In short
Offset pagination (LIMIT 20 OFFSET 100000) makes the database produce and throw away every skipped row, so deep pages get slower, and rows shift between pages when data changes underneath. Keyset pagination, often called cursor pagination, remembers the sort key of the last row shown and asks for the rows after it, which an index serves in the same time on every page. For a public API, sort on a unique tie-breaker and hand the key to clients as an opaque, signed page token.
Key points
- With
OFFSET n, the database still computes the n skipped rows, so the cost of a page grows with how deep it is. - Offset pages skip or repeat items when rows are inserted or deleted between requests. Keyset pages do not, because they start from a value, not a position.
- Keyset needs a total, stable order: sort on the visible column plus a unique tie-breaker such as
id, and index those columns in that order. - A page token should be opaque to clients and checked by the server: sign it with an HMAC, bind it to the query, and encrypt it if its contents must stay private.
- Exact total counts cost a scan proportional to the matching rows. Prefer a
has_moreflag, an estimate or a capped count. - Keyset cannot jump to page 400. Most feeds, exports and sync jobs never need to; admin tables with page numbers can keep offset for shallow pages.
How offset pagination works, and why deep pages get slow
Offset pagination is the first thing most APIs ship: GET /posts?limit=20&offset=40 becomes ORDER BY created_at DESC LIMIT 20 OFFSET 40. It is easy to build, easy to explain and lets a client jump to any page. The trouble is what OFFSET means to the database. It is not a seek. It is an instruction to produce rows in order and discard the first n of them.
PostgreSQL’s documentation says it plainly: the rows skipped by an OFFSET clause still have to be computed inside the server, so a large OFFSET might be inefficient. Other databases behave the same way, because the engine cannot know which row is number 100,001 without counting its way there.
GET /posts?limit=20&offset=100000
ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 100000
1. Find the newest entry in the index a few page reads
2. Produce rows 1 to 100,000 in order each read, then thrown away
3. Produce rows 100,001 to 100,020 returned to the client
The work grows with the offset.
GET /posts?limit=20&page_token=<last row was 2026-11-12 09:30, id 48213>
WHERE (created_at, id) < ('2026-11-12 09:30:00+00', 48213)
ORDER BY created_at DESC, id DESC LIMIT 20
1. Descend the index to that key a few page reads
2. Produce the next 20 rows returned to the client
The work is the same on every page.With an index that matches the sort, each skipped row is still a walk through the index and usually a visit to the table to fetch the row. Without one, it is worse: the database has to read every matching row and sort them before it can count off the offset. Either way, page 1 is fast in development, and page 5,000 is slow for the client that pages through everything, which is usually an export or a sync job, exactly the caller that reaches deep pages.
Skipped and duplicated items when data changes
The second problem has nothing to do with speed. An offset is a position in a list that keeps changing. If a new row is inserted at the top between two requests, every row shifts down one place, and the next page starts with the last item of the previous one. If a row on an earlier page is deleted, everything shifts up, and one item is never shown at all. For a feed that is a cosmetic glitch. For a sync job or an export it is lost or doubled data.
posts = list(range(10, 0, -1)) # ten posts, newest first: 10, 9, ... 1
def offset_page(data, offset, limit=3):
return data[offset:offset + limit]
def keyset_page(data, after, limit=3):
return [p for p in data if p < after][:limit] # WHERE id < :after
page1 = offset_page(posts, 0)
print('page 1: ', page1)
posts.insert(0, 11) # a new post arrives before page 2 is requested
print('offset page 2: ', offset_page(posts, 3))
print('keyset page 2: ', keyset_page(posts, after=page1[-1]))
posts.remove(11)
posts.remove(9) # or instead, a post from page 1 is deleted
print('offset page 2: ', offset_page(posts, 3))
print('keyset page 2: ', keyset_page(posts, after=page1[-1]))
# page 1: [10, 9, 8]
# offset page 2: [8, 7, 6]
# keyset page 2: [7, 6, 5]
# offset page 2: [6, 5, 4]
# keyset page 2: [7, 6, 5]The keyset version asks for “posts older than 8”, a value, so neither the insert nor the delete moves its starting point. It does not freeze the list: a row inserted above the cursor will not appear until the client starts again from the top, and a row updated so that its sort key moves can still appear twice or not at all. If a job needs every row exactly once, page on a key that never changes, such as an increasing id, or read from a snapshot.
There is also a quieter version of the same bug. PostgreSQL’s documentation warns that without an ORDER BY that puts the rows in a unique order, LIMIT returns an unpredictable subset, and that different LIMIT and OFFSET values can produce different plans and so different orders. Sorting on created_at alone, where many rows share a timestamp, lets the order of those rows change from one request to the next.
Keyset pagination: seek instead of skip
Keyset pagination, also called the seek method, replaces the position with the sort key of the last row the client saw. The next page is “the first 20 rows that sort after this one”. With an index on the sort columns, the database descends the index straight to that key and reads 20 entries, so page 5,000 costs the same as page 1.
-- One index serves the sort in both directions (read backward for DESC)
CREATE INDEX posts_created_id_idx ON posts (created_at, id);
-- First page: ask for one row more than you show, to learn if more exist
SELECT id, title, created_at FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 21;
-- Next page: seek past the last row shown
SELECT id, title, created_at FROM posts
WHERE (created_at, id) < ('2026-11-12 09:30:00+00', 48213)
ORDER BY created_at DESC, id DESC
LIMIT 21;
-- Previous page: seek before the first row shown, flip the order,
-- then reverse the rows in the application
SELECT id, title, created_at FROM posts
WHERE (created_at, id) > ('2026-11-12 11:05:00+00', 48240)
ORDER BY created_at ASC, id ASC
LIMIT 21;The condition (created_at, id) < (...) is a row comparison. PostgreSQL’s documentation defines it as left to right: the first pair of elements that differ decides the result, which is exactly the order ORDER BY created_at DESC, id DESC produces. It is the compact form of created_at < :ts OR (created_at = :ts AND id < :id), and PostgreSQL can use it directly as a bound on a B-tree scan over (created_at, id). Asking for 21 rows and showing 20 tells you whether a next page exists without a second query.
- Every sort column must always hold a value. A row comparison with a missing value is unknown rather than true or false, so those rows silently drop out of every page. Make the columns required in the schema, or sort on an expression such as
COALESCE(published_at, created_at)and index that same expression. - Row comparison only works when all columns sort in the same direction. For “newest first, then by name A to Z”, write the expanded
ORform, and index the columns with matching directions. - Filters go in front of the sort key in the index. A list of open posts sorted by date wants an index on
(status, created_at, id). - The cursor must carry every sort column, not only the one shown to the user.
A stable sort and the index that serves it
Keyset pagination only works on a total order: no two rows may compare equal on the full sort key. Timestamps, names, scores and amounts all repeat. Append a unique column, usually the primary key, as the last sort column, and the order becomes total and repeatable. Stripe-style object ids, auto-increment ids and time-ordered UUIDs all work as tie-breakers.
The index is what turns keyset from correct into fast. PostgreSQL’s documentation on indexes and ORDER BY describes the case that matters here: an explicit sort has to process all the data to find the first n rows, but if an index matches the ORDER BY, the first n rows can be retrieved directly without scanning the rest. A B-tree can also be read backward, so one index on (created_at, id) serves both ASC and DESC when both columns go the same way. How composite indexes order their columns, and why equality columns go first, is covered in database indexing explained.
Every sort option an API exposes is another index to maintain. Offer a small, fixed set of sorts, each with its tie-breaker and its index, rather than “sort by any field”. A user-chosen sort on an unindexed column turns each keyset page back into a full sort.
Opaque page tokens: encode, sign, bind
A cursor is the last row’s sort key. You could expose it as query parameters, ?after_created_at=...&after_id=..., but that makes the sort key part of your public contract. Change the sort, add a tie-breaker or move to another store, and every client breaks. Most APIs instead return an opaque string, a page token, and ask clients to send it back unchanged.
Google’s API design guide, AIP-158, sets the rules most teams converge on. Page tokens must be opaque but URL-safe strings that clients cannot parse, and the guide adds that base64-encoding an otherwise readable token is not enough obfuscation. All other request parameters must match the call that produced the token, or the API should return an INVALID_ARGUMENT error; page_size is the exception and may change between pages. Tokens grant no authorization: every request is checked as if the token were absent. APIs may also expire tokens, and the guide gives three days as a rule of thumb.
import base64, hashlib, hmac, json
SECRET = b'load-me-from-a-secret-store' # rotating it voids old tokens
def sign(body, query_key): # binds the token to this query's filters and sort
return hmac.new(SECRET, body + query_key.encode(), hashlib.sha256).digest()[:16]
def encode_cursor(created_at, row_id, query_key):
body = json.dumps([created_at, row_id]).encode()
return base64.urlsafe_b64encode(sign(body, query_key) + body).rstrip(b'=').decode()
def decode_cursor(token, query_key):
raw = base64.urlsafe_b64decode(token + '=' * (-len(token) % 4))
tag, body = raw[:16], raw[16:]
if not hmac.compare_digest(tag, sign(body, query_key)):
raise ValueError('invalid page token')
return tuple(json.loads(body))
q = 'status=open&sort=-created_at' # the request's filters and sort, in canonical form
token = encode_cursor('2026-11-12T09:30:00Z', 48213, q)
print(token)
print(decode_cursor(token, q))
for t, key in ((token[:-4] + 'AAAA', q), (token, 'status=closed&sort=-created_at')):
try: decode_cursor(t, key)
except ValueError as e: print('rejected:', e)
# lmb7EorVc0Jbd8CxoORt0VsiMjAyNi0xMS0xMlQwOTozMDowMFoiLCA0ODIxM10
# ('2026-11-12T09:30:00Z', 48213)
# rejected: invalid page token
# rejected: invalid page tokenThe token is the JSON sort key, prefixed with a truncated HMAC-SHA256 tag and base64url-encoded. The tag covers a canonical string of the request’s filters and sort as well, so a token cannot be replayed against a different query, and editing any byte of it fails the check. Python’s documentation recommends hmac.compare_digest over == for this comparison, because it avoids the early exit that makes timing attacks possible. Add a version number when the format may change, and an issue time if tokens should expire.
- Signing stops tampering, not reading. Anyone can base64-decode this token and see the timestamp and id. If the sort key reveals something, such as a score or another tenant’s data shape, encrypt the token with an authenticated cipher such as AES-GCM instead.
- The other option is a server-side token: store the cursor state under a random id and return the id. Nothing leaks, but you now run a store with expiry.
- Never build SQL from token contents as text. Decode to typed values and pass them as bound parameters.
- Treat a token that fails verification as a client error, with a message telling the client to restart from the first page.
Total counts and what they cost
“Showing 1 to 20 of 48,213” looks free and is not. PostgreSQL’s documentation notes that SELECT count(*) FROM sometable requires effort proportional to the size of the table: it scans the whole table or an index that includes every row. With a filter, it is proportional to the matching rows. A paginated endpoint that also counts does the expensive part of offset pagination on every request.
- Return
has_moreinstead. Fetch one extra row and report whether it exists. Stripe’s list responses do exactly this. - Cap the count.
SELECT count(*) FROM (SELECT 1 FROM posts WHERE status = 'open' LIMIT 1001) AS tstops at 1,001, and the UI shows “1,000+”. - Estimate it. For a whole table, PostgreSQL keeps
reltuplesinpg_class; the documentation describes it as an estimate refreshed byVACUUM,ANALYZEand some DDL, not on every change. AIP-158 lets atotal_sizefield be an estimate, as long as the API documents that. - Count separately. Compute the total once per search, asynchronously or on the first page only, and cache it with the results.
Going backward, and jumping to a page
To page backward from a keyset page, take the first row shown, flip the comparison and the sort direction, fetch, then reverse the rows in the application so they display in the usual order. That is the third query in the SQL above. The page token should record its direction, so the server knows which query to run, and each response can return both a next and a previous token.
What keyset cannot do is jump to page 400, because there is no cheap way to know which key starts that page. For feeds, infinite scroll, exports, sync and anything an API client loops over, nobody needs that. For an admin table where people do click page numbers, three options work: keep offset but cap how deep it goes, offer filters and search so nobody needs page 400, or replace numbered pages with jumps by value, such as “go to March”, which keyset handles well.
For change feeds, where a client wants “everything since I last asked”, a cursor on a monotonically increasing column works, but rows committed late, with an earlier value than one already read, can be missed. Reading the database’s change stream avoids that; see change data capture.
How Stripe, GitHub and Google document pagination
- Stripe. List endpoints take
limit(1 to 100, default 10),starting_afterandending_before, which are mutually exclusive. Both take an object id from the previous page, and results come in reverse chronological order. The response carrieshas_more. The cursor is a plain object id: the server turns it into a position. - GitHub REST API. Paginated responses carry a
linkheader with URLs markedrel="next",rel="prev",rel="first"andrel="last";lastcan be missing when it cannot be calculated. Depending on the endpoint, the URLs usepage,before/afterorsince, which is why GitHub tells clients to use the URLs from the header rather than build them.per_pagetops out at 100 for most endpoints. - RFC 8288. The
Linkheader GitHub uses is standardized in RFC 8288, Web Linking, which defines the header’s syntax and link relation types;nextandprevare relation types registered with IANA. A client that followsrel="next"until it disappears works with any pagination scheme behind it. - Google AIP-158. Requests take
page_sizeandpage_token; responses returnnext_page_token, which is empty only at the end of the collection. A page may hold fewer results than requested even before the end, so clients must loop on the token, not on the page size.
The common thread: the server owns the cursor format, the client echoes it back, and the end of the list is signaled explicitly. Whichever style you choose, document the default and maximum page size, how the end is signaled, whether tokens expire and what happens when the data changes between pages. The same contract applies whether the API is REST or GraphQL (REST vs GraphQL).
Offset, keyset or opaque cursor: choosing
| Aspect | Offset and limit | Keyset in query parameters | Opaque cursor token |
|---|---|---|---|
| Cost of a deep page | Grows with the offset | Same on every page, with a matching index | Same as keyset |
| Inserts and deletes between pages | Items skipped or repeated | Stable from the cursor onward | Stable from the cursor onward |
| Jump to page N | Yes | No; jump by value instead | No |
| Sort options | Any, if you accept the cost | Few, each with an index and tie-breaker | Few, each with an index and tie-breaker |
| Changing the sort key later | Easy | Breaks clients | Invisible to clients |
| Tampering | Harmless | Clients can craft any key | Rejected by the signature check |
| Typical use | Small admin tables, numbered pages | Internal APIs, simple feeds | Public APIs, sync and export endpoints |
A reasonable default for a new API: opaque, signed tokens over keyset queries, a small set of indexed sorts with id as the tie-breaker, has_more instead of a total, and a documented maximum page size. Fast pages also keep connections free for other requests (PostgreSQL connection pooling).
BYD Tech builds web apps and the APIs behind them: the code lives in the client’s GitHub from day one, AI-assisted work is reviewed by an engineer, and IP is assigned to the client.
Sources
Checked when this post was written.
- PostgreSQL docs: LIMIT and OFFSET
- PostgreSQL docs: Row Constructor Comparison
- PostgreSQL docs: Indexes and ORDER BY
- PostgreSQL docs: Aggregate Functions (count performance note)
- PostgreSQL docs: Statistics Used by the Planner
- Stripe API reference: Pagination
- GitHub Docs: Using pagination in the REST API
- RFC 8288: Web Linking
- Google AIP-158: Pagination
- Python docs: hmac, keyed hashing for message authentication