Pagination: Cursor vs Offset
Comparing Offset pagination (skipping N rows) against Cursor/Keyset pagination (seeking from the last item's indexed key) for scale and consistency
Table of Contents
Structure Diagram
Random page jump · Slows at depth
- DB CostScans & discards N skipped rows O(N)
- Live InsertsCauses duplicate or skipped items
- Best UI FitAdmin tables with page numbers
Steady O(log N) · Feed-consistent
- DB CostIndex seek via WHERE id < cursor
- Live InsertsNo duplicates/skips on live inserts
- Best UI FitInfinite scroll, feeds, public APIs
What is Pagination: Cursor vs Offset?
Comparing Offset pagination (skipping N rows) against Cursor/Keyset pagination (seeking from the last item's indexed key) for scale and consistency. It is a core concept in APIs & Networking within Web Dev.
Core Principles
Offset pagination (LIMIT 20 OFFSET 10000) skips a fixed number of rows from the start, while Cursor (Keyset) pagination uses an indexed bookmark from the last returned item (WHERE (created_at, id) < (?, ?) LIMIT 20) to seek directly to the next slice.
Offset queries degrade linearly at deep pages because the database still scans and discards skipped rows, and live inserts shift row positions—causing duplicates or skipped items. Cursor pagination maintains steady O(log N) index performance and stable results under concurrent writes.
Practical Takeaways
- Include a unique tie-breaker and opaque encoding: Timestamps alone can collide. Pair
(created_at, id)in a composite index and Base64-encode the cursor so clients treat it as an opaque token. - Avoid expensive
COUNT(*)with theLIMIT + 1trick: Fetch one extra row beyond the page size; if it exists, sethasNextPage: trueand trim the extra item before returning. - Offset still has a place: For small admin tables where users must jump directly to page 5, offset pagination remains simple and practical.
Notable Examples
- Stripe, Slack, and GitHub APIs: Standardize on cursor tokens (
starting_after,next_cursor) for scalable list endpoints. - GraphQL Relay Connections: Formalizes
edgesandpageInfo { endCursor, hasNextPage }across clients.