Keyset pagination in Postgres: why OFFSET gets slow on deep pages, and the cursor query that doesn't
Why LIMIT/OFFSET pagination slows down page after page in PostgreSQL and returns duplicate or missing rows while data changes, and how keyset (cursor, seek) pagination with a row comparison and a matching index fixes both. Includes measurements on 1,000,000 rows, previous-page and has-more queries, and four traps: non-unique sort keys, NULLs, mixed sort directions and missing indexes. Every query replayed on Postgres 17.11.
On this page
LIMIT 20 OFFSET 200000 looks like it reads 20 rows. It reads 200,020 and throws away 200,000. That is why list pages and APIs that paginate with OFFSET get slower the further a user scrolls, and why infinite scroll sometimes shows the same item twice. Keyset pagination (also called cursor or seek pagination) fixes both: instead of telling Postgres how many rows to skip, you tell it where the last page ended, and an index jumps straight there. In this post we measure the difference on a million rows, write the query for single-column, multi-column and mixed-direction sort orders, and go through the four traps that make keyset pages silently skip rows. Every query result, plan and timing below comes from scripted replays on PostgreSQL 17.11, the major version Relyt One runs.
- Replace
OFFSET nwithWHERE (sort_key, id) < (:last_sort_key, :last_id), keep the sameORDER BY sort_key DESC, id DESC LIMIT n, and create an index on(sort_key, id). - Always add a unique tie-breaker (usually the primary key) to both the
ORDER BYand the cursor. Without it, rows that share a sort value disappear at page boundaries. - Keep sort keys
NOT NULL, or sort onCOALESCE(...). A row comparison with aNULLis neither true nor false, so those rows never come back. - Row comparisons only work when every column sorts in the same direction. For
created_at DESC, id ASC, expand the comparison and add a bound on the leading column so the index is still used. - Keyset can't jump to page 7,000. It is the right fit for "next / previous" and infinite scroll. If you need page numbers, keep
OFFSETfor the first few pages, or show an estimated total.
The PostgreSQL manual says it in one sentence: "The rows skipped by an OFFSET clause still have to be computed inside the server; therefore a large OFFSET might be inefficient." An index helps Postgres produce rows in order, but it can't tell Postgres which row is the 200,001st without walking past the first 200,000.
Here is the test table: one million events, two per second, with an index that matches the sort order.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL,
user_id int NOT NULL,
payload text NOT NULL
);
INSERT INTO events (created_at, user_id, payload)
SELECT timestamptz '2026-01-01 00:00:00+00' + (g / 2) * interval '1 second',
g % 5000,
repeat(md5(g::text), 3)
FROM generate_series(1, 1000000) AS g;
CREATE INDEX events_created_id ON events (created_at, id);
VACUUM ANALYZE events;The table is 142 MB and the index 30 MB. Page 10,001 of a "newest first" feed with OFFSET:
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, COSTS OFF)
SELECT id, created_at, user_id FROM events
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 200000; Limit (actual rows=20 loops=1)
Buffers: shared hit=5172
-> Index Scan Backward using events_created_id on events (actual rows=200020 loops=1)
Buffers: shared hit=5172
Planning Time: 0.058 ms
Execution Time: 15.716 msThe plan is already as good as OFFSET gets: it walks the index backwards, so there is no sort. But the index scan still returned 200,020 rows to the Limit node, and Postgres touched 5,172 buffers (8 kB pages) to get them.
Instead of a page number, the client sends back the sort key and id of the last row it received. The next page is "the 20 rows that come after that row in this order":
-- last row of the previous page: created_at = 2026-01-05 15:06:40+00, id = 800001
SELECT id, created_at, user_id FROM events
WHERE (created_at, id) < ('2026-01-05 15:06:40+00', 800001)
ORDER BY created_at DESC, id DESC
LIMIT 20; Limit (actual rows=20 loops=1)
Buffers: shared hit=3 read=1 written=1
-> Index Scan Backward using events_created_id on events (actual rows=20 loops=1)
Index Cond: (ROW(created_at, id) < ROW('2026-01-05 15:06:40+00'::timestamp with time zone, 800001))
Buffers: shared hit=3 read=1 written=1
Planning Time: 0.038 ms
Execution Time: 0.046 ms(created_at, id) < (a, b) is a row constructor comparison. Postgres compares the elements left to right and stops at the first pair that differs, so it means exactly "created_at < a, or created_at = a and id < b", which is "comes after this row" in a DESC, DESC order. A B-tree index on (created_at, id) can use it as an Index Cond: Postgres seeks to that position in the index and reads the next 20 entries. In our replay both queries returned the same 20 ids.
We ran each query nine times with EXPLAIN (ANALYZE, BUFFERS, TIMING OFF) and took the median of the reported execution time. That is time spent inside the server only, without network and client time, with a warm cache. We replayed the benchmark four times, each in a fresh container. Buffer counts were identical every time and timings stayed within a few percent; the table shows the range of the medians.
| Page | OFFSET | Keyset |
|---|---|---|
| 1 | 0.01 ms | 0.01 ms |
| 101 | 0.15–0.16 ms | 0.01 ms |
| 1,001 | 1.5–1.6 ms | 0.01 ms |
| 10,001 | 15–16 ms | 0.01 ms |
| 50,000 (last) | ~130 ms | 0.01 ms |
At those five depths OFFSET touched 4, 56, 522, 5,172 and 25,847 buffers; keyset touched 4 or 5 at every depth. OFFSET grows in a straight line with the page number, because the work is proportional to the number of rows skipped.
The setup: Docker postgres:17.11-alpine with default settings (including the 128 MB shared_buffers, so on the deepest pages part of the table came from the operating system's page cache rather than Postgres's own buffers) on an Apple M1 Pro (5 CPUs and 12 GB given to Docker). Absolute numbers will differ on your hardware; the shape won't. Two things make real systems look worse than this table:
- Cold pages. When the skipped rows are not in memory, every one of those thousands of buffers can become a disk read. Keyset reads the same handful of pages no matter how deep the user goes.
- Wider rows and joins.
OFFSETproduces every skipped row before throwing it away, so the more work each row takes, the more work is wasted. Our rows were about 140 bytes and the query had no joins.
Page 1 costs the same either way. If nobody ever goes past page 3, OFFSET is fine. The trouble starts with infinite scroll, API clients that export by walking every page, and crawlers that follow "next" links to the end.
Speed is only half of it. OFFSET counts positions, and positions move when rows are inserted or deleted between two requests. Take a small table of ten posts, one per hour, and a page size of 3, newest first:
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL,
title text NOT NULL
);
INSERT INTO posts (created_at, title)
SELECT timestamptz '2026-11-01 00:00:00+00' + g * interval '1 hour', 'post ' || g
FROM generate_series(1, 10) AS g;
CREATE INDEX posts_created_id ON posts (created_at, id);
SELECT id, title FROM posts ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 0;
-- 10, 9, 8
-- a new post (id 11) is published before the user asks for page 2
INSERT INTO posts (created_at, title) VALUES ('2026-11-01 11:00:00+00', 'post 11');
SELECT id, title FROM posts ORDER BY created_at DESC, id DESC LIMIT 3 OFFSET 3;
-- 8, 7, 6 <- post 8 againThe new row pushed everything down one position, so post 8 appears at the end of page 1 and again at the start of page 2. A delete does the opposite. Starting again from page 1 (10, 9, 8), if post 9 is deleted before page 2, OFFSET 3 returns 6, 5, 4: post 7 is never shown.
The keyset query for page 2 says "after post 8" and doesn't care what happened above it:
SELECT id, title FROM posts
WHERE (created_at, id) < ('2026-11-01 08:00:00+00', 8)
ORDER BY created_at DESC, id DESC
LIMIT 3;
-- 7, 6, 5 after the insert, and also after the deleteKeyset is not a snapshot. A row inserted below the cursor will show up on a later page, which is usually what you want in a feed. If you need a frozen result set, for example for an export, keep one transaction open with REPEATABLE READ, or use a server-side cursor (DECLARE ... CURSOR) inside a transaction.
Paginating on created_at alone looks fine until several rows share a timestamp. We reloaded the ten posts so that posts 3 to 7 all have created_at = 12:00. Newest first, the order is 7, 6, 5, 4, 3 (all 12:00), then 10, 9, 8, 2, 1:
-- page 1: ORDER BY created_at DESC LIMIT 3 -> 7, 6, 5 (all at 12:00)
SELECT id, created_at FROM posts
WHERE created_at < '2026-11-01 12:00:00+00'
ORDER BY created_at DESC LIMIT 3;
-- 10, 9, 8 <- posts 4 and 3 (also 12:00) are skippedcreated_at < 12:00 excludes the two 12:00 posts that didn't fit on page 1. Add the primary key as a tie-breaker in both the ORDER BY and the cursor, and page 2 is 4, 3, 10. The manual makes the same point about LIMIT in general: use an ORDER BY "that constrains the result rows into a unique order". In real tables, timestamps collide more than you think: bulk imports, rows written in one transaction (now() returns the transaction start time, so every row gets the same value), and clients that send times rounded to the second.
Postgres sorts NULLs last in ascending order by default. But a row comparison that meets a NULL doesn't return true or false. The manual: "If either of this pair of elements is null, the result of the row comparison is unknown (null)", and WHERE drops rows whose condition is unknown.
CREATE TABLE tasks (id int PRIMARY KEY, due date);
INSERT INTO tasks VALUES (1, '2026-12-01'), (2, NULL), (3, '2026-12-03'), (4, NULL), (5, '2026-12-05');
-- ORDER BY due, id gives 1 (Dec 1), 3 (Dec 3), 5 (Dec 5), 2 (NULL), 4 (NULL)
SELECT id, due FROM tasks
WHERE (due, id) > ('2026-12-05', 5)
ORDER BY due, id LIMIT 2;
-- (0 rows) <- tasks 2 and 4 are never shownThe fix is to keep sort columns NOT NULL, or to sort on an expression that has no NULLs and use the same expression in the cursor (and in an expression index):
SELECT id, due FROM tasks
WHERE (COALESCE(due, 'infinity'), id) > ('2026-12-05', 5)
ORDER BY COALESCE(due, 'infinity'), id LIMIT 2;
-- 2, 4
CREATE INDEX tasks_due_id ON tasks ((COALESCE(due, 'infinity')), id);A row comparison has one direction. With the same ten posts, for "newest first, and among equal timestamps the lowest id first" (ORDER BY created_at DESC, id ASC), (created_at, id) < (a, b) is wrong. With page 1 ending at (12:00, 5), it returned 3, 4, 10: posts 3 and 4 again, and 6 and 7 skipped. Write the comparison out instead:
SELECT id, created_at FROM posts
WHERE created_at < '2026-11-01 12:00:00+00'
OR (created_at = '2026-11-01 12:00:00+00' AND id > 5)
ORDER BY created_at DESC, id ASC
LIMIT 3;
-- 6, 7, 10That returns the right rows, but check the plan on a big table. On our million rows with the DESC, DESC order, the expanded OR form was not used as an index condition. Postgres scanned the index from the top and filtered:
-> Index Scan Backward using events_created_id on events (actual rows=20 loops=1)
Filter: ((created_at < '2026-01-05 15:06:40+00'::timestamp with time zone) OR (...))
Rows Removed by Filter: 200000
Execution Time: 24.409 msThat is no better than OFFSET. Adding a redundant bound on the leading column gives Postgres something to seek on:
WHERE created_at <= :last_created_at
AND (created_at < :last_created_at OR (created_at = :last_created_at AND id < :last_id)) Index Cond: (created_at <= '2026-01-05 15:06:40+00'::timestamp with time zone)
Rows Removed by Filter: 1
Execution Time: 0.021 msThe same trick applies to the mixed order: for ORDER BY created_at DESC, id ASC, the condition becomes
WHERE created_at <= :last_created_at
AND (created_at < :last_created_at OR (created_at = :last_created_at AND id > :last_id))On our million rows this ran in 0.05 ms with only the (created_at, id) index: Postgres seeks with the same Index Cond and adds an Incremental Sort to reorder rows that share a timestamp. With an index whose directions match the query, (created_at DESC, id ASC), the sort step disappears (0.04 ms). A B-tree index can be scanned forwards or backwards, which covers ASC, ASC and DESC, DESC with one index, but not a mix of the two.
Keyset is only fast because the index can find the starting point and already has rows in the right order. We dropped events_created_id and ran the same page 10,001 query with only the primary key left:
Limit
-> Gather Merge
Workers Planned: 2
-> Sort
Sort Key: created_at DESC, id DESC
-> Parallel Seq Scan on events
Filter: (ROW(created_at, id) < ROW(...))About 47 ms (medians of 46–49 ms across replays) and 18,212 buffers: a scan of the whole table on every page. When you filter as well, the columns you filter on with = go first, then the sort columns. For a per-user feed:
CREATE INDEX events_user_created_id ON events (user_id, created_at, id);
SELECT id, created_at FROM events
WHERE user_id = 42 AND (created_at, id) < (:last_created_at, :last_id)
ORDER BY created_at DESC, id DESC
LIMIT 20; -> Index Only Scan Backward using events_user_created_id on events (actual rows=20 loops=1)
Index Cond: ((user_id = 42) AND (ROW(created_at, id) < ROW(...)))
Execution Time: 0.022 msPrevious page. Flip the comparison and the order, then flip the result back. With the ten posts from trap 1, if the current page is 4, 3, 10 and starts with (12:00, 4):
SELECT * FROM (
SELECT id, created_at FROM posts
WHERE (created_at, id) > ('2026-11-01 12:00:00+00', 4)
ORDER BY created_at ASC, id ASC
LIMIT 3
) AS prev
ORDER BY created_at DESC, id DESC;
-- 7, 6, 5Is there a next page? Ask for one row more than the page size. If you get LIMIT + 1 rows, show LIMIT and render a "next" link; otherwise this is the last page. No count(*) needed.
What about the total? An exact count(*) has to read the whole table or index. On our million rows it took about 25 ms, and it grows with the table. If a rough number is enough ("about 1M results"), the planner's estimate is free: SELECT reltuples::bigint FROM pg_class WHERE relname = 'events' returned 1,000,000 here after ANALYZE. For filtered queries, the row estimate in EXPLAIN output is a common approximation, with the caveat that it can be far off.
The cursor. Don't make clients build WHERE clauses. Give them an opaque token that encodes the last row's sort values, and decode and validate it on the server. Most apps do this in application code. In SQL, it can look like this:
-- encode the last row of a page (\gset stores it in the psql variable "cursor")
SELECT encode(convert_to(json_build_object('t', created_at, 'id', id)::text, 'UTF8'), 'base64') AS cursor
FROM posts ORDER BY created_at DESC, id DESC LIMIT 1 OFFSET 2 \gset
\echo :cursor
-- eyJ0IiA6ICIyMDI2LTExLTAxVDEyOjAwOjAwKzAwOjAwIiwgImlkIiA6IDV9
-- decode it for the next query
SELECT (convert_from(decode(:'cursor', 'base64'), 'UTF8')::json ->> 't')::timestamptz AS t,
(convert_from(decode(:'cursor', 'base64'), 'UTF8')::json ->> 'id')::bigint AS id;
-- 2026-11-01 12:00:00+00 | 5If the token goes into a URL, use URL-safe base64 (base64url) in your application: standard base64 contains +, / and =, and Postgres's encode(..., 'base64') also inserts a line break every 76 characters. Base64 is encoding, not protection: anyone can decode and change the token. That is fine as long as the server treats the decoded values as untrusted input, passes them as query parameters, and applies the same access filters (user_id = $1, row-level security) as any other query. Keep the exact timestamp precision in the token. Postgres stores microseconds, and a cursor truncated to milliseconds or seconds can skip or repeat rows that share the same millisecond or second.
- Admin screens and small result sets where nobody pages far. Below a few thousand skipped rows, the difference in our table was about a millisecond or less.
- UIs that really need "jump to page 37". A common compromise is page numbers for the first pages plus "next" beyond them.
- Sorts that can't be backed by an index, such as ranking by a computed score. Keyset needs a stable, indexable sort key.
Everywhere else, and especially in public APIs, infinite scroll and batch jobs that walk a whole table, keyset is faster and returns each row once.
Everything in this post is standard PostgreSQL 17 SQL with no extensions, which is what Relyt One runs. The part that is hard to judge on a laptop is your own data: how many rows share a timestamp, whether the sort column has NULLs, and whether the planner picks your new index. On Relyt One you can create a branch from your production database, which starts from the parent's data with copy-on-write storage and runs on its own compute. Create the index there, compare EXPLAIN (ANALYZE, BUFFERS) for your deepest pages with OFFSET and with keyset, and delete the branch when you're done.
Related reading: why Postgres sometimes ignores your index, and the manual's chapter on LIMIT and OFFSET.



