Cursor-Based Pagination
What You'll Learn
You'll learn how cursor-based pagination uses opaque tokens to maintain a stable position in result sets, even when underlying data changes during traversal.
The Core Idea
Cursor-based pagination replaces numeric offsets with opaque tokens (cursors) that encode a specific position in the dataset. Instead of saying "skip the first 50 items," you say "continue from this exact point I marked."
Think of it like a bookmark with a unique fingerprint. Rather than remembering "I was on page 10," you mark the exact sentence you stopped at with a code that describes its unique characteristics (timestamp, ID, or combination). Even if someone adds pages before your bookmark, you'll still find your exact spot.
How It Works
When a client requests the first page:
GET /api/posts?limit=20
The API returns results plus a cursor pointing after the last item:
{
"data": [...],
"next_cursor": "eyJpZCI6MTAwLCJ0cyI6MTYzMjg0ODQwMH0="
}
For the next page, the client provides this cursor:
GET /api/posts?limit=20&cursor=eyJpZCI6MTAwLCJ0cyI6MTYzMjg0ODQwMH0=
The cursor typically encodes values like {id: 100, created_at: "2024-01-15T10:30:00"}. The API decodes it and queries: "Give me 20 posts where id > 100 OR (id = 100 AND created_at > ...)"
Why This Beats Offset-Based Pagination
Consistency with changing data: If items are inserted/deleted during pagination, cursors keep you at the logical position. With offsets, you'd skip items or see duplicates.
Performance: No expensive OFFSET 10000 skipping in the database—you query directly from a known position using indexes.
Key Takeaway: Cursor-based pagination uses encoded position markers instead of numeric offsets, ensuring stable, efficient traversal even when the underlying dataset changes between requests.