How-To Guide

How to Implement Cursor Pagination in a REST API

Replace offset pagination with stable keyset pagination, opaque cursors, correct ordering, and indexes that keep large result sets fast.

On this page

  1. Introduction
  2. Choose a stable ordering key
  3. Encode the cursor
  4. Write the keyset query
  5. Handle ties, deletes, and updates
  6. Test the boundaries
  7. Common pitfalls
  8. Conclusion

Introduction

Pagination looks like a simple LIMIT and OFFSET, but offset pagination has two problems that appear as data grows. The database must read and discard the rows before the offset, so page 10,000 is dramatically more expensive than page 1. And if rows are inserted or deleted between requests, the same row can appear twice or be skipped entirely. A feed, audit log, or search result that changes while the user pages through it will show duplicates and gaps.

Cursor pagination, also called keyset pagination, avoids both problems. Instead of asking for rows 20,001 through 20,010, the client asks for the next ten rows after the last row it saw. The database uses an index to jump directly to that position, and changes elsewhere in the result set do not shift the page boundary.

This tutorial builds a cursor-paginated endpoint for an orders table. It covers the ordering key, cursor encoding, SQL, API shape, tests, and the mistakes that make a cursor unstable.

Choose a stable ordering key

A cursor must identify a precise position in a deterministic order. A timestamp alone is not enough: two orders can share the same created_at value, and the database is free to return ties in any order. Use a composite key such as (created_at, id) and always sort in a defined direction. The id breaks ties, and the pair is unique.

CREATE INDEX orders_created_at_id_idx
  ON orders (created_at DESC, id DESC);

The index must match the sort order. A query that sorts by created_at DESC, id DESC can use this index directly. If the query sorts by created_at DESC but the index is (created_at ASC, id ASC), the plan may need a sort or a backward scan depending on the database. Measure the plan with EXPLAIN rather than assuming.

Allow only a small, documented set of sort options. If the client can choose arbitrary columns, the cursor must encode the column and direction, and the API must validate them against an allowlist. A cursor that carries a column name from the client is an SQL injection risk if it is ever interpolated.

Encode the cursor

The cursor should contain the values needed to resume, not the SQL that produced them. For the (created_at, id) order, encode both values in a compact format and base64url-encode the result. The cursor is opaque to the client; it is a position, not a query.

type Cursor = { createdAt: string; id: string };

function encodeCursor(row: { createdAt: Date; id: string }): string {
  const payload: Cursor = {
    createdAt: row.createdAt.toISOString(),
    id: row.id,
  };
  return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
}

function decodeCursor(raw: string): Cursor {
  let parsed: unknown;
  try {
    parsed = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'));
  } catch {
    throw new HttpError(400, 'invalid cursor');
  }
  if (
    typeof parsed !== 'object' || parsed === null ||
    typeof (parsed as Cursor).createdAt !== 'string' ||
    typeof (parsed as Cursor).id !== 'string' ||
    Number.isNaN(Date.parse((parsed as Cursor).createdAt))
  ) {
    throw new HttpError(400, 'invalid cursor');
  }
  return parsed as Cursor;
}

Base64url avoids +, /, and = characters that need escaping in URLs. Decoding must validate the shape, the date, and the id format. A malformed cursor should return 400, not 500 and not an empty page. If the cursor is exposed to untrusted clients and tampering matters, sign it with an HMAC or encrypt it; base64 alone provides no integrity.

Do not put a page number inside the cursor and call it cursor pagination. A page number still requires offset arithmetic and inherits the same shifting problem.

Write the keyset query

For descending order, the next page contains rows strictly older than the cursor, or rows with the same timestamp and a smaller id. SQL row-value comparison expresses this cleanly:

SELECT id, customer_id, total_cents, created_at
FROM orders
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT $3;

Fetch limit + 1 rows. If the extra row exists, there is a next page; return only limit rows and build the next cursor from the last returned row. This avoids a separate COUNT query and avoids returning an empty page with a misleading hasNext: false.

For ascending order, reverse the comparison and the sort direction. Keep the index aligned. If the API supports both directions, the cursor must record the direction or the endpoint must make direction part of the request and validate that it matches the cursor.

The response shape should make the contract explicit:

{
  "items": [{ "id": "o-9", "totalCents": 4200 }],
  "nextCursor": "eyJjcmVhdGVkQXQiOiIyMDI2LTEwLTIwVDEwOjAwOjAwWiIsImlkIjoiby05In0",
  "hasNext": true
}

nextCursor is null when there are no more rows. Avoid returning a total count by default; counting a large filtered set can be as expensive as the original offset query. If the product needs a count, compute it separately, cache it, or show an approximate value with a clear label.

Handle ties, deletes, and updates

Ties are handled by the composite key. Deletes do not shift the boundary because the query continues after a specific value. Updates are trickier: if a row’s created_at changes, it moves in the ordering and may be skipped or repeated. Treat the sort key as immutable, or accept that changing it can move a row across pages. If users need a stable feed, sort by an immutable sequence rather than a mutable timestamp.

A row deleted after the client receives it may still appear in a cached page; that is normal. A row inserted before the cursor will not appear in later pages, which is also expected for a descending feed. Document whether the API guarantees a snapshot or a live view. A snapshot requires a consistent read, a materialized result, or a transaction with a fixed visibility point; most APIs provide a live view and accept these semantics.

Test the boundaries

Add tests for an empty result, a single page, multiple pages, duplicate timestamps, a cursor pointing at a deleted row, a malformed cursor, and a cursor with an invalid date. Assert that walking pages returns each row exactly once under a stable data set. Then insert and delete rows between pages and assert the documented behavior.

A property-style test can compare keyset pagination with a full sorted list on a small data set: concatenating all pages must equal the full list. That catches ordering and comparison mistakes that a single happy-path test misses.

Common pitfalls

  • Using a non-unique sort key. Ties make pages overlap or skip rows.
  • Mismatched index order. The query works but scans or sorts the table.
  • Fetching a count on every page. The count can dominate latency.
  • Trusting the cursor. Validate and bound every field; never interpolate it into SQL.
  • Using offset with a cursor-shaped API. The client cannot tell, but the performance and correctness problems remain.
  • Changing the sort direction without encoding it. The cursor from one direction is invalid in the other.

Conclusion

Cursor pagination is a small change to the query and a larger change to the API contract. Choose a unique, indexed ordering key; encode the last row’s values into an opaque, validated cursor; query with a keyset predicate and limit plus one; and test ties, deletions, and malformed input. The result is stable paging whose cost stays roughly constant as the user moves deeper, instead of degrading with every page.

Sources: PostgreSQL row comparison, Use The Index, Luke — pagination, OWASP input validation.

FAQ

Why is offset pagination slow on large tables?
The database must scan and discard every row before the offset. Page 10,000 reads 100,000 rows just to return the next 10, and the cost grows with the page number.
Are cursors secure if they are base64-encoded?
Base64 is encoding, not encryption. Treat a cursor as untrusted input, validate every decoded field, and never let it carry SQL fragments or column names. Sign it if clients must not tamper with the values.
What happens when a row is deleted between pages?
Keyset pagination continues after the last seen key, so deletions do not shift the remaining rows. Offset pagination can skip or duplicate rows when the underlying set changes.

Related Examples