patternModerate
REST API pagination — cursor-based vs offset-based
Viewed 0 times
cursor paginationoffset paginationLIMIT OFFSETnext_cursorkeyset pagination
Problem
Offset-based pagination (LIMIT/OFFSET) gets slow on large datasets and produces inconsistent results when data changes between pages.
Solution
Use cursor-based for large/changing datasets. Client sends ?cursor=abc123&limit=20 where cursor encodes last item's sort key. Query: WHERE id > cursor ORDER BY id LIMIT 20. Return next_cursor in response. Advantages: O(1) performance, stable results. Keep offset for small, stable datasets where page N of M UX is needed.
Why
OFFSET N tells the database to fetch and discard N rows. At OFFSET 1000000, it processes a million rows. Cursor-based uses indexed WHERE clause, making every page equally fast.
Revisions (0)
No revisions yet.