← Back to Backend, page 1

backend-0003 · Medium mid

How do you paginate a REST API, and why does offset pagination break or slow down on large or changing data compared with keyset (cursor) pagination?

Offset pagination (LIMIT n OFFSET k) is simple but the database still reads and skips k rows, so deep pages are slow, and inserts or deletes between requests shift the rows so items repeat or vanish. Keyset (cursor) pagination asks for rows after the last seen sort key (WHERE id < last ORDER BY id DESC LIMIT n), which is fast with an index and stable under changes. The cost: no jump to page 50, and the sort key must be unique and indexed.

Full answer

Offset pagination

  • GET /items?limit=20&offset=40. Easy to build, supports page numbers and totals.
  • Problems: the engine produces and discards offset rows, so cost grows with the page number. If a row is inserted before the current position, the next page repeats a row. If a row is deleted, one row is skipped.

Keyset (cursor) pagination

  • The client sends the sort key of the last row it saw: GET /items?limit=20&after=eyJpZCI6OH0. The server runs WHERE (sort_key) < (:last) ORDER BY sort_key DESC LIMIT 20. With an index the engine jumps straight to the position.
  • The cursor is opaque to clients (often base64 of the last key). This lets you change its content later.
  • The sort key must be unique and stable. For a non-unique column such as created_at, add the id as a tie breaker and use a row comparison: WHERE (created_at, id) < (:t, :id).
  • Return a next cursor, or nothing at the end. A total count is expensive, so offer it only when needed (or an estimate).

Choosing: use keyset for feeds, logs and large tables, and offset for small admin tables where page numbers matter. Always cap limit (for example 100).

javascript
const { Client } = require('pg');

(async () => {
  const db = new Client(); await db.connect();
  await db.query('DROP TABLE IF EXISTS page_items; CREATE TABLE page_items (id serial PRIMARY KEY, title text)');
  await db.query("INSERT INTO page_items (title) SELECT 'item ' || g FROM generate_series(1, 10) g");
  const ids = (r) => r.rows.map((x) => x.id).join(', ');

  const offsetPage = (limit, offset) => db.query('SELECT id FROM page_items ORDER BY id DESC LIMIT $1 OFFSET $2', [limit, offset]);
  const keysetPage = (limit, after) => db.query('SELECT id FROM page_items WHERE ($2::int IS NULL OR id < $2) ORDER BY id DESC LIMIT $1', [limit, after]);
  const encode = (id) => Buffer.from(JSON.stringify({ id })).toString('base64url');
  const decode = (cursor) => JSON.parse(Buffer.from(cursor, 'base64url').toString()).id;

  const o1 = await offsetPage(3, 0);
  const k1 = await keysetPage(3, null);
  const cursor = encode(k1.rows.at(-1).id);
  console.log('page 1 (both)        :', ids(o1), '| cursor =', cursor);

  await db.query("INSERT INTO page_items (title) VALUES ('new item')");     // a new row arrives between the requests

  console.log('page 2 with offset   :', ids(await offsetPage(3, 3)), '(8 appears again)');
  console.log('page 2 with keyset   :', ids(await keysetPage(3, decode(cursor))), '(continues from 7)');

  const plan = await db.query('EXPLAIN (COSTS OFF) SELECT id FROM page_items WHERE id < 8 ORDER BY id DESC LIMIT 3');
  console.log('keyset plan uses the primary key index:', plan.rows.some((r) => /Index/.test(r['QUERY PLAN'])));

  await db.query('DROP TABLE page_items');
  await db.end();
})();

Run against the local PostgreSQL. A new row is inserted between page 1 and page 2 to show the difference. Timing of deep offsets was not measured here. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): page 1 (both) : 10, 9, 8 | cursor = eyJpZCI6OH0 page 2 with offset : 8, 7, 6 (8 appears again) page 2 with keyset : 7, 6, 5 (continues from 7) keyset plan uses the primary key index: true

Key points

  • Offset skips rows by reading them, so deep pages are slow.
  • Changes between requests make offset pages repeat or miss rows.
  • Keyset uses the last seen key and an index.
  • The sort key must be unique; add the id as a tie breaker.
  • Cursors should be opaque and limits capped.

Common mistakes

  • Using OFFSET on a table with millions of rows and deep pages.
  • Sorting by a non-unique column with no tie breaker.
  • Exposing raw ids in a cursor that clients start to parse.
  • Returning an exact total count on every request.
  • No maximum limit.

Follow-ups

  • How do you paginate by (created_at, id) in SQL?
  • How do you go backwards with a keyset cursor?
  • What do you return for 'total pages'?

Tips

  • Say 'the database still reads the skipped rows'.
  • Show the WHERE form of keyset.
  • Mention the trade-off: no random page jump.