Quick revision
The short answer
Declare Window<Post> findFirst20ByOrderByCreatedAtDescIdDesc(ScrollPosition position) in the repository (Spring Data 3.1+), call it first with ScrollPosition.keyset(), and for each following call pass window.positionAt(window.size() - 1), the keyset position of the last row, while window.hasNext() says whether more data exists. Spring Data turns the position into where conditions on the last row's createdAt and id, so the database never skips rows with a large offset. The sort must be deterministic, which is why id, a unique column, is part of it.
What to remember
In this answer, we saw that keyset pagination remembers the last row's sort values and asks for rows after them, so every page costs the same and new rows do not cause duplicates. In Spring Data 3.1 and later, a method returning Window<Post> and taking a ScrollPosition implements it: we start with ScrollPosition.keyset(), continue with window.positionAt(window.size() - 1) while window.hasNext() is true, and rely on a deterministic sort ending in id, backed by a matching index.
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.
Declare Window<Post> findFirst20ByOrderByCreatedAtDescIdDesc(ScrollPosition position) in the repository (Spring Data 3.1+), call it first with ScrollPosition.keyset(), and for each following call pass window.positionAt(window.size() - 1), the keyset position of the last row, while window.hasNext() says whether more data exists. Spring Data turns the position into where conditions on the last row's createdAt and id, so the database never skips rows with a large offset. The sort must be deterministic, which is why id, a unique column, is part of it.
Why this question is asked
Feeds, timelines and activity logs are read by scrolling: newest first, twenty at a time, and some users scroll a long way. Offset paging gets slower with every page and shows duplicates when new posts arrive. Keyset pagination fixes both, and Spring Data 3.1 added a built-in API for it. Interviewers ask this to see whether we can implement it correctly, which means getting the sort, the position handling and the index right, and whether we understand why it is faster. In this answer, we will recap the problem with offsets, see how keyset pagination works, write the repository method and the calling code, look at the SQL, and cover deterministic sorting and the index that makes it fast.
1A Quick Recap: Why Offsets Hurt Feeds
Offset paging asks the database to skip a number of rows and return the next few. Page 500 of size 20 means skip 9,980 rows. The database cannot jump to row 9,981; it must find and discard all the rows before it, so each page is slower than the last.
Offsets also shift. If five new posts arrive while a user reads page 1, page 2 now starts five rows earlier, and the user sees five posts again. Keyset pagination, also called seek or cursor pagination, avoids both problems by remembering the last row we showed and asking for rows that come after it in the sort order.
2How Keyset Pagination Works
Suppose the feed is sorted by createdAt descending, newest first. The last post on page 1 was created at 10:15:00 with id 812. The next page is every post that comes after it in that order: created earlier than 10:15:00, or created at exactly 10:15:00 with a smaller id. The id comparison is needed because two posts can share a timestamp, and without it we would skip or repeat them.
With an index on (created_at, id), the database jumps straight to that point in the index and reads the next 21 entries. The cost is the same for page 1 and page 10,000.
- First call: ScrollPosition.keyset()No condition; newest 20 posts
- Remember the last row's keys
createdAt= 10:15:00, id = 812 - Next call: position of the last rowwhere (created_at, id) < (10:15:00, 812)
- window.hasNext()?YesRepeat with the new last rowNoEnd of feed
4 steps in order. Play them, or step through them one at a time.
Each request starts right after the last row the client saw.
3The Repository Method
Spring Data 3.1 introduced Window<T>, a slice of results that also knows how to produce the position for the next request, and ScrollPosition, which describes where to start. A derived method returns Window and takes a ScrollPosition; the limit comes from First20 and the sort from OrderBy.
Notice the sort: CreatedAtDesc followed by IdDesc. createdAt alone is not unique, so it does not define a single order; adding id, which is unique, makes the order deterministic and gives the keyset a tie-breaker.
4Calling It Page by Page
The first call uses ScrollPosition.keyset(), an initial keyset position with no values. Each following call uses the position of the last element of the previous window. window.positionAt(index) returns the scroll position for the element at that index; for keyset scrolling it holds that element's sort values.
In a web API, the client cannot hold a ScrollPosition object, so we send it the keys. A KeysetScrollPosition exposes them through getKeys(), a map such as {createdAt=2026-11-05T10:15:00Z, id=812}. We encode that as an opaque cursor string, and on the next request decode it and rebuild the position with ScrollPosition.forward(keys). Never trust a cursor blindly; validate its fields like any other input.
5The SQL It Produces
Here is roughly what runs for the first and second calls on PostgreSQL with Hibernate 6. Spring Data expands the keyset into explicit or conditions, which every database understands.
Notice the extra row again: like a Slice, Window asks for one more row than it returns to set hasNext(). There is no count query and no offset.
6Deterministic Sorting and the Index
The sort must be deterministic, meaning no two rows can tie on every sort column. If we sort only by createdAt and 30 posts share the timestamp 10:15:00, the condition created_at < 10:15:00 skips the ones that did not fit on the previous page, and they are never shown. Ending the sort with a unique column, usually the primary key, removes the ties.
The index must match the sort. An index on (created_at desc, id desc), or on (created_at, id), which PostgreSQL can read backwards, lets the database start at the position and read 21 entries. Without it, the query sorts the whole table each time and loses the benefit. With filters, such as one author's feed, put the equality column first: (author_id, created_at, id).
7Follow-up questions
Can keyset pagination jump to page 50?
No. It can only move forward or backward from a known position, which is why it suits feeds and infinite scroll rather than numbered pages. If the product needs page numbers, use offset paging for shallow pages, or limit how deep users can jump.
What does ScrollPosition.offset() do?
It is offset-based scrolling with the same Window API, so code can switch between offset and keyset positions. It still has the cost of large offsets, so for deep feeds keyset is the better choice.
What happens if the row at the cursor is deleted?
Nothing breaks. The cursor holds values, not a row reference, so the next query simply returns rows after those values. That is another advantage over offsets, which shift when rows are deleted.
8Conclusion
In this answer, we saw that keyset pagination remembers the last row's sort values and asks for rows after them, so every page costs the same and new rows do not cause duplicates. In Spring Data 3.1 and later, a method returning Window<Post> and taking a ScrollPosition implements it: we start with ScrollPosition.keyset(), continue with window.positionAt(window.size() - 1) while window.hasNext() is true, and rely on a deterministic sort ending in id, backed by a matching index.
Open with
In the repository I would declare Window<Post> findFirst20ByOrderByCreatedAtDescIdDesc(ScrollPosition position). Window and ScrollPosition came in Spring Data 3.1. The sort is createdAt descending and then id descending, because createdAt is not unique and keyset pagination needs a deterministic order; the unique id breaks ties.
Then, if they want more
The first call passes ScrollPosition.keyset(), which has no values, so we get the newest twenty posts.
For the next call I take window.positionAt(window.size() minus one), which is a keyset position holding the last post's createdAt and id, and pass it in. window.hasNext() tells me whether to continue, and Spring Data works that out by fetching twenty-one rows, so there is no count.
Under the hood, the position becomes a where clause: created_at less than the last value, or equal with id less than the last id, then the same order by and a limit.
That is why it is fast: there is no offset, so with an index on created_at and id the database seeks straight to the position, and page ten thousand costs the same as page one. It also avoids duplicates when new posts arrive, because we start after a value, not a row count.
In a REST API I would encode the position's keys as an opaque cursor for the client and rebuild it with ScrollPosition.forward on the next request, validating it like any input. WindowIterator can also loop through windows for batch jobs.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6
- 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 "Implement keyset (scrolling) pagination with Spring Data JPA's Window and ScrollPosition...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/fa4fa4fa1a/