How-To Guide

How to Fix Deep Pagination Performance

Replace OFFSET with keyset pagination on a stable composite sort, estimate totals instead of counting, and keep cursor state tamper-proof.

On this page

  1. Introduction
  2. Measure the degradation curve
  3. Design the cursor around sort stability
  4. Rewrite the query
  5. Handle total counts honestly
  6. Support deep links and jumps
  7. Cursor encoding and API shape
  8. Test correctness under mutation
  9. Common pitfalls
  10. Conclusion

Introduction

Pagination with LIMIT and OFFSET feels natural because it mirrors page numbers, and it performs acceptably while users sit near the front. The cost structure is hostile to depth: OFFSET 100000 LIMIT 20 obliges the database to walk the index past one hundred thousand rows, producing and discarding them, before it can emit the twenty requested. Page latency grows linearly with depth, deep links and export jobs hammer the slowest possible path, and under load those deep scans are precisely the queries that fill temp space and saturate IO. The fix, keyset pagination, replaces positional offsets with value-based cursors: the client says give me rows after this one, defined by the sort key values of the last row it saw, and the database seeks directly to that position in the index. Constant cost at any depth, at the price of changing how clients express position. This tutorial measures the degradation, designs the cursor correctly around sort stability, rewrites the query, and handles the two product features that resist: total counts and arbitrary page jumps.

Measure the degradation curve

Make the problem visible before rewriting anything, because the fix changes API shape and deserves evidence. Measure the same query at increasing offsets on production-sized data: offset 0, 10,000, 100,000, 1,000,000, each timed cold and warm. The latency curve rises linearly with offset under OFFSET, and stays flat under keyset. On the database side, EXPLAIN ANALYZE on the deep query shows rows scanned in the thousands or millions against rows returned in the tens, and pg_stat_statements or the slow log aggregates how often users or jobs actually request deep pages, which is often surprising: analytics dashboards, scrapers, and export jobs sit at depth far more than human users do. This measurement doubles as the migration business case, and re-running it after the migration is the verification.

EXPLAIN ANALYZE
SELECT id, created_at, title FROM articles
ORDER BY created_at DESC, id DESC
OFFSET 100000 LIMIT 20;

Design the cursor around sort stability

Keyset pagination is only correct if the sort key is totally ordered and stable: two rows must never compare equal, or rows can shift across page boundaries when the underlying data shifts between requests. A sort on created_at alone fails the moment two rows share a timestamp, which bulk inserts guarantee will happen. The design rule is a composite sort key ending in a unique column: (created_at, id) with id unique makes the ordering total. The cursor is then just the last row’s key values, opaque to the client, and the next page request compares against it. Ordering direction matters for the comparison: descending sort needs descending comparison in the predicate, and mixed directions, created_at descending with id ascending, need careful row-value construction or explicit tuple logic. Keep the sort key small and index-aligned: the pagination index should be exactly the sort key, (created_at DESC, id DESC), or the database sorts per page and the constant-cost property evaporates.

Rewrite the query

The rewrite expresses position as a predicate the index can seek to. PostgreSQL’s row-value comparison does it in one clause.

-- positional: scans and discards 100,000 rows
SELECT id, created_at, title FROM articles
ORDER BY created_at DESC, id DESC
OFFSET 100000 LIMIT 20;

-- keyset: seeks directly to the cursor
SELECT id, created_at, title FROM articles
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The row-value comparison (created_at, id) < ($1, $2) is lexicographic: it matches rows strictly after the cursor in the sort order, and the index on (created_at DESC, id DESC) turns it into an index seek with at most LIMIT plus one rows touched. On engines without row-value syntax, expand to the equivalent OR form, created_at < $1 OR (created_at = $1 AND id < $2), which planners handle slightly less elegantly but still far better than OFFSET. The first page simply omits the predicate. The cursor handed to the client should be the key values of the final row of this response, serialized opaquely, base64 of a compact encoding, so clients treat it as a token rather than as data to construct.

Handle total counts honestly

Page-number UIs want total counts, and exact COUNT over large filtered sets is itself an OFFSET-class cost: a full scan to answer how many. Three responses cover the honest spectrum. Estimate: display approximately 1.2 million results using the planner’s row estimate from EXPLAIN, table statistics, or a sampled count, and accept that the number drifts. Cap: display 1,000+ and stop counting past a threshold, which matches how users actually use totals, nobody pages to page 40,000, and export jobs should use cursors, not counts. Cache: compute the exact count asynchronously on a refresh interval for the rare surfaces that truly need it. What the honest approaches share is refusing to pay a full scan per page view for a number users glance at once. The count decision should be made per surface: search results want estimates, financial reports want exact cached counts, infinite feeds want neither.

