The deep-page problem, measured
I didn't want to publish another “OFFSET is slow” post, so I put both queries on PostgreSQL 17.12 in Docker and measured them over 1.2 million rows. Then I tried to break the cursor implementation in the ways real data breaks it: duplicate timestamps, backward navigation, NULL sort keys, mixed sort directions, filter changes, deletes, and rows that arrive late.
The setup was boring on purpose: page size 20, three runs per query, and only rows matching this filter:
status = 'published' AND deleted_at IS NULL
When I say depth below, I mean how many rows the client has already consumed before asking for the next page. At depth 1,000,000, the measured median was 139.894 ms with OFFSET; the keyset query stayed at 0.046 ms.
| Rows already seen | OFFSET median | Keyset median | Speedup |
|---|---|---|---|
| 0 | 0.032 ms | 0.032 ms | 1.0× |
| 10,000 | 1.168 ms | 0.023 ms | 50.8× |
| 100,000 | 12.472 ms | 0.067 ms | 186.1× |
| 1,000,000 | 139.894 ms | 0.046 ms | 3,041.2× |
Don't copy the exact milliseconds into your capacity plan. Copy the shape. The raw EXPLAIN (ANALYZE,BUFFERS) output shows why:
OFFSET at depth 100,000
Index Scan using idx_posts_active_created_at_id
actual time=0.033..10.345 rows=100020 loops=1
Buffers: shared hit=7366
Execution Time: 12.382 ms
Keyset at the same logical position
Index Cond: (ROW(created_at, id) < ROW(...))
actual time=0.021..0.023 rows=20 loops=1
Buffers: shared hit=4
Execution Time: 0.042 ms
The terminal run behind that table — the JSON exactly as the script printed it:
OFFSET isn't evil. It still works for small admin tables, bounded search results, or interfaces that genuinely need “jump to page 37”. For a feed that clients keep walking forward, though, it's usually the wrong tool.
What a cursor must guarantee
The easiest way to get keyset wrong is to treat the cursor as “the last id”. It isn't. It's a position in a total ordering, and in this feed that ordering is:
ORDER BY created_at DESC, id DESC
Once you choose it, these three pieces either line up or pagination lies to you:
- The index stores
(created_at DESC, id DESC). - The query sorts by
created_at DESC, id DESC. - The cursor comparison uses the same columns in the same order.
id isn't there because UUIDs are chronological; random UUIDs aren't. It's there because timestamps repeat in imports, batch jobs, tests, and sometimes plain production traffic. Without that unique final column, two rows with the same created_at can swap places between requests. The client then sees a row twice, or never sees it at all.
PostgreSQL row comparison does the lexicographic work:
(created_at, id) < ($1, $2::uuid)
It first compares created_at. It compares id only when the timestamps are equal. This is the behavior described in the row constructor documentation, and it is also where NULL starts to matter: a comparison involving NULL is unknown, not true.
Build the PostgreSQL query
Start with the schema, because PostgreSQL can't rescue a pagination query whose index tells a different ordering story. This version keeps soft-deleted rows out with a partial index. It also declares created_at as NOT NULL on purpose: a non-nullable sort key isn't a nice-to-have, it's a precondition of this design. If your column allows NULL, read the NULL sort keys section before copying anything.
CREATE TABLE posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
title TEXT NOT NULL,
score INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'published',
deleted_at TIMESTAMPTZ
);
CREATE INDEX idx_posts_active_created_at_id
ON posts (created_at DESC, id DESC)
WHERE deleted_at IS NULL;
CREATE INDEX idx_posts_status_created_at_id
ON posts (status, created_at DESC, id DESC);
The first page has no cursor predicate:
SELECT id, created_at, title, score, status
FROM posts
WHERE status = 'published'
AND deleted_at IS NULL
ORDER BY created_at DESC, id DESC
LIMIT 21; -- page size 20 + 1 probe row
The next page starts strictly after the last row returned to the client:
SELECT id, created_at, title, score, status
FROM posts
WHERE status = 'published'
AND deleted_at IS NULL
AND (created_at, id) < ($1, $2::uuid)
ORDER BY created_at DESC, id DESC
LIMIT 21;
Fetch one extra row. If PostgreSQL returns 21 rows, trim to 20 and set hasNextPage = true. The cursor for after comes from the twentieth row, not from the probe row.
This is the same basic keyset shape described in the broader pagination recipe. What matters here is everything around that shape: the contract, the backward direction, and the cases where the shape stops being sufficient.
Make the cursor safe to expose
I treat cursors as user input with structure. Base64 doesn't help there; it only changes how the bytes look. A client can decode the payload, move the timestamp back a few minutes, encode it again, and hand your API a perfectly valid-looking lie.
A production cursor should be opaque because your server validates and signs it, not because base64 looks obscure. The payload shape I use is small:
{
"v": 1,
"sort": "created_at_desc_id_desc",
"values": ["2026-01-02T06:22:41.000Z", "bf011d9e-5148-4a43-ac14-ef1bd0deeb07"],
"filters": "2be3aab71010df9b",
"exp": 1796475600
}
The filters value is a digest of the canonical filter set. If the cursor was created for status=published and the next request uses status=draft, reject it. If you don't bind the cursor to filters, a client can silently jump between two different ordered universes and your API will still return HTTP 200.
A minimal TypeScript encoder:
import { createHash, createHmac } from 'crypto';
function encodeCursor(payload: object, secret: string): string {
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signature = createHmac('sha256', secret)
.update(body)
.digest('hex')
.slice(0, 32);
return `${body}.${signature}`;
}
function filterDigest(filters: Record<string, unknown>): string {
const canonical = JSON.stringify(Object.fromEntries(Object.entries(filters).sort(([a], [b]) => a.localeCompare(b))));
return createHash('sha256').update(canonical).digest('hex').slice(0, 16);
}
Validation should reject, with HTTP 400, cursors that are malformed, expired, signed incorrectly, built for another sort, or built for another filter set. Don't silently fall back to page one; that turns a bad cursor into a plausible response and makes broken retries look successful.
Signing does not encrypt the payload. If cursor values are sensitive, do not put them in the cursor. Usually they are not secret — they are already visible in the page being returned.
Previous pages without duplicates
Forward pagination is the easy half. Backward pagination is where implementations that looked fine in a demo tend to lie. Reversing the comparison alone doesn't work; you also have to reverse the scan and then put the rows back into the order the UI promised.
Suppose the current page starts at cursor row C. Rows before C satisfy:
(created_at, id) > (cursor_created_at, cursor_id)
But the rows nearest to C are the smallest rows in that reverse space, so the inner query scans ascending. The outer query puts the page back into the public descending order:
SELECT id, created_at, title, score, status
FROM (
SELECT id, created_at, title, score, status
FROM posts
WHERE status = 'published'
AND deleted_at IS NULL
AND (created_at, id) > ($1, $2::uuid)
ORDER BY created_at ASC, id ASC
LIMIT 21
) previous_rows
ORDER BY created_at DESC, id DESC;
The response contract should separate cursor values from existence flags:
{
"data": [],
"pageInfo": {
"nextCursor": "eyJ2IjoxfQ.signature",
"prevCursor": null,
"hasNextPage": true,
"hasPreviousPage": false
}
}
Use this logic:
| Request | hasNextPage |
hasPreviousPage |
|---|---|---|
| First page | extra probe row exists | false |
after forward page |
extra probe row exists | true when a page was returned |
before backward page |
true when a page was returned | extra probe row exists |
Watching the walk is more convincing than reading about it. The companion includes demo_walk.py, which seeds the same fixture and pages through it on video — six forward pages over rows with colliding timestamps, then a backward walk from a mid-feed cursor:
Don't return prevCursor on the first page just because the first row exists. That was the bug in the previous version of this recipe: the client could ask for a page before the beginning and receive the first page again.
If your transport is GraphQL rather than a REST-ish JSON API, keep the SQL but adapt the contract to Relay. The Relay connections recipe covers that transport-specific shape.
Where keyset pagination breaks
I don't trust pagination code just because the first demo page looks right. The companion harness seeds a small fixture, walks it forward and backward, tampers with the cursor contract, and prints the result. This is the run behind this page:
PASS duplicate timestamps: 42/42 rows, 0 duplicates, 0 skips
PASS backward navigation: previous page matches forward page 2 exactly
PASS NULL sort keys: tuple comparison returned 0/4 NULL rows; coalesced NULL handling returned 4/4
PASS mixed direction: expanded condition matched 42/42 rows in baseline order
PASS filter binding: published cursor accepted for published and rejected for draft
PASS deletes and late inserts: deleted row absent, older late row stayed behind the cursor, 0 duplicates
That block is a transcription. This is the run itself:
The “pass” for NULL is intentionally a pass about confirming the hazard. Plain tuple comparison returned none of the four NULL rows.
Duplicate sort keys
Always end the ordering with a unique column. created_at alone feels safe until an import inserts two thousand rows inside the same second; microsecond precision doesn't save you when the application writes the same timestamp explicitly.
NULL sort keys
Tuple comparison doesn't paginate NULL values the way most people expect. This case is nasty because the first page can look perfectly healthy. With ORDER BY created_at DESC NULLS LAST, id DESC, rows with NULL never satisfy (created_at, id) < cursor.
The least surprising fix is to make the sort key NOT NULL and backfill old rows. If NULL is meaningful, use a generated/coalesced sort column or write the comparison explicitly:
WHERE created_at IS NULL
OR (created_at, id) < ($1, $2::uuid)
That form only covers the transition from non-null rows into the NULLS LAST tail. Once the cursor itself is null, you need a separate branch. This is why nullable sort keys are usually more expensive than they look.
Mixed-direction ordering
A row tuple comparison only tells one direction story. This ordering tells two:
ORDER BY score DESC, id ASC
After a cursor (score, id), the correct forward condition is:
WHERE score < $1
OR (score = $1 AND id > $2::uuid)
score moves downward, but the tiebreaker moves upward. If the order becomes more complicated than two columns, write a small test that compares a paginated walk against one baseline ORDER BY query. Once the ordering grows past two columns, a small executable test beats mental algebra.
Filter changes
Fixed filters belong in the query and in the index. Changing filters are different: the values stay outside the cursor, but the cursor still carries a digest of the filter set that created it. Otherwise a cursor produced for one filtered feed can be replayed against another feed as if nothing happened.
For a fixed published/active feed, the useful index shape is usually:
CREATE INDEX idx_posts_status_created_at_id
ON posts (status, created_at DESC, id DESC);
Equality columns come first. Sort columns come after them. If the API accepts many optional filter combinations, do not create an index for every permutation; pick the few feed shapes that matter and measure the rest.
Deletes, inserts, and mutable keys
Deleting a row after a cursor was issued is usually fine because the cursor points to a position; it doesn't pin the physical row that happened to be there.
Late inserts are different. A row whose sort key falls behind the cursor won't come back later, even when its commit happened after the cursor was created. This can happen with out-of-order sequence allocation or timestamps generated before a long transaction commits. Infinite scroll feeds usually accept that behavior. Exports and reconciliation jobs often can't accept that gap.
Mutable sort keys are worse. If a user can edit created_at — or whatever column drives the feed — the row can jump across positions the client already consumed. I prefer immutable keys for cursor feeds. When the key genuinely has to change, say so in the API contract: is this a moving view, or a snapshot-like walk?
Ship the API
The HTTP shape can stay small:
GET /posts?limit=20&after=eyJ2IjoxfQ.signature
{
"data": [
{
"id": "bf011d9e-5148-4a43-ac14-ef1bd0deeb07",
"createdAt": "2026-01-02T06:22:41.000Z",
"title": "post-1042"
}
],
"pageInfo": {
"nextCursor": "eyJ2IjoxfQ.signature",
"prevCursor": null,
"hasNextPage": true,
"hasPreviousPage": false
}
}
Cap limit at a value your UI can actually render, often 50 or 100. In this design an invalid cursor returns 400 because the client sent something the server can't interpret. If your API already uses 422 for semantic validation, use that instead — consistency matters more than winning an argument about status codes.
Migrating from OFFSET does not require a flag day:
- Add cursor fields to the existing response while keeping
page/offset. - Ship keyset for “next page” traffic and keep numbered pages for legacy clients.
- Stop promising arbitrary jumps for the new feed; keyset does not know what page 37 means without walking there.
- Move counts out of the pagination hot path. Use an approximate count, a cached count, or no count.
- Remove
OFFSETonly after measuring the share of traffic still using it.
Verify it before production
The companion repository contains the schema, TypeScript/Python/Java implementations, Docker Compose setup, benchmark, correctness harness, and the demo_walk.py script behind the recording above.
docker compose up -d
pip install -r requirements.txt
python benchmark.py
python correctness_test.py
python demo_walk.py
If you don't want to run anything, the artifacts are checked in next to the scripts: benchmark_results.json, the raw EXPLAIN plans at depth 100k, and correctness_results.json. They are the exact files the images on this page were captured from.
benchmark.py reseeds 1.2 million rows, so don't run it casually against a shared database. The correctness harness reseeds a small fixture; run it after the benchmark if you want a fast local database again.
On your own database, don't trust the query shape. Read the plan:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at, title
FROM posts
WHERE status = 'published'
AND deleted_at IS NULL
AND (created_at, id) < ('2026-01-02 06:22:41+00', 'bf011d9e-5148-4a43-ac14-ef1bd0deeb07')
ORDER BY created_at DESC, id DESC
LIMIT 21;
You want to see an index scan with Index Cond containing the cursor comparison. If PostgreSQL scans a large number of rows before applying the cursor, the index and ORDER BY probably do not match. The database indexing recipe goes deeper on composite index shape, and the PostgreSQL query optimization recipe covers the general tuning workflow.
FAQ
When is OFFSET still acceptable?
Use it when the result set is small, the maximum page is bounded, or users truly need random page access. A twenty-page admin report does not deserve cursor machinery. A public feed that clients can scroll indefinitely usually does.
Can I use UUIDs in a keyset cursor?
Yes, but random UUIDs are only tiebreakers. They do not encode creation order. If you want roughly time-ordered UUIDs, use UUIDv7 or a monotonic id; otherwise keep the timestamp as the primary sort key and UUID as the unique final column.
Should the cursor expire?
It depends on the feed. Short-lived cursors reduce replay and schema-drift problems, but they also break tabs left open overnight. If you expire cursors, return a clear error and let the client restart from the first page intentionally.
Does keyset pagination give me a consistent snapshot?
No. It gives you a stable walk through an ordering, not a database snapshot. Rows committed behind the cursor stay behind it. Rows ahead of it can appear. Use snapshot export, logical replication position, or a high-water mark if you need stronger consistency.
See Also
- PostgreSQL LIMIT and OFFSET documentation
- PostgreSQL row comparison documentation
- Use The Index, Luke: Paging Through Results
Originally published at StackPractices.




