How to Use Vaadin Grid With Lazy Loading for Large Data
Load a Vaadin Grid page by page from a database with a callback data provider, add sorting and filtering, and avoid loading every row into memory.

A Vaadin Grid given a List holds every item in the server's memory, for every user who opens the view. At a few hundred rows that is fine. At fifty thousand it is a memory problem multiplied by your concurrent users, and the first symptom is a slow page, not an error. The fix is a data provider that loads only the rows the user can see, a window at a time, as the grid scrolls. This post builds one with the callback API on Vaadin 25, Spring Boot 4 and Spring Data JPA, adds sorting and a filter, discusses the count query, and says what the database must do to keep up. The server-side model that makes this matter is explained in how Vaadin Flow works.
The callback
@Route("orders")
class OrderGridView extends VerticalLayout {
OrderGridView(OrderService orders) {
var grid = new Grid<OrderRow>(OrderRow.class, false);
grid.addColumn(OrderRow::number).setHeader("Number").setSortProperty("number");
grid.addColumn(OrderRow::customer).setHeader("Customer").setSortProperty("customer");
grid.addColumn(OrderRow::total).setHeader("Total").setSortProperty("total");
grid.setItems(query -> orders.page(query.getOffset(), query.getLimit()).stream());
setSizeFull();
add(grid);
}
}grid.setItems(CallbackDataProvider.FetchCallback) registers a function that Vaadin calls whenever the grid needs rows. The query object carries getOffset() and getLimit(): the index of the first row wanted and the number of rows, typically a page of about fifty items around the visible area. The callback returns a Stream of exactly the items in that window. The grid keeps those in memory and asks for more as the user scrolls; rows far from the viewport are discarded. A table of ten million rows costs the same memory as a table of a hundred.
Because the grid asks by offset and limit, the repository has to answer in the same terms. With Spring Data, translate to a page:
List<OrderRow> page(int offset, int limit) {
int pageNumber = offset / limit;
return repository.findAllBy(PageRequest.of(pageNumber, limit)).getContent();
}This works when the offset is a multiple of the limit, which it usually is. Vaadin also offers query.getPage() and query.getPageSize(), with the same rule, and a VaadinSpringDataHelpers class that converts the query into a Pageable including the sort. Using it avoids the arithmetic: repository.findAll(VaadinSpringDataHelpers.toSpringPageRequest(query)).stream(). For an arbitrary offset that is not a multiple of the page size, the plain arithmetic above returns the wrong rows, so use the helper or a query with OFFSET and LIMIT.
Project to a row type, as in OrderRow, a record with only the displayed columns, instead of loading full entities with their relationships. The grid does not need the order lines, and loading them multiplies the cost of every page. See projections for the technique.
Add sorting
When the user clicks a header, Vaadin passes the sort order in the query. The callback must apply it, or the column will appear to sort and do nothing:
grid.setItems(query -> {
Sort sort = Sort.by(query.getSortOrders().stream()
.map(o -> o.getDirection() == SortDirection.ASCENDING
? Sort.Order.asc(o.getSorted()) : Sort.Order.desc(o.getSorted()))
.toList());
return orders.page(query.getOffset(), query.getLimit(), sort).stream();
});setSortProperty("number") on each column names the property sent back in getSorted(). The callback maps that name to a database column. Never concatenate that string into SQL: it comes from the client, and a tampered request can send anything. Whitelist the allowed names (a map from property to column) or pass it to Spring Data, which rejects unknown properties. The risk is the same as in any dynamic ORDER BY, covered in preventing SQL injection.
Sort by a column that is indexed. A sort on an unindexed column makes the database sort the full table for each page request, and the grid feels slow however clever the Java is.
Add a filter
A text field above the grid narrows the rows. The callback reads the current filter value, and the grid is told to reload when it changes:
var filter = new TextField();
filter.setPlaceholder("Filter by customer");
filter.setValueChangeMode(ValueChangeMode.LAZY);
filter.addValueChangeListener(e -> grid.getDataProvider().refreshAll());
grid.setItems(query -> orders.search(filter.getValue(), query.getOffset(), query.getLimit()).stream());ValueChangeMode.LAZY waits a short time after the last keystroke before sending the value, so typing "smith" triggers one query, not five. The more idiomatic form uses a typed filter object with setItems(DataProvider). DataProvider.fromFilteringCallbacks(fetch, count) plus withConfigurableFilter() gives a ConfigurableFilterDataProvider where you call setFilter(text), and the framework reloads for you; it keeps the filter out of the lambda's closure and works better with several grids. Whichever you choose, escape % and _ in the filter if the query uses LIKE, and cap its length.
Count or no count
The grid needs to know how many rows exist to size the scrollbar. The one-argument setItems(FetchCallback) form has no count callback, so the grid starts with an estimate and extends it as the user scrolls and the callback keeps returning full pages; when a page comes back short, the grid knows the end. That avoids a select count(*), which on a big table with a filter can cost more than the page query itself. The scrollbar then jumps when the estimate grows, which is acceptable for a feed and awkward for a report. If you want an exact size, supply a count callback:
grid.setItems(
query -> orders.search(filter.getValue(), query.getOffset(), query.getLimit()).stream(),
query -> (int) orders.count(filter.getValue()));Cache the count, or make it approximate, if it is slow: some databases offer estimated row counts from statistics, and for an unfiltered table an estimate is usually enough.
Database matters
Lazy loading moves the work to the database, so the database must cope. OFFSET pagination gets slower as the offset grows, because the database walks past all earlier rows: page 10,000 reads 500,000 rows to return fifty. For a grid that users scroll deeply, switch to keyset pagination (where id > :lastId order by id limit 50), which keeps the cost flat, at the price of tracking the last key and limiting random jumps. For most business grids, users filter before they scroll, and offset paging is fine.
Index the columns used for sorting and filtering, and check the plans with EXPLAIN. Watch for the query count: a lazy loaded relationship in the row type triggers a query per row, the classic N+1 problem; fetch what the columns need in the same statement. The connection setup from plain JDBC is in the JDBC tutorial if you use it directly.
Where this does not apply
For small, bounded lists, such as the countries or a user's ten recent items, setItems(List) is simpler and fast, and it allows in-memory sorting and filtering with no database round trip. Lazy loading also trades server memory for database load, so a grid opened by thousands of users each issuing queries on every scroll needs a database sized for it. The component reference is the Grid documentation, and the data provider API is described in binding data. To build the first view, see the Vaadin tutorial.


