Pagination: offset vs cursor (keyset) trade-offs

Difficulty: Intermediate

Question

Compare offset-based and cursor-based pagination. Which would you choose for a large, frequently changing feed, and why?

Answer

Pagination exists because returning a million rows in one response would blow up memory, bandwidth and latency. Think of a library catalogue: you do not hand someone the whole index; you give them a page and a way to ask for the next one. The interesting question is how you define 'next'.

Offset pagination uses page and limit, or offset and limit: GET /orders?offset=40&limit=20. It is easy to implement (SQL LIMIT 20 OFFSET 40), easy to understand, and it allows random access, jumping to page 7 directly, and showing total page counts. But it has two real problems. First, performance: the database still has to walk and discard the first N rows, so deep pages get slower linearly; OFFSET 1000000 is painfully slow. Second, consistency: if rows are inserted or deleted while the client pages, items shift, so the client sees duplicates or misses records. On a live feed, that is a visible bug.

Cursor pagination, also called keyset or seek pagination, uses a pointer to the last item seen instead of a position: GET /orders?limit=20&after=eyJpZCI6MTAwfQ. The query becomes WHERE (created_at, id) < (:last_created_at, :last_id) ORDER BY created_at DESC, id DESC LIMIT 20, which uses an index and takes roughly constant time regardless of depth. It is stable under inserts and deletes, since you continue from a specific row rather than a count. The trade-offs: no jumping to arbitrary pages, no cheap total count, and sorting must be by a deterministic, indexed, unique combination of columns. Always add a tiebreaker such as id, otherwise rows with equal timestamps may be skipped or repeated.

The cursor should be opaque to clients, typically base64 of the sort keys, possibly signed or encrypted so clients do not depend on its internals or tamper with it. Return it in the response as next_cursor, or in a Link header, along with has_more. Stripe uses starting_after and has_more; GitHub and Slack use cursors too.

Total counts: SELECT COUNT(*) on a big table can itself be slow. Offer it optionally, cap it, or return an estimate. Many products replace exact totals with 'load more' or infinite scroll, which is a natural fit for cursors.

My default recommendation: use cursor pagination for large, append-heavy or frequently changing collections, such as feeds, orders, logs and events. Use offset for small, mostly static datasets, admin tables that truly need page numbers, or when the collection is bounded. It is also fine to support both where UI requirements demand it, but cap the maximum offset.

Other details interviewers probe: set a default limit and a hard maximum, so clients cannot ask for limit=100000. Keep sort order stable and documented. Decide what happens when a cursor points at a since-deleted row; keyset handles this gracefully because it compares values, not row existence. And for bidirectional paging, support before as well as after.

Summary: offset is simple but slow deep and unstable under change; cursor is fast, stable, and slightly less flexible.

Code examples

Keyset query and response

-- SQL for the next page
SELECT id, status, created_at
FROM orders
WHERE user_id = $1
  AND (created_at, id) < ($2, $3)
ORDER BY created_at DESC, id DESC
LIMIT 21;  -- fetch limit+1 to know if more exist

-- Response
{
  "data": [ /* 20 orders */ ],
  "has_more": true,
  "next_cursor": "eyJjIjoiMjAyNi0wOS0wMVQxMDoxNTozMFoiLCJpIjo5OX0"
}

Fetching limit plus one row tells you whether another page exists without a COUNT query.

Express cursor handler

app.get('/v1/orders', async (req, res) => {
  const limit = Math.min(Number(req.query.limit) || 20, 100);
  const cur = req.query.after
    ? JSON.parse(Buffer.from(req.query.after, 'base64url').toString())
    : null;
  const rows = await db.query(
    `SELECT * FROM orders WHERE user_id=$1 ${cur ? 'AND (created_at,id) < ($2,$3)' : ''}
     ORDER BY created_at DESC, id DESC LIMIT ${limit + 1}`,
    cur ? [req.user.id, cur.c, cur.i] : [req.user.id]
  );
  const hasMore = rows.length > limit;
  const page = rows.slice(0, limit);
  const last = page[page.length - 1];
  res.json({
    data: page,
    has_more: hasMore,
    next_cursor: hasMore ? Buffer.from(JSON.stringify({ c: last.created_at, i: last.id })).toString('base64url') : null
  });
});

Limit is capped, a tiebreaker id is used, and the cursor is opaque base64url.

Key points

Common follow-up questions

Interview tips

Concepts covered

pagination, offset, cursor, keyset

More API Design questions