Keyset pagination in Postgres: why OFFSET gets slow
Replace OFFSET with keyset pagination in Postgres: row comparisons, tie-breakers, mixed sort orders, and the timestamp and plan-cache traps.
· 8 min read
- Postgres
- Pagination
- Performance
Almost every list endpoint starts with LIMIT 20 OFFSET 40. It is easy to write and it works in development. It has two problems that only show up later. It gets slower the deeper you go, and it can show a client the same row twice, or miss one, while the data is changing.
Keyset pagination (also called cursor or seek pagination) fixes both. Instead of “skip 40 rows”, the client says “give me the rows after this one”. This article covers how to write that correctly in Postgres, including the mistakes that pass a quick test and fail in production.
Everything here was run on PostgreSQL 16 with Node.js 22 and the pg driver, against a table of two million rows. Timings are from one small machine, so read them as relative, not absolute.
What OFFSET costs
The table:
CREATE TABLE posts (
id bigserial PRIMARY KEY,
created_at timestamptz NOT NULL,
title text NOT NULL
);
CREATE INDEX posts_created_id ON posts (created_at DESC, id DESC);
Page one is cheap, because the index already has the rows in order:
SELECT id, created_at, title FROM posts
ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 0;
EXPLAIN (ANALYZE, BUFFERS) shows an index scan returning 20 rows, in about 0.04 ms. Now ask for page 50,001:
... LIMIT 20 OFFSET 1000000;
The plan is the same index scan, but it reads 1,000,020 rows and throws the first million away. That touched 11,188 buffers and took roughly 100 to 215 ms across runs. The cost grows in step with the offset:
| OFFSET | Execution time (several runs) |
|---|---|
| 0 | 0.03 to 0.05 ms |
| 1,000 | 0.1 to 0.3 ms |
| 100,000 | 11 to 30 ms |
| 1,000,000 | 100 to 215 ms |
An index cannot help here. Postgres has to walk past every skipped row to know where the page starts. Crawlers, exports and “next page” loops are the usual way someone ends up at offset one million.
Rows move while you page
The second problem is correctness. We fetched page 2 (rows 21 to 40), inserted five new rows at the top of the ordering, then fetched page 3 with OFFSET 40. Five of the twenty rows on page 3 had already appeared on page 2. The new rows pushed everything down. Deletes do the opposite and make rows vanish.
For a feed, this is an irritation. For a job that walks a table to sync or export it, it is a bug.
The keyset form
Remember the last row you returned, and ask for rows that sort after it. Postgres supports row-wise comparison, which compares the columns left to right, like sorting words:
SELECT id, created_at, title FROM posts
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;
With $1 and $2 taken from the last row of the previous page, the plan shows the comparison as an Index Cond. Postgres goes straight to the right place in the index and reads 20 entries. We ran this at the one-millionth row: 4 buffers, about 0.05 ms, the same as page one. The cost no longer depends on depth.
It also fixes the drift. Our test deleted the cursor row and inserted five new rows at the top, then fetched the next page with the same cursor. The next page of three rows came back identical to the one we fetched before the changes.
Three rules make it work.
The sort must be unique. The id in (created_at, id) is the tie-breaker. Without it, rows with the same created_at are ordered arbitrarily, and the comparison cannot say where one page ended. Always end the sort with a unique column, usually the primary key.
The index must serve the sort. The index above is on (created_at DESC, id DESC), the same columns in the same order. (An index with every column ascending would also work, since Postgres can scan it backwards. Mixed directions are where it matters, below.) If your list has a filter such as WHERE account_id = $1, put that column first in the index.
The sort columns must be NOT NULL. Comparing a row containing NULL gives NULL, so such rows are silently dropped. Use COALESCE in both the index and the query if you cannot avoid nulls.
Don’t compare on the first column alone. This is the mistake that passes a demo. Using WHERE created_at < $1 looks right, but a page boundary can fall in the middle of a group of rows sharing a timestamp, and the rest of the group is skipped. We loaded 10,000 rows with 20 per timestamp and paged through them 25 at a time. The created_at-only version returned 6,250 rows. The tuple version returned all 10,000, each once. In real data, timestamps collide more often than you expect, especially on bulk inserts, where now() returns the same value for every row in a transaction.
A cursor you can hand to clients
The helper fetches one more row than the page size. If that row comes back, there is another page and it is dropped. This avoids a count(*) and an empty final page. Treat the cursor as opaque. Encode the sort key into one string, so you can change it later without breaking clients. Here is a complete helper:
const encode = (row) =>
Buffer.from(JSON.stringify([row.ts, row.id])).toString("base64url");
class BadCursor extends Error {}
function decode(cursor) {
try {
const [ts, id, ...rest] = JSON.parse(Buffer.from(cursor, "base64url").toString());
if (
rest.length ||
typeof ts !== "string" ||
!/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d(\.\d{1,6})?[+-]\d\d(:\d\d)?$/.test(ts) ||
!/^\d{1,18}$/.test(String(id))
) throw new Error();
return { ts, id: String(id) };
} catch {
throw new BadCursor("bad cursor");
}
}
const COLS = "id, title, created_at, created_at::text AS ts";
const ORDER = "ORDER BY created_at DESC, id DESC LIMIT $1";
export async function listPosts(db, { limit = 20, cursor } = {}) {
limit = Math.min(Math.max(Number(limit) | 0, 1), 100);
const after = cursor ? decode(cursor) : null;
const { rows } = after
? await db.query(
`SELECT ${COLS} FROM posts
WHERE (created_at, id) < ($2::timestamptz, $3::bigint)
${ORDER}`,
[limit + 1, after.ts, after.id],
)
: await db.query(`SELECT ${COLS} FROM posts ${ORDER}`, [limit + 1]);
const page = rows.slice(0, limit);
return {
items: page.map(({ ts, ...row }) => row),
nextCursor: rows.length > limit ? encode(page.at(-1)) : null,
};
}
We walked all two million rows with it in pages of 1,000 and got every row once. Catch BadCursor in your handler and return HTTP 400, and clamp limit as shown. Two details in this code matter. (The ::text cast assumes the default ISO DateStyle.)
Send the timestamp as text. The pg driver turns timestamptz into a JavaScript Date, which holds milliseconds. Postgres stores microseconds. If the cursor is built from the Date, the cursor is slightly earlier than the real row, and rows in between are skipped. We stored rows 100 microseconds apart and paged 25 at a time: the Date cursor returned 8,335 of 10,000 rows with no error, and a cursor built from created_at::text returned all of them. The query selects created_at::text AS ts for exactly this reason.
Ids are strings. A bigint comes back from pg as a string, because it can exceed JavaScript’s safe integer range. Keep it as a string end to end and cast in SQL, as above.
Two queries, not one
It is tempting to write a single statement for both cases:
WHERE $1::timestamptz IS NULL OR (created_at, id) < ($1::timestamptz, $2::bigint)
It works, and it can be very slow. A prepared statement is planned with the real parameter values for its first five executions. After that Postgres may switch to a generic plan, built without knowing the values, and then it cannot know whether $1 is null. The plan scans the index from the start and discards rows through a filter. With a named query in pg, the sixth run went from under a millisecond to about 100 ms. Forcing a generic plan (SET plan_cache_mode = force_generic_plan) gave the same result, with one million rows removed by the filter.
Plain unnamed client.query(text, values) calls did not switch in our runs, but drivers and ORMs that always prepare statements can. Keep the first page and later pages as separate statements, as in the helper above, and the question never arises.
Mixed sort directions
Row comparison assumes every column sorts the same way. Suppose the list is ORDER BY score DESC, id ASC, with an index on (score DESC, id ASC). Then (score, id) < (500, 5000) is the wrong condition. On a million-row test table (an id, a score and a payload column, with an index on (score DESC, id ASC)) it matched 500,005 rows where the correct answer was 500,995. It runs, and it returns the wrong rows.
The correct condition spells out the two cases:
WHERE score < 500 OR (score = 500 AND id > 5000)
ORDER BY score DESC, id ASC LIMIT 20
Written like that, Postgres could not use the first part as an index condition. It scanned from the top and filtered out 499,005 rows. That took about 550 ms when the rows had to be fetched from the table, and tens of milliseconds with an index-only scan. Add a redundant bound on the leading column:
WHERE score <= 500 AND (score < 500 OR id > 5000)
ORDER BY score DESC, id ASC LIMIT 20
Now score <= 500 is an Index Cond, the rest is a cheap filter, and the same page took under 0.2 ms. The work is bounded by the size of one score group. When you can, avoid the problem: give every column in the sort the same direction.
What you give up
Keyset pagination has real limits:
- No jumping to page 37. You can only move from one page to the next. That suits feeds, APIs, exports and infinite scroll. It does not suit a screen with numbered pages.
- No cheap total.
count(*)over a large table is its own cost. Show “more results” instead of “page 3 of 5,000”, or keep an approximate count. - The sort order is fixed by the index. Every sort option a user can choose needs its own index and its own cursor shape.
- Late commits can be missed. A row committed after you passed its position, with an earlier key, never appears. That is fine for feeds. For an incremental sync, add a safety margin or use a sequence-based cursor.
For small, stable tables, OFFSET is fine. Use keyset for anything that is an API, a sync, or a walk over everything. For another case where one well-indexed query does the heavy lifting, see our Postgres job queue with SKIP LOCKED.
If you’re designing an API, a data pipeline or the database behind them, see our backend development service.