← Back to Node.js, page 7

nodejs-0134 · Medium mid

How do you paginate a list API: offset versus cursor (keyset) pagination, and what goes wrong with offsets?

Offset pagination (page and limit, SQL OFFSET) is simple but slow on large tables and unstable when rows are inserted or deleted between requests, which gives duplicates or gaps. Cursor (keyset) pagination returns an opaque cursor that encodes the last seen sort key and asks for rows after it. It is fast, stable and the right default for feeds and big collections.

Full answer

Offset pagination

  • GET /items?page=3&limit=20 becomes LIMIT 20 OFFSET 40.
  • Good: easy, supports jumping to page N and showing total pages.
  • Bad: the database still reads and discards all skipped rows, so deep pages are slow. If a row is inserted or deleted while the user pages, items shift: a row can appear on two pages or be skipped.

Cursor (keyset) pagination

  • The client sends the cursor from the previous response: GET /items?limit=20&cursor=abc.
  • The cursor encodes the sort key of the last row, such as { id: 40 } or { createdAt, id }. The query is WHERE id > 40 ORDER BY id LIMIT 20 (with an index, this is fast at any depth).
  • Fetch limit + 1 rows to know whether there is a next page without a count query.
  • With a non-unique sort column, add a unique tie-breaker: WHERE (created_at, id) > ($1, $2) ORDER BY created_at, id.
  • Return the cursor as an opaque string (base64url of JSON), so you can change its content. Optionally sign it, and validate it on input.
  • Limits: you cannot jump to page 50 or show an exact total cheaply. That is fine for infinite scroll and APIs.

Response design

  • { data: [...], nextCursor: '...' or null } (and optionally hasMore).
  • Cap the limit (for example 100) and set a default.
  • Links in the Link header (rel="next") are an alternative.
  • Document sort order and what happens to changes while paging.
javascript
const express = require('express');

// 12 items with ids 1 to 12, newest data inserted at the front later.
let items = Array.from({ length: 12 }, (_, i) => ({ id: i + 1, title: 'item ' + (i + 1) }));
const app = express();

// Offset pagination over a list ordered by id DESC (newest first)
app.get('/offset', (req, res) => {
  const page = Number(req.query.page || 1), limit = Number(req.query.limit || 5);
  const sorted = [...items].sort((a, b) => b.id - a.id);
  res.json(sorted.slice((page - 1) * limit, page * limit).map((i) => i.id));
});

// Cursor pagination: the cursor holds the last id seen
const encode = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
const decode = (text) => JSON.parse(Buffer.from(text, 'base64url').toString());
app.get('/cursor', (req, res) => {
  const limit = Math.min(Number(req.query.limit || 5), 100);
  const after = req.query.cursor ? decode(req.query.cursor).id : Infinity;
  const rows = items.filter((i) => i.id < after).sort((a, b) => b.id - a.id).slice(0, limit + 1); // one extra row
  const hasMore = rows.length > limit;
  const data = rows.slice(0, limit);
  res.json({ data: data.map((i) => i.id), nextCursor: hasMore ? encode({ id: data.at(-1).id }) : null });
});

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const get = async (path) => (await fetch(base + path)).json();

  // Offset: a new item arrives between page 1 and page 2.
  const offset1 = await get('/offset?page=1&limit=5');
  items.push({ id: 13, title: 'item 13' });
  const offset2 = await get('/offset?page=2&limit=5');
  console.log('offset page 1:', offset1.join(','), '| page 2 after an insert:', offset2.join(','), '| duplicate id 8:', offset1.includes(8) && offset2.includes(8));

  // Cursor: the same insert between the pages.
  items = items.filter((i) => i.id !== 13);
  const cursor1 = await get('/cursor?limit=5');
  items.push({ id: 13, title: 'item 13' });
  const cursor2 = await get('/cursor?limit=5&cursor=' + cursor1.nextCursor);
  console.log('cursor page 1:', cursor1.data.join(','), '| page 2 after an insert:', cursor2.data.join(','), '| next cursor present:', Boolean(cursor2.nextCursor));
  console.log('cursor is opaque text:', cursor1.nextCursor, '=', JSON.stringify(decode(cursor1.nextCursor)));
  server.close();
});

A new item arrives between the first and second page. Offset pagination repeats an item and cursor pagination does not. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): offset page 1: 12,11,10,9,8 | page 2 after an insert: 8,7,6,5,4 | duplicate id 8: true cursor page 1: 12,11,10,9,8 | page 2 after an insert: 7,6,5,4,3 | next cursor present: true cursor is opaque text: eyJpZCI6OH0 = {"id":8}

Key points

  • Offset is simple but slow deep down and unstable with changes.
  • Cursor pagination uses the last seen key with an index.
  • Fetch limit + 1 to detect the next page.
  • Add a unique tie-breaker to the sort key.
  • Return an opaque cursor and cap the limit.

Common mistakes

  • Using OFFSET for large tables and deep pages.
  • Sorting by a non-unique column without a tie-breaker.
  • Exposing the cursor format so clients build their own.
  • Running a COUNT(*) on every request for the total.
  • Not capping the limit parameter.

Follow-ups

  • How do you paginate by createdAt when many rows share the same timestamp?
  • How do you let a client go backwards with cursors?
  • How do you show page numbers if the product needs them?

Tips

  • Show the insert-between-pages problem.
  • Say 'limit plus one'.
  • Give the SQL for the keyset query.