Book a 30-min callBook a call

API pagination: offset vs cursor (keyset), and how to design page tokens

Why offset pagination slows down on deep pages, how keyset (cursor) pagination works, and how to design signed, opaque page tokens for an API.

Two rows of boxes: in the top row an arrow walks past crossed-out boxes before reaching a page, in the bottom row an arrow jumps straight to a marked box and reads the next few.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
15 min read

Questions people ask

Is cursor pagination faster than offset pagination?

On deep pages, yes. With OFFSET the database computes and discards every skipped row, so the cost grows with the page number. A keyset cursor seeks straight to the last key through an index and reads one page of rows, so page 5,000 costs about the same as page 1. On the first few pages the difference is small.

Can keyset pagination jump to a specific page number?

No. A keyset cursor knows where the last page ended, not where page 400 starts. You can jump by value instead, such as to a date or a name, or keep offset pagination for shallow numbered pages in admin screens.

Should a page token be signed or encrypted?

Sign it at least, with an HMAC that also covers the query parameters, so clients cannot edit it or reuse it on another query. Encrypt it with an authenticated cipher if the sort key reveals anything the client should not see. Google AIP-158 notes that base64 encoding alone is not enough obfuscation.

How do I show a total count with cursor pagination?

An exact count scans every matching row, so avoid it on every request. Return a has_more flag by fetching one extra row, cap the count and show "1,000+", use an estimate such as reltuples in PostgreSQL, or compute the total once and cache it.

What column should break ties in the sort order?

A unique, immutable column, usually the primary key. Add it as the last ORDER BY column, include it in the index after the sort columns, and carry it in the cursor. Without it, rows that share a timestamp can be skipped or repeated across pages.

Building something like this?