Backend & Node.js · APIs, data and failure

How do you paginate a large API collection?

Mediumpaginationapi designdatabaseUpdated Oct 2026
Quiz this track

Short answer

Use offset pagination for small, stable datasets and cursor or keyset pagination for large or changing collections. Keyset pagination is stable and fast because it seeks from the last seen key instead of counting skipped rows.

Pagination is both an API contract and a query plan. Offset pagination says skip N rows and take M. It is easy to implement and supports jumping to a page, but the database still walks the skipped rows and results can shift when data changes between requests.

sql
SELECT id, created_at, total
FROM orders
WHERE (created_at, id) < ('2026-10-01', 1042)
ORDER BY created_at DESC, id DESC
LIMIT 25;
Keyset pagination uses the last row as the starting point. The compound key keeps ordering stable when timestamps tie.

How to choose

  • Offset is fine for admin tables and small result sets
  • Cursor or keyset is better for feeds, logs and large tables
  • Cursor pagination cannot jump to an arbitrary page without extra state
  • Return an opaque cursor, not a raw offset, so the implementation can change
  • Use a stable sort with a unique tiebreaker such as id
  • Avoid returning a total count on every request if the count is expensive

The cursor should encode the sort key and direction, and it must be validated. If the sort order changes, old cursors may produce incorrect results. For counts, cache them, compute them approximately or expose them only when the client asks.

Deep offset pagination is a common cause of slow queries under load. If page 1000 is slow but page 1 is fast, the problem is the growing offset scan, not the page size.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why does deep offset pagination get slower?
  2. 2What should a cursor contain?
  3. 3How do you paginate a feed with ties in the sort key?
  4. 4When is returning a total count a bad idea?

Say it in the interview

I use offset pagination when the dataset is small or users need page numbers. For large or changing collections I use keyset pagination, seeking from the last seen sort key and id so the query stays fast and results do not shift. The cursor is opaque and validated, and the sort always includes a unique tiebreaker. I avoid expensive total counts on every page.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Backend & Node.js mock interview and get scored feedback on depth, clarity and confidence.