Skip to main content
05

Offset vs cursor pagination

EasyAPI designPaginationSQL

What's the difference between offset and cursor (keyset) pagination, and when do you use each?

TL;DR

Offset pagination (LIMIT 20 OFFSET 40) is simple and lets users jump to any page, but it gets slow on deep pages (the database still reads and discards all skipped rows) and skips or duplicates rows when data changes between requests. Cursor pagination remembers the last row seen and asks for rows after it (WHERE created_at < $cursor). It's fast at any depth with an index and stable under inserts, but you can only go next or previous. Use offset for small admin tables with page numbers; use cursors for feeds, infinite scroll, large tables and public APIs.

Key points

  • The cursor must follow a unique, ordered key. Add a tiebreaker: ORDER BY created_at DESC, id DESC.
  • Back the sort with a composite index on those same columns.
  • Return the cursor as an opaque string (base64 of the values) so clients don't depend on its format.
  • Return nextCursor (or null at the end) instead of a total count. COUNT(*) on big tables is expensive.
  • Offset breaks under writes: if a new row is inserted while the user reads page 1, page 2 repeats the last item of page 1.

Example

sql
-- Offset: slow at OFFSET 100000
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 100000;

-- Cursor (keyset): uses the index, same speed at any depth
SELECT * FROM posts
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;
json
{ "items": [...], "nextCursor": "eyJjIjoiMjAyNi0xMS0yN1QxMDowMDowMFoiLCJpIjo0Mn0=" }

Common follow-ups

  • How do you show "page 7 of 50" with cursors? You can't directly. If you really need it, use offset for shallow pages or an approximate count.
  • How does GraphQL do this? The Relay connection spec: first, after, edges and pageInfo { hasNextPage, endCursor }.

What interviewers look for

Tip

Explain why deep offsets are slow and unstable, how the cursor query uses an index, and the tiebreaker column.

  • Red flag: cursor pagination ordered by a non-unique column with no tiebreaker.

Was this helpful?

Related questions