Top comments (2)
Mathias, the number that reframes this for me is not the 3,041.2x at 1M rows — it is the keyset column staying at 0.023–0.067 ms while OFFSET climbs from 0.032 ms to 139.894 ms. The flat line is the argument, not the ratio.
The part I would press on before using this: your correctness harness proves 42/42 rows with 0 duplicates and 0 skips, but the benchmark runs on 1.2 million rows. Did the duplicate-timestamp and backward-navigation checks run against the same 1.2M-row table, or only the 42-row fixture? That matters because the id tiebreaker only earns its keep when created_at actually collides, and 42 rows cannot show the collision rate at 1.2M scale.
The second gap is the NULL tail — you are clear that once the cursor itself is null you need a separate branch, and that making the sort key NOT NULL is the least surprising fix. In the companion repo, is that branch implemented, or does the schema enforce NOT NULL so the branch never runs? If the schema enforces it, that is the rule worth stating up front.
Which would you test first on a feed where created_at can be edited after publish — the mutable-key jump, or the late-arriving row that lands behind the cursor?
@userxnom thanks for reading it this closely — and the flat line framing is better than the one I used. Stealing it.
On the harness: honest answer, the correctness suite ran against the 42-row fixture, not the 1.2M table. The defense I'd offer is that the fixture isn't average-case data, it's engineered worst case. Duplicate created_at values are forced in on purpose, interleaved with distinct ones. And whether the tiebreaker logic is correct doesn't really depend on volume: (created_at, id) either sorts deterministically or it doesn't, and forced collisions at 42 rows prove that.
But you're right about the part I didn't do. The benchmark table uses generated timestamps, so I can't claim the 1.2M run actually exercised collisions at scale. Fair gap, and honestly it's now the first one I want to close.
You guessed right on NULLs too: the schema enforces created_at TIMESTAMPTZ NOT NULL, so the null-key branch never runs in the companion. Which means you're also right that it shouldn't be sitting in the edge-case section. It's effectively a precondition of the design. I'm pulling that line up front in the piece.
Mutable-key first, and it's not close. The late row behind the cursor is stable-snapshot behavior — annoying in a live feed, sure, but nothing gets corrupted. It's the same trade streams make on purpose. A mutated sort key silently breaks the contract: rows you already saw come back into the window, rows you never saw get skipped, and the client can't even tell it happened. If created_at can be edited after publish, it's not a keyset key anymore. It's updated_at wearing a costume. Pick the column you actually mean.