•4 min read

Keyset Pagination in Postgres: Page 2 Was Page 1 Again

A pause long enough to click twice

Support asked me to find an order from last winter. The admin list pages through eight million rows by now, and getting there took a visible pause, long enough that I clicked twice and got two identical screens. That's a pagination bug of its own; we'll come back to it.

I rebuilt the query on a scratch Postgres 16.15 cluster with two million synthetic orders so the numbers came from clean data, then swapped the endpoint to keyset pagination. The swap is where this got interesting: my first version served page one for page two, and nobody would have noticed for a week.

OFFSET only hurts when an index is doing the ordering

Twenty rows per page, ordered by created_at, id:

OFFSETno indexindex on (created_at, id)
058.3 ms0.03 ms
100,00096.6 ms5.8 ms
1,000,000163.9 ms61.8 ms
1,900,000411.3 ms111.4 ms

Without the index every page pays for sorting the whole table, and page one is already 58 ms, so nothing about the offset stands out until the sort starts spilling to disk near the end. Add the index and page one costs 0.03 ms while the whole price moves into the walk: the planner reads rows=1900020 to hand back twenty, and time grows with how far you scrolled rather than with the work you asked for.

A pager that feels sluggish at page three is usually a sort that doesn't match an index, not the offset.

Keyset at the same spot: 0.07 ms, twenty rows read, one Index Cond: ROW(created_at, id) > ROW(...). Fifteen hundred times cheaper at the bottom of two million rows.

Passengers queueing toward a boarding gate under a lit gate sign

The comparison that runs backwards

I wrote the line every article shows you:

WHERE (created_at, id) < ($1, $2)

It worked, tests passed, I moved on. Except the sort clause in that endpoint was ORDER BY created_at DESC, id ASC. Someone bolted the tiebreaker on months later and reached for the direction that feels normal for an id.

A row comparison expands to a < x OR (a = x AND b < y). One operator, both columns. There's no tuple syntax for "descending first, ascending second", and Postgres won't warn you. It answers a different question.

Fifty rows sharing one timestamp, page size twenty. Page one is ids 50000 to 50019, page two should be 50020 to 50039. The tuple comparison returned 50000 ... 50018. Page two, delivered as page one.

Spelling the predicate out fixes the rows:

WHERE created_at < $1 OR (created_at = $1 AND id > $2)

It costs the index condition though. The plan becomes an incremental sort over a backward index scan with Rows Removed by Filter: 99952, 4.9 ms instead of 0.07. So either point the tiebreaker the same way as the sort column and keep the tuple, or accept the OR and reread the plan whenever the sort clause changes.

A cursor that quietly ends the list

The second endpoint sorts by last_note_at DESC, nullable, null for anything nobody has touched. Postgres puts nulls first when you sort descending. Page one is entirely nulls, the cursor from its last row is NULL, and the next request compares against NULL, which matches nothing.

Zero rows. No error, no log line. The list stops after twenty entries, which looks to a user like an account with twenty items.

Checked both ways: a cursor of (NULL, 7) returns 0 rows, a real timestamp in the same slot returns 282,857. Coalesce the column in the sort and in the index:

CREATE INDEX orders_note_sort ON orders
  ((COALESCE(last_note_at, 'epoch'::timestamptz)) DESC, id);

First page in 0.019 ms, and the keyset predicate lands as a real index condition rather than a filter. A plain index on (last_note_at, id) is no help here, by the way. With that one in place Postgres still sorted the whole table in 64 ms.

The 456 microseconds nobody passes back

This is the one I would have shipped. node-postgres hands you a timestamptz as a JavaScript Date, and a Date stops at milliseconds:

raw    2026-01-01 11:06:39.123456+00
Date   2026-01-01T11:06:39.123Z

Send that back as a cursor and the boundary row satisfies its own "after" predicate: .123000 sorts before .123456. Page two opens with rows the reader already finished.

correct cursor      1999970, 1999977, 1999984
millisecond cursor  1999956, 1999963, 1999970

Two repeats, and it compounds, because each page then drags the previous one along. Select the sort column as ::text and let the string travel back untouched.

What the query looks like now

SELECT id, created_at::text AS created_at
FROM orders
WHERE (created_at, id) < ($1::timestamptz, $2)
ORDER BY created_at DESC, id DESC
LIMIT 21;

Twenty-one rows so I can show twenty and know whether a next page exists. Timestamp as text. Tiebreaker is the primary key, pointing the same direction as the sort column. Nullable sort columns get coalesced in the ORDER BY, with an expression index behind the result. Where a direction genuinely has to differ, I write the OR by hand and read the plan before merging.

Those shapes live in Snippet Ark now, mostly so I stop re-deriving the OR. And the double click from the start? Guard the button against a second request while the first is in flight. Two identical pages is a frontend bug, but it's a free preview of what a broken cursor looks like.