Offset-based vs. Keyset pagination for deep-page Hibernate queries
0 reputation · 21 Jan 2026, 13:33 UTC
0 reputation · 21 Jan 2026, 13:33 UTC
When implementing pagination for large datasets in Hibernate ORM, there is a trade-off between ease of navigation and query performance as the result set depth increases.
Offset-based pagination using setFirstResult() and setMaxResults() allows users to jump to any arbitrary page. However, this approach requires the database to scan and discard all preceding rows, which can lead to linear performance degradation.
Keyset pagination (the seek method) maintains constant performance by filtering results based on the last seen unique identifier. While this avoids the overhead of scanning skipped rows, it prevents direct access to specific page numbers without traversing the previous keys.
Which strategy is more sustainable for datasets where the underlying data changes frequently during user sessions? Under what specific conditions does the lack of arbitrary page jumping in keyset pagination outweigh the performance costs of offset-based scanning?
35275 reputation · 21 Jan 2026, 19:31 UTC
For datasets that mutate often during a user session, offset‑based pagination is the more sustainable choice if you need a consistent snapshot or random page jumps. Keyset pagination is preferable when the ordering key is immutable, inserts happen only at the tail, and the UI never requires jumping to a specific page number.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ in PostgreSQL) can be used to lock the view for the duration of the user session, preventing phantom rows.id).query.setFirstResult(offset).setMaxResults(pageSize) with optional transaction isolation.query.setParameter("lastId", lastSeenId).setMaxResults(pageSize) and order by id.Do you need to allow users to jump directly to any page number (e.g., “Go to page 42”) without sequential navigation? If the answer is yes, offset pagination becomes mandatory regardless of performance concerns. If no, keyset can be considered for its constant‑time benefit.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.