Quick revision
The short answer
OFFSET makes the database read and throw away every row before the requested page, so page 5000 of size 50 reads 250,050 rows to return 50, and concurrent inserts shift the pages. Keyset pagination instead remembers the last row: WHERE (created_at, id) < (:lastCreatedAt, :lastId) ORDER BY created_at DESC, id DESC LIMIT :size, served by a matching index, so every page costs the same. The API returns an opaque cursor and a next link, Spring Data 3.1+ supports it with Window and ScrollPosition.keyset(), and exact totals are dropped or estimated.
What to remember
In this answer, we saw that OFFSET reads and discards every preceding row, so deep pages on 200 million rows are slow and concurrent inserts shift them. Keyset pagination uses a row comparison on (created_at, id) with a matching index so each page costs the same. The API hands out an opaque cursor and a next link, Spring Data's Window and ScrollPosition implement it, and exact totals are replaced by omitted, capped or estimated counts.
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 makes the database read and throw away every row before the requested page, so page 5000 of size 50 reads 250,050 rows to return 50, and concurrent inserts shift the pages. Keyset pagination instead remembers the last row: WHERE (created_at, id) < (:lastCreatedAt, :lastId) ORDER BY created_at DESC, id DESC LIMIT :size, served by a matching index, so every page costs the same. The API returns an opaque cursor and a next link, Spring Data 3.1+ supports it with Window and ScrollPosition.keyset(), and exact totals are dropped or estimated.
Why this question is asked
Event tables, audit logs and activity feeds grow forever, and an endpoint that was fast at 100,000 rows becomes slow at 200 million without any code change. Interviewers ask this design question because the fix touches SQL, indexing, API shape and Spring Data at once. In this answer, we will see why offset degrades, write the keyset query and its index, design the cursor and response, implement it with Spring Data's scrolling API, and decide what to do about totals.
1Why OFFSET Gets Slower With Every Page
OFFSET 249950 does not mean jump to row 249,950. Databases cannot know which row is at that position without producing all the rows before it in the requested order. So even with an index on created_at, the database walks the index, fetches and counts 249,950 rows, discards them, and then returns the next 50. The cost of a page grows linearly with its number: page 1 reads 50 rows, page 5000 reads 250,050.
Offset has a correctness problem too. Events keep arriving while a client pages. Every new event at the top pushes every row down by one, so the client sees the last row of the previous page again, or misses rows when old ones are deleted.
| Page | OFFSET pagination | Keyset pagination |
|---|---|---|
| 1 | 50 | 50 |
| 100 | 5,000 | 50 |
| 5,000 | 250,050 | 50 |
| 100,000 | 5,000,050 | 50 |
2The Keyset Query and Its Index
Keyset pagination, also called seek or cursor pagination, uses the sort values of the last row the client received as the starting point. Because created_at is not unique, we add id as a tiebreaker so the order is total, and we compare both together.
The row comparison (created_at, id) < (a, b) means created_at < a, or created_at = a and id < b, which is exactly the position after the last row in our order. PostgreSQL uses the index for it, jumping straight to that position and reading 51 entries. If a database handles row comparisons poorly, we write the expanded form with OR. Reading one extra row is a cheap way to know whether to return a next cursor.
3Designing the Cursor and the Response
The client should not build the WHERE clause itself. We give it an opaque cursor: a string it stores and sends back but does not interpret. Inside, it holds the last row's sort values, encoded for example as base64url of a small JSON object. Opaque cursors let us change the encoding later, and we can sign them with an HMAC if we do not want clients to tamper with them.
The trade-off is visible in the API: clients can go to the next page, and to the previous one if we also return a backwards cursor, but they cannot jump to page 5000. For feeds, logs and synchronisation that is fine, because nobody reads page 5000 by number; it was only ever reached by clicking next.
4Implementing It With Spring Data
Spring Data 3.1 added a scrolling API that generates keyset queries for us. A repository method takes a ScrollPosition and returns a Window, a slice of results that knows the position of each element.
9 messages in order. Play them, or step through them one at a time.
ScrollPosition.keyset() means start from the beginning. The keys of the last position are exactly what we encode into the cursor, and ScrollPosition.forward rebuilds the position from a decoded cursor. Spring Data adds the WHERE clause on the sort properties; we still create the index ourselves, and we check the generated SQL once to be sure it uses it.
5What About the Total Count?
Clients often ask for a total, but an exact SELECT count(*) on 200 million rows has to visit every row or every index entry, which can take longer than the page itself. With filters it is even worse. So the endpoint omits the total by default. If a screen really needs a number, we offer an estimate, for example PostgreSQL's planner statistics (reltuples in pg_class for a whole table, or the row estimate from EXPLAIN for a filtered query), and label it approximate, or we count only up to a cap such as 10,000 and report more than 10,000.
6Follow-up questions
How do you support sorting by a non-unique column with keyset pagination?
We always append a unique, immutable column, usually the primary key, as the last sort key, both in ORDER BY and in the row comparison, and include it in the cursor. The index must contain the same columns in the same order and direction, for example (status, created_at DESC, id DESC). Without the tiebreaker, rows that tie on the last cursor value would be skipped or repeated.
What happens to the cursor if the sort order changes between requests?
A cursor only makes sense for the order it was created in, because it holds values of specific sort columns. So the cursor encodes the sort it belongs to, and if a request arrives with a cursor and a different sort parameter, the server rejects it with 400 and the client starts again from the first page. Silently applying the cursor to another order would return nonsense.
Can keyset pagination go backwards?
Yes. For a previous page we reverse the comparison and the ORDER BY, read the rows, and reverse them again before returning. Spring Data supports this through the direction of a keyset position, for example ScrollPosition.backward.
7Conclusion
In this answer, we saw that OFFSET reads and discards every preceding row, so deep pages on 200 million rows are slow and concurrent inserts shift them. Keyset pagination uses a row comparison on (created_at, id) with a matching index so each page costs the same. The API hands out an opaque cursor and a next link, Spring Data's Window and ScrollPosition implement it, and exact totals are replaced by omitted, capped or estimated counts.
Open with
Offset pagination degrades because OFFSET means the database must produce and throw away every preceding row in sort order, so page 5000 with size 50 touches about 250,000 rows to return 50, and the cost grows with the page number.
Then, if they want more
It also shifts pages when new events arrive. I would switch to keyset pagination. The order is created_at descending with id as a tiebreaker, with an index on created_at desc, id desc. The first page is ORDER BY those columns LIMIT 51, using the extra row to know if there is a next page.
The next page is WHERE created_at, id is less than the last row's values, same ORDER BY and LIMIT, so the database seeks into the index and reads only 51 entries for any page.
The API returns an opaque cursor, base64 of the last row's sort values, possibly signed, plus a next link, and clients can no longer jump to arbitrary pages, which is fine for an event feed. In Spring Data 3.1 and later I can implement it with a repository method that takes a ScrollPosition and returns a Window, starting with ScrollPosition.keyset.
Finally, I would not return an exact total count on 200 million rows; I would omit it or offer an estimate.
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 Framework reference, Spring Web MVC
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 endpoint GET /events?page=5000&size=50 on a table with 200 million rows has become...": https://scrivio-interview-library.netlify.app/spring-boot/rest-api-design/33e4f131b6/