Why does OFFSET pagination degrade at scale and how does keyset (cursor) pagination fix it?
Quick Summary: OFFSET N forces the database to read, sort, and discard all N preceding rows linearly O(N); Keyset (cursor) pagination seeks directly via a tuple comparison WHERE (created_at, id) < (:ts, :id) using a composite B-Tree index in constant O(log n) time.
Direct Interview Answer
When users browse page 5,000 with LIMIT 20 OFFSET 100000, SQL engines scan and throw away 100,000 rows on every request—causing latency spikes and duplicate/skipped records if rows insert while paging.
Keyset pagination passes the last seen (created_at, id) cursor cleanly to seek directly into the B-Tree index.
Detailed Technical Explanation
Include a unique tie-breaker column like id alongside created_at inside both the tuple comparison and the supporting index so identical timestamps never drop rows across page boundaries.
Practical Walkthrough
Constant-time keyset pagination SQL query with deterministic tie-breaker.
CREATE INDEX idx_jobs_pub_id ON jobs (published_at DESC, id DESC);
SELECT id, title, published_at
FROM jobs
WHERE (published_at, id) < ('2026-12-01 10:00:00', 8450)
ORDER BY published_at DESC, id DESC
LIMIT 20;
Instant Index Scan jumping directly to row 8450 at constant latency.
Real-World Production Use Case
Job boards, infinite-scroll activity feeds, and multi-million-row fintech audit transaction ledgers.
Common Interview Mistakes to Avoid
- Ordering only by non-unique timestamp without an id tie-breaker, dropping rows with identical timestamps.
- Expecting keyset pagination for random arbitrary jumps like "Go directly to Page 47".