principleModeratepending
API pagination -- cursor-based vs offset-based
Viewed 0 times
cursor paginationoffsetnext_cursorkeysetpage tokenhas_more
Problem
APIs returning large datasets need pagination. Offset-based pagination (page=3&limit=20) is simple but breaks when data changes between pages: items shift, causing duplicates or missing items.
Solution
Use cursor-based pagination for dynamic data: return a next_cursor token that points to the last item. Client sends cursor to get the next page. Benefits: stable across data changes, no skipped/duplicate items, efficient with database indexes. Use offset only for truly static data or when random page access is needed. Response format: { data: [...], next_cursor: 'abc123', has_more: true }.
Why
Offset pagination uses OFFSET N in SQL, which scans and discards N rows. Cursor pagination uses WHERE id > cursor with an index, which is O(1) regardless of page number.
Revisions (0)
No revisions yet.