Offset pagination (OFFSET ... LIMIT) slows down on deep pages and shows duplicates or gaps when rows are inserted or deleted between requests. Keyset (cursor) pagination solves both. Principle Order by a unique, stable key and fetch rows after the last row the client received: SELECT id, title, created_at FROM posts WHERE (created_at, id) < (:lastCreatedAt, :lastId) -- row-value comparison (PostgreSQL, MySQL 8) ORDER BY created_at DESC, id DESC LIMIT :size; Index: CREATE INDEX idx_posts_created_id ON posts (created_at DESC, id DESC); The database seeks directly to the position, so every page costs about the same. Spring Data JPA implementation Option 1 — Spring Data's built-in scrolling (Spring Data 3.1+): Window<Post> window = postRepository.findFirst20ByOrderByCreatedAtDescIdDesc( ScrollPosition.keyset()); // next page: window.positionAt(window.size() - 1), passed back into the same repository method Option 2 — explicit JPQL query: @Query(""" select p from Post p where p.createdAt < :createdAt or (p.createdAt = :createdAt and p.id < :id) order by p.createdAt desc, p.id desc """) List<Post> nextPage(@Param("createdAt") Instant createdAt, @Param("id") long id, Limit limit); (Limit is supported in Spring Data 3.2+; otherwise use Pageable.ofSize(n) with a query that has no OFFSET.) API design - Encode the cursor (createdAt and id of the last item) as an opaque Base64 string; sign it (HMAC) if clients must not tamper with it. - Response: { items: [...], nextCursor: "..." }, with nextCursor null at the end. Fetch size + 1 rows to know whether more exist. - Validate page size with a maximum. - Filters must remain the same between pages; include them in the cursor or validate them. Trade-offs - No random access to page 37 and no cheap total count — usually fine for feeds, timelines, infinite scroll and APIs. - Sort keys should be immutable (creation time, ID). If the sort column can change, items may move between pages. - Each sort order needs its own cursor format and index, always with a unique tie-breaker column. - Clients can use the cursor for "load more" and for incremental sync (fetching items newer than the newest seen).
Ravindra Wadile · · 0 likes