Quick revision
The short answer
OFFSET paging makes the database read and throw away every row before the requested page, so page 100,000 reads millions of rows, and Page also runs an expensive count over 50 million rows. We redesign it as keyset paging: remember the last row's created_at and id and ask for rows after it with WHERE (created_at, id) < (:lastCreatedAt, :lastId), backed by a matching index, which Spring Data supports through scrolling with Window and KeysetScrollPosition since 3.1. We use Slice or an estimated count instead of an exact total, and agree with the users that jumping to an arbitrary page number goes away.
What to remember
In this answer, we saw that OFFSET paging reads and discards every earlier row, so deep pages cost millions of reads, and that Page adds a full count on every request. Keyset paging seeks past the last row with WHERE (created_at, id) < (:lastCreatedAt, :lastId) on a matching index, so every page costs the same, and Spring Data supports it through Window and KeysetScrollPosition. Slice or an estimated count replaces the exact total, and filters plus Next and Previous replace jumping to arbitrary pages.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
OFFSET paging makes the database read and throw away every row before the requested page, so page 100,000 reads millions of rows, and Page also runs an expensive count over 50 million rows. We redesign it as keyset paging: remember the last row's created_at and id and ask for rows after it with WHERE (created_at, id) < (:lastCreatedAt, :lastId), backed by a matching index, which Spring Data supports through scrolling with Window and KeysetScrollPosition since 3.1. We use Slice or an estimated count instead of an exact total, and agree with the users that jumping to an arbitrary page number goes away.
Why this question is asked
Paging looks like a solved problem: Spring Data gives us Pageable, a page number and a size, and it works perfectly on small tables. On a table with 50 million audit rows, the first pages are fast and the deep ones take more than 10 seconds, because of how OFFSET works. Interviewers ask this to see whether we understand the cost model behind paging and can change both the query and the user experience. In this answer, we will see why OFFSET gets slower with depth, why the count is expensive, how keyset paging works, how to use it in Spring Data, and what changes for the user.
1Why OFFSET Gets Slower With Depth
Pageable becomes SQL with LIMIT and OFFSET. Page 0 with size 50 is LIMIT 50 OFFSET 0; page 200,000 is LIMIT 50 OFFSET 10,000,000. The database cannot jump to row 10 million, because rows have no fixed position. It has to produce the rows in order and count them, walking 10,000,050 index entries and fetching their rows, only to discard the first 10 million. So the cost grows linearly with the page number.
| Request | OFFSET paging | Keyset paging |
|---|---|---|
| first page | 50 rows read | 50 rows read |
| page 1,000 | 50,050 rows read | 50 rows read |
| page 200,000 | 10,000,050 rows read | 50 rows read |
| total count | full count every request | not needed (Slice or estimate) |
And there is a second query. A Page carries the total number of elements, so Spring Data also runs a count query. In PostgreSQL, count(*) on 50 million rows has to visit every row or index entry visible to the transaction, which takes seconds on its own, on every page request.
2How Keyset Paging Works
Keyset paging, also called seek paging, does not count rows to skip. Instead, the client remembers the sort values of the last row it saw and asks for rows that come after it. Because created_at may not be unique, we add the id as a tie-breaker, so the sort order is total and no row is skipped or repeated.
Notice the row value comparison (created_at, id) < (..., ...). It compares created_at first and uses id only when created_at is equal, which is exactly the sort order. With the matching index, the database starts reading at that point in the index and stops after 50 rows, whatever the depth. The index must match the ORDER BY, including the direction and the tie-breaker column, or the database will sort millions of rows instead.
3Keyset Paging in Spring Data
Since Spring Data 3.1, repositories support scrolling. A query method returns a Window, which holds the results and can produce the position to continue from, and takes a ScrollPosition. ScrollPosition.keyset() starts from the beginning, and the Window gives the next keyset position built from the last row's sort values.
For a web API, the position is sent to the client as an opaque cursor, for example the last created_at and id encoded in Base64, and the client sends it back for the next page. This keeps the server stateless. The exact SQL Spring Data generates for the keyset condition may differ from the row value form above, so we check the logged SQL and the plan; check your version.
4Dropping the Exact Count
Even with fast pages, a total count of 50 million rows on every request is expensive. If the screen only needs Next and Previous, Spring Data's Slice returns a page of results and whether there is a next one, by fetching one extra row, with no count query. If the screen must show a total, an estimate is usually enough: PostgreSQL keeps an approximate row count in pg_class.reltuples, or EXPLAIN's estimated rows for a filtered query, and showing about 50 million records is honest and instant. An exact count can be computed occasionally and cached.
5Changing the User Experience
Keyset paging has one real limitation: it cannot jump to page 7,342, because there is no row number to seek to. For an audit admin screen, that is rarely a loss. Nobody browses to the middle of 50 million records; people look for something. So we replace page numbers with Next and Previous, and add filters that take them where they want to go: a date range, a user, an action type. A date jump works well with keyset paging, because starting at a date is just another seek position.
This is a product decision as well as a technical one, so we show the users the new screen early. In practice, deep pages were usually a workaround for missing filters, and the redesign makes the screen both faster and more useful.
- Request has a cursor?YesDecode last created_at and idNoStart from the newest row or a chosen date
- Seek with WHERE (created_at, id) < cursorindex range scan, LIMIT 51
- Got 51 rows?YesReturn 50 and a next cursorNoReturn the rows, no next page
3 steps in order. Play them, or step through them one at a time.
6Follow-up questions
How does Previous work with keyset paging?
We seek in the opposite direction: rows greater than the first row on the current page, ordered ascending, with the same LIMIT, and then reverse them for display. The same index serves both directions, because a B-tree can be scanned backwards.
What happens if rows are inserted while the user pages?
Keyset paging is stable: new rows above the cursor do not shift the next page, so nothing is skipped or shown twice. With OFFSET, an insert at the top pushes every row down by one, so the next page repeats a row.
Can we still use filters with keyset paging?
Yes, the filter conditions are added to the WHERE clause, and the index should start with the equality filter columns, for example (user_id, created_at, id), so the seek stays a range scan inside that user's rows.
7Conclusion
In this answer, we saw that OFFSET paging reads and discards every earlier row, so deep pages cost millions of reads, and that Page adds a full count on every request. Keyset paging seeks past the last row with WHERE (created_at, id) < (:lastCreatedAt, :lastId) on a matching index, so every page costs the same, and Spring Data supports it through Window and KeysetScrollPosition. Slice or an estimated count replaces the exact total, and filters plus Next and Previous replace jumping to arbitrary pages.
Open with
Deep pages are slow because Pageable becomes OFFSET, and the database has to read and throw away every row before the page, so page 200,000 of 50 reads ten million rows.
Then, if they want more
Page also triggers a count query, which on 50 million rows is several seconds by itself. I would switch to keyset paging.
We sort by created_at descending with id as a tie-breaker, add an index on created_at desc and id desc, and for the next page we ask for rows where created_at and id, as a row value, are less than the last row's values, with a limit.
The database seeks straight to that point in the index, so every page reads about 50 rows no matter how deep it is.
In Spring Data 3.1 and later I can do this with a query method that returns a Window and takes a ScrollPosition, starting from ScrollPosition.keyset() and continuing from the position of the last element, and I would send that position to the client as an opaque cursor.
I would also drop the exact total: use Slice, which just fetches one extra row to know if there is a next page, or show an estimated count. The trade-off is that users cannot jump to an arbitrary page number, so I would discuss replacing page numbers with Next, Previous and filters such as a date range.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An admin screen pages through 50 million audit records with Spring Data Pageable sorted...": https://scrivio-interview-library.netlify.app/databases/database-scaling/7761328259/