
LIMIT 20 OFFSET 40 gets slower with every page and shows the wrong rows when data changes. I measured both, then fixed it.
LIMIT 20 OFFSET 40 is in almost every codebase. It's easy to write, every ORM supports it, and it works fine on page 1.
It has two problems. It gets slower the deeper you go, and it returns duplicate or missing rows when data changes between page loads. Most people know the first one in theory. Few have watched the second one quietly break a batch job.
TL;DR: On a 10M-row table, OFFSET took 1.06 s to fetch the last page. Keyset pagination took 0.006 ms. When the data changed between page loads, OFFSET showed 153 duplicates in one test and skipped half the rows of a batch job in another. Keyset had zero errors. Use keyset (cursor) pagination for feeds, APIs, and anything that walks a whole table.
Every number here is measured, not estimated. I ran these queries against a real Postgres server with 10 million rows. The exact scripts are in the "Run it yourself" section near the end.
Problem 1: OFFSET reads every row it skips
OFFSET 1000000 doesn't jump to row 1,000,001. Postgres walks the index from the top, fetches a million rows, throws them away, and then returns your 20. The Postgres docs say it plainly: "The rows skipped by an OFFSET clause still have to be computed inside the server."
Keyset pagination remembers the last row you saw and asks for rows after it. The index jumps straight there.
flowchart LR
subgraph KEY["WHERE (created_at, id) < cursor LIMIT 20"]
direction LR
k1["Jump to the cursor<br/>in the index"]:::step --> k2["Read 20 rows"]:::ok --> k3["Return 20 rows"]:::ok
end
subgraph OFF["OFFSET 1000000 LIMIT 20"]
direction LR
o1["Start at the<br/>top of the index"]:::step --> o2["Read and discard<br/>1,000,000 rows"]:::waste --> o3["Return 20 rows"]:::ok
end
classDef step fill:#1c7ed6,stroke:#1864ab,color:#fff
classDef waste fill:#e8590c,stroke:#c2410c,color:#fff
classDef ok fill:#2f9e44,stroke:#2b8a3e,color:#fffThe setup: Postgres 16.15 with stock config on a 2 vCPU / 7 GB cloud VM. A posts table with 10M rows sorted newest first on (created_at desc, id desc), with one index on exactly that. Each query ran 7 times; the table shows the median server-side execution time.
Rows skipped | OFFSET | Keyset | Rows OFFSET read | Index + table pages OFFSET read |
|---|---|---|---|---|
0 (page 1) | 0.01 ms | 0.01 ms | 20 | 4 |
1,000 | 0.11 ms | 0.01 ms | 1,020 | 16 |
10,000 | 1.1 ms | 0.01 ms | 10,020 | 126 |
100,000 | 8.3 ms | 0.01 ms | 100,020 | 1,221 |
1,000,000 | 88 ms | 0.01 ms | 1,000,020 | 12,169 |
5,000,000 | 541 ms | 0.02 ms | 5,000,020 | 60,828 |
9,999,980 (last page) | 1,063 ms | 0.006 ms | 10,000,000 | 121,651 |
Keyset read 20 rows and 4 pages at every depth. OFFSET's cost grew in proportion to the rows skipped, about 0.1 ms per 1,000 rows:
%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#e8590c, #2f9e44"}}}}%%
xychart-beta
title "Time to fetch one 20-row page"
x-axis "Rows skipped" ["0", "1k", "10k", "100k", "1M", "5M", "10M"]
y-axis "ms" 0 --> 1100
line [0.01, 0.108, 1.1, 8.3, 88.4, 541, 1063]
line [0.008, 0.008, 0.012, 0.009, 0.009, 0.017, 0.006]Orange: OFFSET · Green: keyset (flat at about 0.01 ms)
"Nobody goes to page 50,000" is true for humans. But crawlers do, and so do export jobs, sync jobs, and "load more" buttons someone leaves running. Each of those deep requests can hold a database connection for up to a second.
Problem 2: OFFSET shows the wrong rows when data changes
OFFSET counts positions, not rows. If anything is inserted or deleted above your position between two page loads, every row shifts and the page boundary lands somewhere else.
sequenceDiagram
participant U as User
participant DB as Feed (newest first)
U->>DB: Page 1: OFFSET 0 LIMIT 20
DB-->>U: Posts 100 … 81
rect rgba(232, 89, 12, 0.15)
Note over DB: New post 101 arrives.<br/>Every post moves down one place.
end
U->>DB: Page 2: OFFSET 20 LIMIT 20
DB-->>U: Posts 81 … 62
rect rgba(232, 89, 12, 0.15)
Note over U: Post 81 shown twice
endA deletion does the opposite: rows move up, and one row slides past the boundary without ever being shown.
I measured it. A 2,000-row table, read 20 rows at a time from start to finish, with changes between each page load. Both methods saw exactly the same changes:
What happens between page loads | OFFSET | Keyset |
|---|---|---|
A. 2 new posts arrive, 1 random post is deleted | 153 duplicates (7% of rows shown) | 0 duplicates |
B. 2 random posts are deleted | 94 posts never shown, though they were never deleted | 0 missed |
C. A batch job processes a page, then deletes those rows | Processed 1,000 of 2,000 rows | Processed all 2,000 |
Scenario C is the dangerous one, because nobody sees it happen. The job processes rows 1–20 and deletes them. Now the old rows 21–40 are at the top, and OFFSET 20 jumps right past them. Every other page gets skipped, the job reports success, and half the work never happens. The same thing happens when the job updates rows so they drop out of its WHERE clause.
Keyset pagination doesn't care. It asks for rows older than the last one it saw. Rows inserted above, rows deleted anywhere: the next page is still exactly the next page.
The fix: keyset pagination
Instead of a page number, the client sends back the sort key of the last row it saw:
-- One index that matches the sort order
create index posts_feed_idx on posts (created_at desc, id desc);
-- First page
select id, author_id, created_at, title
from posts
order by created_at desc, id desc
limit 20;
-- Next page: the client sends the created_at and id of the last row it got
select id, author_id, created_at, title
from posts
where (created_at, id) < ($1, $2)
order by created_at desc, id desc
limit 20;(created_at, id) < ($1, $2) is a row comparison. It means "earlier timestamp, or the same timestamp with a smaller id", and Postgres can use it directly as an index condition.
Five rules that make it correct:
End the sort with a unique column.
created_atalone isn't unique. In my table, 3 posts share every second, so a cursor of justcreated_atwould skip or repeat rows at page boundaries. Addingidfixes that.Index the exact sort order. Without a matching index, Postgres has to read and sort every matching row to find your 20.
Row comparison only works when every column sorts the same direction. For
order by price asc, id desc, write it out:where price > $1 or (price = $1 and id < $2)Previous page = flip it. Use
>withorder by created_at asc, id asc, then reverse the 20 rows in your app.Keep the cursor's full precision. Postgres timestamps have microseconds. JavaScript's
Datekeeps only milliseconds, so round-tripping a cursor through it can skip rows. Send the cursor as an opaque string.
I checked these queries on a static table: keyset returned exactly the same rows in the same order as OFFSET, including the previous-page and mixed-direction versions.
The trap: one query for every page
It's tempting to handle the first page and the next pages with a single query:
-- Don't do this
where ($2 is null or (created_at, id) < ($1, $2))That works at first. But many drivers and ORMs use prepared statements, and after 5 executions Postgres may switch to a generic plan that doesn't know whether $2 is null. I tested it. On the 6th call, the plan turned the condition into a filter and walked the index from the top:
Query | Plan | Rows read to return 20 | Time |
|---|---|---|---|
One query with | Filter | 9,740,818 | 1,212 ms |
Separate next-page query | Index Cond | 20 | 0.04 ms |
Keyset with a bad plan is just OFFSET in disguise. Use two separate queries.
What the API looks like
Clients get an opaque cursor, not a page number. That's how Stripe's API works, for example: starting_after=<last object id>, plus a has_more flag.
{
"data": [ ... 20 posts ... ],
"next_cursor": "WyIyMDI1LTAxLTI3VDAxOjAwOjAwLjEyMzQ1NiswMDowMCIsIDcwMDAwMDBd"
}A small helper in Python. Fetch one extra row to know whether another page exists, and reject cursors you can't parse:
"""Opaque pagination cursors: encode the last row's sort key, decode it on the next request."""
import base64
import json
from datetime import datetime
def encode_cursor(created_at: datetime, id: int) -> str:
raw = json.dumps([created_at.isoformat(), id]).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def decode_cursor(cursor: str) -> tuple[datetime, int]:
try:
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
ts, id = json.loads(raw)
return datetime.fromisoformat(ts), int(id)
except (ValueError, TypeError) as e:
raise ValueError("invalid cursor") from e
FIRST_PAGE = """
select id, author_id, created_at, title from posts
order by created_at desc, id desc
limit %(limit)s"""
NEXT_PAGE = """
select id, author_id, created_at, title from posts
where (created_at, id) < (%(at)s, %(id)s)
order by created_at desc, id desc
limit %(limit)s"""
def list_posts(db, cursor: str | None = None, limit: int = 20) -> dict:
if cursor:
at, id = decode_cursor(cursor)
rows = db.execute(NEXT_PAGE, {"at": at, "id": id, "limit": limit + 1}).fetchall()
else:
rows = db.execute(FIRST_PAGE, {"limit": limit + 1}).fetchall()
page, has_more = rows[:limit], len(rows) > limit # 1 extra row tells us if there's more
last = page[-1] if page else None
return {
"data": page,
"next_cursor": encode_cursor(last["created_at"], last["id"]) if has_more else None,
}It needs Python 3.10+ and assumes rows come back as dicts (for example, psycopg's dict_row). The %(name)s placeholders are psycopg's style; adapt them for your driver. Base64 isn't encryption: clients can decode a cursor and see the timestamp and id. If that matters, sign or encrypt it.
What you give up
No "jump to page 37". Keyset moves forward and back from where you are. For feeds, infinite scroll, APIs, and jobs, nobody misses it.
No cheap "page 3 of 500,000".
select count(*)on my 10M rows took about 0.3 s, on every request. Show "Load more", or use an estimate (reltuplesinpg_class) if you just need "about 10M results".Each sort order users can pick needs a matching index, ending in a unique column. If users can sort by 8 different columns, that's 8 indexes or some slow sorts.
OFFSET is still fine for small lists, admin screens with a few pages, and data that doesn't change while someone is paging.
Which one should you use?
flowchart TD
A{"Batch job, export,<br/>or sync?"} -->|Yes| KS["Keyset"]:::ks
A -->|No| B{"Infinite scroll<br/>or public API?"}
B -->|Yes| KS
B -->|No| C{"Users need numbered<br/>pages (jump to 7)?"}
C -->|No| KS
C -->|Yes| D{"Small, or rarely<br/>changing data?"}
D -->|Yes| OFF["OFFSET is fine"]:::off
D -->|No| CAP["OFFSET with a page limit,<br/>plus filters or search"]:::cap
classDef ks fill:#2f9e44,stroke:#2b8a3e,color:#fff
classDef off fill:#1c7ed6,stroke:#1864ab,color:#fff
classDef cap fill:#e8590c,stroke:#c2410c,color:#fffAnything that walks a whole table (exports, syncs, migrations, cleanup jobs): always keyset. Scenario C is a real bug waiting to happen.
Feeds, infinite scroll, public APIs: keyset, with an opaque cursor.
Numbered pages on big data: cap how deep users can go and give them filters. Nobody reads page 4,000 on purpose.
Run it yourself
Needs Postgres 12+ and psql. The table takes about 1 GB. PGTZ=UTC keeps timestamps readable.
psql -f setup.sql # 10M posts, about 30 s
psql -f speed.sql # OFFSET vs keyset at 7 depths
psql -f drift.sql # scenarios A, B, Csetup.sql
-- setup.sql: a 10M-row "feed" table, newest first.
drop table if exists posts;
create table posts (
id bigint generated always as identity primary key,
author_id int not null,
created_at timestamptz not null,
title text not null
);
-- Every 3 posts share a timestamp, so (created_at) alone is not unique.
insert into posts (author_id, created_at, title)
select (g % 50000) + 1,
'2025-01-01 00:00:00+00'::timestamptz + (g / 3) * interval '1 second',
'Post #' || g
from generate_series(1, 10000000) g;
-- One index serves both offset and keyset queries.
create index posts_feed_idx on posts (created_at desc, id desc);
vacuum analyze posts;speed.sql
-- speed.sql: fetch one 20-row page at increasing depths, OFFSET vs keyset.
-- Each query runs 7 times; we keep the median execution time.
-- timing off: skip per-row timing so instrumentation doesn't inflate deep scans.
drop table if exists speed_results;
create table speed_results (depth bigint, method text, median_ms numeric, rows_read bigint, buffers bigint);
do $$
declare
depths bigint[] := array[0, 1000, 10000, 100000, 1000000, 5000000, 9999980];
n bigint;
c_at timestamptz;
c_id bigint;
q text;
plan json;
times numeric[];
m text;
begin
foreach n in array depths loop
-- The cursor a client would hold after reading n rows (not timed).
if n > 0 then
select created_at, id into c_at, c_id
from posts order by created_at desc, id desc offset n - 1 limit 1;
end if;
foreach m in array array['offset', 'keyset'] loop
if m = 'offset' then
q := format('select id, author_id, created_at, title from posts
order by created_at desc, id desc limit 20 offset %s', n);
elsif n = 0 then
q := 'select id, author_id, created_at, title from posts
order by created_at desc, id desc limit 20';
else
q := format('select id, author_id, created_at, title from posts
where (created_at, id) < (%L::timestamptz, %s)
order by created_at desc, id desc limit 20', c_at, c_id);
end if;
times := '{}';
for i in 1..7 loop
execute 'explain (analyze, buffers, timing off, format json) ' || q into plan;
times := times || (plan -> 0 ->> 'Execution Time')::numeric;
end loop;
insert into speed_results
select n, m,
(select percentile_cont(0.5) within group (order by t) from unnest(times) t),
(plan -> 0 -> 'Plan' -> 'Plans' -> 0 ->> 'Actual Rows')::bigint,
(plan -> 0 -> 'Plan' ->> 'Shared Hit Blocks')::bigint
+ (plan -> 0 -> 'Plan' ->> 'Shared Read Blocks')::bigint;
end loop;
end loop;
end $$;
select depth as rows_skipped,
max(median_ms) filter (where method = 'offset') as offset_ms,
max(median_ms) filter (where method = 'keyset') as keyset_ms,
max(rows_read) filter (where method = 'offset') as offset_rows_read,
max(rows_read) filter (where method = 'keyset') as keyset_rows_read,
max(buffers) filter (where method = 'offset') as offset_pages,
max(buffers) filter (where method = 'keyset') as keyset_pages
from speed_results
group by depth
order by depth;drift.sql
-- drift.sql: read a whole feed, newest first, while it changes between page loads.
-- Both methods face the same inserts and deletes (same seed, same order of operations).
drop table if exists feed, initial_rows, shown, deleted_rows, drift_results;
create table feed (
id bigint generated always as identity primary key,
created_at timestamptz not null
);
create index on feed (created_at desc, id desc);
create table initial_rows (id bigint);
create table shown (method text, page int, id bigint, created_at timestamptz);
create table deleted_rows (method text, id bigint);
create table drift_results (scenario text, method text, pages int, rows_shown int, duplicates int, missed int);
create or replace procedure read_feed(scenario text, m text, start_rows int, page_size int,
inserts_per_page int, deletes_per_page int,
delete_seen boolean default false)
language plpgsql as $$
declare
p_no int := 0;
got int;
c_at timestamptz; -- keyset cursor: last row the client saw
c_id bigint;
gone bigint;
begin
truncate feed restart identity;
insert into feed (created_at)
select '2025-01-01 00:00:00+00'::timestamptz + (g / 3) * interval '1 second'
from generate_series(1, start_rows) g;
truncate initial_rows, shown, deleted_rows;
insert into initial_rows select id from feed;
perform setseed(0.42);
loop
p_no := p_no + 1;
if m = 'offset' then
insert into shown
select m, p_no, id, created_at from feed
order by created_at desc, id desc
limit page_size offset (p_no - 1) * page_size;
else
insert into shown
select m, p_no, id, created_at from feed
where c_id is null or (created_at, id) < (c_at, c_id)
order by created_at desc, id desc
limit page_size;
end if;
get diagnostics got = row_count;
exit when got = 0;
select s.created_at, s.id into c_at, c_id
from shown s where s.method = m and s.page = p_no
order by s.created_at, s.id limit 1;
-- Meanwhile: new posts arrive at the top, and random posts get deleted.
insert into feed (created_at)
select (select max(created_at) from feed) + g * interval '1 second'
from generate_series(1, inserts_per_page) g;
for i in 1..deletes_per_page loop
delete from feed
where id = (select id from feed order by random() limit 1)
returning id into gone;
insert into deleted_rows values (m, gone);
end loop;
-- Batch-job style: delete (archive) the rows we just processed.
if delete_seen then
insert into deleted_rows
select m, id from feed where id in (select id from shown s where s.method = m and s.page = p_no);
delete from feed where id in (select id from shown s where s.method = m and s.page = p_no);
end if;
end loop;
insert into drift_results
select scenario, m, p_no - 1,
(select count(*) from shown s where s.method = m),
(select count(*) - count(distinct id) from shown s where s.method = m),
(select count(*) from initial_rows i
where not exists (select 1 from shown s where s.method = m and s.id = i.id)
and not exists (select 1 from deleted_rows d where d.method = m and d.id = i.id));
end $$;
-- 2,000 rows, 20 per page. What happens between page loads:
-- A) feed: 2 new posts arrive and 1 random post is deleted
call read_feed('A: new posts arriving', 'offset', 2000, 20, 2, 1);
call read_feed('A: new posts arriving', 'keyset', 2000, 20, 2, 1);
-- B) feed: 2 random posts are deleted, nothing new arrives
call read_feed('B: posts being deleted', 'offset', 2000, 20, 0, 2);
call read_feed('B: posts being deleted', 'keyset', 2000, 20, 0, 2);
-- C) batch job: process a page, then delete (archive) those rows
call read_feed('C: job deletes what it processed', 'offset', 2000, 20, 0, 0, true);
call read_feed('C: job deletes what it processed', 'keyset', 2000, 20, 0, 0, true);
select * from drift_results;The bottom line
OFFSET looks harmless because page 1 is always fast, and test data never changes while you click "next". In production, neither holds. Deep pages get slower in proportion to how far you skip, and every insert or delete above the reader moves the page boundary.
Keyset pagination fixes both with one idea: remember where you stopped, not how far you've gone. It takes one index, one row comparison, and two queries.
If you change one thing this week, start with any job that walks a whole table with OFFSET. That's where rows silently go missing.
Further reading: Markus Winand's No Offset, the classic write-up on this topic.
Comments0
Log in to join the discussion.
No comments yet.