The feature most at risk in the migration is jump to page N, which positional offset served naturally. Keyset position is data values, not an index, so arbitrary jumps need a translation layer. Segment-based jumping preserves the feature at coarse granularity: maintain a small table of checkpoint cursors, every thousandth row’s key values, written by a background job or opportunistically as users page; jumping to page 4,030 seeks to checkpoint 4,000 and pages forward thirty times at constant cost. For date-sorted feeds, jumping by date is the natural cursor: the UI offers jump to March rather than page 87, which users often prefer and which is a single seek. Export and scraping flows, the deepest paginators of all, should abandon page numbers entirely and walk cursor links until exhaustion, which is both faster and resilient to concurrent inserts that would otherwise shift positional pages under them. These accommodations keep the product features while removing the linear scan they were built on.

CREATE TABLE pagination_checkpoints (
 feed text, segment int, last_created_at timestamptz, last_id bigint,
 PRIMARY KEY (feed, segment)
);

Cursor encoding and API shape

Expose the cursor through the API in a way that survives tampering and drift. Opaque encoding: serialize the key values, sign or at least validate them server-side, and base64 the result, so clients pass tokens rather than forging positions; unsigned cursors invite clients to hand-craft keys that bypass intended sort orders or filters. Statelessness: the cursor must carry all position state itself, sort key values and any filter context that affects ordering, so the server does not need per-client pagination sessions. Link semantics: return next and prev cursors in the response, in the Link header style or an envelope field, so clients never construct cursors themselves. Validation: reject cursors whose values do not type-check or whose sort does not match the request’s declared sort, with a clear error, rather than silently returning odd results. A well-shaped cursor API makes the migration invisible to well-behaved clients, which simply follow links, and visible only to the page-number holdouts that the checkpoint layer serves.

Test correctness under mutation

Pagination bugs live in the interaction with concurrent writes, so tests must mutate data mid-walk. Insertion ahead of the cursor: new rows arriving at the front must not duplicate items already delivered, which keyset guarantees by value comparison and OFFSET does not. Deletion of the cursor row: the next-page predicate uses strict inequality against values, not row identity, so deleting the last-seen row must still return the following page, and a test should assert exactly that. Tie handling: seed rows sharing sort values and page through them, asserting no row appears twice and none is skipped, which validates the unique tiebreaker. Boundary: the final page must report hasMore false cleanly, an empty page must terminate walks, and a forged cursor must produce a validation error rather than results. Run the walk-under-mutation test with concurrent inserts from another connection, because that is the production condition the design exists for.

const seen = new Set<number>();
let cursor: string | null = null;
do {
 const page = await list({ limit: 20, cursor });
 for (const row of page.items) {
  if (seen.has(row.id)) throw new Error('duplicate: ' + row.id);
  seen.add(row.id);
 }
 cursor = page.nextCursor;
} while (cursor);

Common pitfalls

  • Sorting on a non-unique column. Ties shuffle rows across pages; always append a unique tiebreaker to the sort key.
  • No index matching the sort. Per-page sorting replaces the seek; the index must be the sort key exactly.
  • Exact COUNT on every page. The totals number costs a full scan, recreating the problem being fixed.
  • Unsigned hand-crafted cursors. Clients forge positions; encode opaquely and validate server-side.
  • Mixed-direction sorts with naive predicates. Row-value comparisons must mirror the exact sort direction per column.
  • Keeping page-number exports. Deep scrapers walking pages are the worst OFFSET offenders; move them to cursor links.

Conclusion

Deep pagination is a data-structure problem wearing a UI costume: positional OFFSET costs a scan proportional to depth, and the cure is making position a value rather than an index. Sort on a unique composite key with a matching index, express the next page as a row-value comparison against the last-seen key, and hand clients opaque, validated cursor tokens with next links. Serve totals as estimates, caps, or cached counts rather than per-page scans, and translate arbitrary jumps through checkpoints or date seeks so the product keeps its features without its scans. Test under mutation, because duplication and loss across boundaries are the failure modes positional thinking hides. The result is page latency that is flat at depth one and depth one million, and exports that walk links instead of counting rows.

Sources: Use the index, Luke: no offset, PostgreSQL: LIMIT and OFFSET, Use the index, Luke: partial results.

FAQ

Why is OFFSET slow exactly?
The database must produce and discard all preceding rows to know where the offset lands. Scanning 100,000 rows to return page 1,001 costs the scan of 100,000 rows, every time, growing linearly with depth.
Can I keep page numbers in URLs with keyset pagination?
Not directly, because keyset position is defined by data values rather than an index. Map page numbers to cursors via a small lookup for shallow pages, or switch UI to next and previous navigation with cursor links.
What if the sort column is not unique?
Append a unique tiebreaker, usually the primary key, to the sort. Without it, rows with equal sort values can shuffle between pages, duplicating or losing items across page boundaries.

Related Examples