Cursor vs Offset Pagination in Spring Boot
Pagination is one of the first things we implement in a Spring Boot API, usually with a simple Pageable. It works perfectly for the first few thousand rows. But once your database grows, offset pagination starts timing out, and users complain about seeing the same item twice as they scroll.
This guide compares offset pagination and cursor-based (keyset) pagination. You’ll see why offset queries slow down at scale, why they return duplicate rows when data changes, and how to implement a fast, stable cursor-based approach using Spring Data JPA.
How Offset Pagination Works (And Why It Fails)
Offset pagination is what Spring Data gives you out of the box when you use Pageable:
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize, Sort.by("id"));
Page<Post> posts = postRepository.findAll(pageRequest);
Under the hood, the database translates this into a SQL query using LIMIT and OFFSET:
SELECT * FROM post ORDER BY id LIMIT 10 OFFSET 10000;
This approach has two critical flaws at scale.
1. Performance degrades linearly
To return page 1,000, the database cannot just jump to row 10,000. It must read the first 10,000 rows, discard them, and then return the 10 you asked for. The deeper the page, the slower the query. At a million rows, an OFFSET query can easily take several seconds and spike CPU usage.
2. The "shifting window" problem
If a new post is inserted while a user is scrolling, the entire dataset shifts down by one row. When the user requests page 2, the database applies the offset again, and the last item from page 1 appears again at the top of page 2. Conversely, if a row is deleted, an item is skipped entirely.
How Cursor-Based Pagination Works
Cursor-based pagination (often called keyset pagination) solves both problems by abandoning the OFFSET keyword entirely.
Instead of asking for "the next 10 rows after skipping 10,000," you ask for "the next 10 rows where the ID is greater than the last ID I saw."
SELECT * FROM post WHERE id > 10500 ORDER BY id LIMIT 10;
Because id is indexed, the database finds the starting point instantly and reads the next 10 rows. It doesn’t scan or discard anything. This runs in constant time, whether you are on page 2 or page 100,000.
Additionally, because it relies on a fixed value (id > 10500), inserting or deleting rows does not cause duplicates or skipped items. The cursor acts as an anchor.
Implementing Cursor Pagination in Spring Boot
While Spring Data JPA’s Pageable is designed for offsets, you can easily implement cursor pagination using a custom query and Spring Data’s Slice.
The Repository
First, define a query that accepts the last seen cursor (in this case, the last post ID).
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface PostRepository extends JpaRepository<Post, Long> {
@Query("SELECT p FROM Post p WHERE p.id > :lastId ORDER BY p.id ASC")
Slice<Post> findNextPage(@Param("lastId") Long lastId, Pageable pageable);
}
Why Slice and not Page? A Page triggers an additional COUNT(*) query to figure out the total number of pages. On a table with millions of rows, that COUNT query is just as slow as the offset query you are trying to escape. A Slice simply fetches pageSize + 1 rows to check if a next page exists, without the expensive count.
The Service
In the service layer, fetch the data and determine the new cursor to return to the client.
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PostService {
private final PostRepository postRepository;
public PostService(PostRepository postRepository) {
this.postRepository = postRepository;
}
public CursorResponse<Post> getPosts(Long cursor, int size) {
// If no cursor is provided, start from the beginning
Long lastId = (cursor != null) ? cursor : 0L;
// Request size + 1 to see if there's a next page
PageRequest pageRequest = PageRequest.of(0, size);
Slice<Post> slice = postRepository.findNextPage(lastId, pageRequest);
List<Post> posts = slice.getContent();
// The next cursor is the ID of the last item in the current list
Long nextCursor = posts.isEmpty() ? null : posts.get(posts.size() - 1).getId();
return new CursorResponse<>(posts, nextCursor, slice.hasNext());
}
}
The API Response
Instead of returning page numbers, the API returns the array of items and the cursor to pass for the next request.
public record CursorResponse<T>(List<T> data, Long nextCursor, boolean hasNext) {}
The client calls your endpoint like this:
- First request:
GET /api/posts?size=10 - Next request:
GET /api/posts?size=10&cursor=10500
Offset vs. Cursor: Comparison Table
| Feature | Offset Pagination | Cursor Pagination |
|---|---|---|
| Database Performance | Slow on deep pages (scans discarded rows) | Fast everywhere (index range scan) |
| Data Consistency | Duplicates/skips when rows are inserted/deleted | Stable; no duplicates or skips |
| Jump to Page N | Easy (page=5) |
Impossible (must traverse sequentially) |
| Total Count | Easy (totalElements) |
Expensive (requires separate COUNT query) |
| Best For | Admin panels, small datasets | Infinite scroll, public feeds, large datasets |
What to Watch Out For
- The sort key must be unique. If you paginate by a timestamp (
createdAt) and two posts share the exact same millisecond, the database might skip one. Use a composite cursor (e.g.,WHERE createdAt = :date AND id > :id) or paginate by the primary key. - Cursor pagination doesn’t support random access. You cannot jump directly to page 50. If your UI requires a numbered pagination bar (
1 2 3 ... 50), cursor pagination is the wrong tool. - API backward compatibility. If you are converting an existing API from offset to cursor, you will need to introduce a new endpoint (e.g.,
/api/posts/cursor) or version the API, as the response shape and parameters change. - Sorting must match the cursor. If you return results ordered by
id ASC, the cursor query must also useid ASCandid > :lastId. Mixing directions (or usingDESCwith>) will break the logic.
Conclusion
Offset pagination is easy to write, but it’s a ticking time bomb for large datasets. It slows down the database and frustrates users with duplicate rows.
Cursor-based pagination fixes this by using an indexed value as a bookmark. By replacing Page with Slice and using a WHERE id > :lastId query, you get constant-time performance that scales to millions of rows. Use cursor pagination for infinite scrolls and public APIs, and keep offset pagination for admin dashboards where users need to jump to specific pages.
Comments
Post a Comment