Skip to the page

Designing HTTP APIs · mid

Pagination (offset vs cursor), filtering and sorting

Offset pagination (LIMIT 20 OFFSET 400) is simple and allows page numbers but gets slower and skips or repeats rows when data changes, while cursor (keyset) pagination continues after the last row seen, stays fast and stable, but cannot jump to page N.

The notes

What you must know

  • Offset: ?page=21&limit=20. The database still reads and throws away all skipped rows, so deep pages are slow; new rows shift everything, so users see duplicates or miss items.
  • Cursor: ?limit=20&cursor=<opaque>. The cursor encodes the sort key of the last item (e.g. createdAt and id). Next query: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20, with a matching index.
  • The sort must be deterministic: add a unique tiebreaker (id), or rows with equal timestamps are skipped or repeated.
  • Make cursors opaque (base64url of JSON) so clients do not build them, and validate them (bad cursor -> 400).
  • Return { items, nextCursor } (null at the end). Fetch limit + 1 rows to know if there is a next page without a COUNT.
  • Exact total counts on big tables are expensive; show 'more' or an estimate unless the product needs the number.
  • Filtering and sorting: whitelist fields (?status=paid&sort=-createdAt), never pass raw input into SQL, and make sure indexes match common filters.

The red pen

Common traps: mistake → fix

  • Mistake: Offset is fine at any size

    Fix: page 10,000 makes the database read 200,000 rows to return 20.

  • Mistake: Cursor = the last id

    Fix: with a non-unique sort key (createdAt) you need the key and a tiebreaker.

  • Mistake: Infinite scroll needs total counts

    Fix: it only needs 'is there more?'.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you paginate an API? Offset or cursor?
  2. Why does offset pagination get slow, and why does it show duplicates?
  3. What exactly goes into a cursor? Why must the sort be deterministic?
  4. How do you support 'jump to page 50' and infinite scroll in the same product?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview