API pagination
easy 24 minPagination sends a long list in small pages.
Video lesson · Chapter 1 of 6
Count past the first page
API pagination
1:18Reel
Theory
Read or listen first. About 2 min.
What it is
A list in an API can be longer than anyone wants to receive at once. Pagination means sending it in pages: the client asks for a limited number of items and gets a way to ask for the next ones.
There are two ideas. With an offset the client says how many items to skip. With a cursor the client hands back a token that says where the last page ended. Keyset pagination is how a database serves a cursor well: it seeks to the rows after the last sort values instead of counting from the start.
Why it exists
A shop has 100,000 products and a search finds 2,500. Sending all of them is slow, uses memory on both sides and shows the person far more than they can look at.
The choice of method decides three things: how fast deep pages are, whether items are repeated or lost while the list changes, and whether the reader can jump to page 37. No method wins all three, so it is a real decision.
A short history
December 2006
PostgreSQL 8.2 makes row comparisons follow the SQL standard and lets them use a multicolumn index, which is what keyset pagination needs.
October 2010
RFC 5988 gives the HTTP Link header a list of relations, among them next and prev, so a response can carry the address of the next page.
August 2017
Slack's engineers describe how their API moved from several older methods to cursors.
October 2017
RFC 8288 replaces RFC 5988 as the standard for web links.
Words to know
- Page size, or limit
- How many items one answer may hold.
- Offset
- How many items to skip before the page starts.
- Cursor
- A token that marks where the next page starts. The client passes it back unchanged.
- Opaque
- Not meant to be read or built by the client.
- Keyset, or seek method
- Finding the next page by comparing with the last row's sort values.
- Tiebreaker
- A unique last sort column, such as the id, so that the order is always the same.
- Data drift
- The list changes between two page requests.
How it works
Step through the idea, or press Play.
Ask for a page. A limit, a fixed order, and where to start
Understand it
Start here
The duck photos
Imagine photographing a long line of ducks, three at a time. You could count past the ones you already have. Or you could remember the last duck. Ducks do not stand still, so it matters which you choose.
Counting depends on everyone in front. Remembering the last one does not.
Why
All of it, or twenty of it
A search with 2,500 results
| Without pages | With pages | |
|---|---|---|
| Request | GET /products?search=headphones | GET /products?search=headphones&limit=20 |
| Items | 2,500 | 20 |
| Size, at 2 KB each | about 5 MB | about 40 KB |
| Transfer at 5 Mbit/s | 8 s | 0.064 s |
| Client | May run out of memory on a phone | Scrolls smoothly |
Faster answers
Smaller payloads, and the first items appear at once.
Less memory
On the client and on the server, which need not build the whole list.
Better experience
People read the first page while the next one loads.
Lower cost
Less bandwidth and less database work, as long as deep pages stay cheap.
One page after another
Method 1
Offset: skip and take
The most familiar form, like page numbers in a book.
-- GET /products?page=3&limit=20SELECT * FROM productsORDER BY created_at DESC, id DESCLIMIT 20 OFFSET 40; -- (page - 1) * limitWhat a deep page reads
Exporting everything with offsets
Data drift with OFFSET 3 and three per page
| What happens | The list becomes | Page 2 shows | Result |
|---|---|---|---|
| Nothing | A B C | D E F | G | D E F | Right |
| X inserted at the start | X A B | C D E | F G | C D E | C is repeated |
| A deleted | B C D | E F G | E F G | D is never seen |
Good for
- Small lists, say under 10,000 rows
- Admin panels with page numbers
- When jumping to page X is required
- Data that rarely changes
Avoid for
- Large lists with deep pages
- Live feeds, because of drift
- Infinite scroll
- Busy public APIs, where anyone may ask for page 50,000
Method 2
Cursor: continue from here
The server returns a token with each page. The client does not need to know what is inside and only sends it back.
GET /products?limit=3{ "data": [ {"id": 1, "name": "Product A"}, {"id": 2, "name": "Product B"}, {"id": 3, "name": "Product C"} ], "next_cursor": "eyJpZCI6M30=", "has_more": true }GET /products?limit=3&cursor=eyJpZCI6M30%3D{ "data": [ {"id": 4, "name": "Product D"}, {"id": 5, "name": "Product E"}, {"id": 6, "name": "Product F"} ], "next_cursor": "eyJpZCI6Nn0=", "has_more": true }A cursor on its round trip
How to write the token
| Way | Example | Property |
|---|---|---|
| Base64 of JSON | {"id":100} becomes eyJpZCI6MTAwfQ== | Simple and easy to debug. Anyone can read and change it: encoding is not protection |
| Signed | base64(data).hmac(data) | Readable, but changes are detected |
| Encrypted | encrypt(data, key) | Unreadable. Use an authenticated mode, so changes are detected too |
| Server side | A random id for stored state | Short, but needs storage and an expiry |
Perfect for
- Infinite scroll
- Social feeds
- Chat and notifications
- Large lists that change often
Limits
- No jump to an arbitrary page
- Going back needs stored cursors or a reversed query
- A total count is a separate, expensive question
- A little more work to build
Method 3
Keyset: seek in the index
Keyset pagination, also called the seek method, replaces counting with a comparison. The last row of the page gives the values.
-- Offset: produces 100,000 rows firstSELECT * FROM products ORDER BY id DESC LIMIT 20 OFFSET 100000;-- Keyset: starts at the place. 512345 is the id of the last row seenSELECT * FROM products WHERE id < 512345 ORDER BY id DESC LIMIT 20;Rows read for the same twenty items
With several sort columns the keyset must hold all of them, and the last must be unique. Otherwise two rows with the same time can be split by a page border and one is lost.
-- Sort by created_at DESC, then id DESC. Last row: ('2024-01-15', 100)SELECT * FROM productsWHERE (created_at, id) < ('2024-01-15', 100)ORDER BY created_at DESC, id DESCLIMIT 20;-- The same without row comparison, or when directions differSELECT * FROM productsWHERE created_at < '2024-01-15' OR (created_at = '2024-01-15' AND id < 100)ORDER BY created_at DESC, id DESCLIMIT 20;CREATE INDEX products_page ON products (created_at DESC, id DESC);Ideal for
- Millions of rows
- Strict speed targets
- Lists with a fitting index
- Reading in order, such as exports and log viewers
Requires
- A unique order, with a tiebreaker
- An index that matches filter and sort
- Care with several columns and with null values
- Giving up random page access
Choose
Compare the three
| Offset | Cursor (opaque) | Keyset (visible) | |
|---|---|---|---|
| Deep pages | Slow, work grows with the offset | As fast as what is inside; with a keyset, a seek | A seek: depth of the index plus the page |
| Jump to a page | Yes | No | No |
| Total count | Usual, but costs its own query | Usually left out | Usually left out |
| When data moves | Repeats and losses | Stable | Stable |
| To build | Simple | Medium | Medium |
| Client must know | Page number | Nothing, pass it back | The sort value of its last item |
| Best for | Admin panels, small lists | Feeds, infinite scroll, public APIs | Internal APIs, exports, analytics |
Which one?
Who uses what
| API | Method |
|---|---|
| Stripe list endpoints | starting_after with an object id, limit 1 to 100, has_more |
| Slack | cursor and next_cursor; an empty one means the end |
| Facebook Graph API | after and before cursors; the docs say not to store them |
| X API v2 | pagination_token, from next_token |
| GitHub REST | Link header; page numbers on many endpoints, cursors on some |
| DynamoDB Query | LastEvaluatedKey back as ExclusiveStartKey, a visible keyset |
| Elasticsearch | from and size up to 10,000 hits, then search_after |
Answer
What a page should contain
{ "data": [ { "id": 7, "name": "Mouse Pad XL", "price": 19.99 } ], "pagination": { "next_cursor": "eyJpZCI6N30", "has_more": true }}Build it in five steps
- 1
Fix the order
Sort columns plus a unique tiebreaker, and an index that starts with the filter columns.
- 2
Cap the limit
A default such as 20 and a maximum such as 100. Reject or reduce larger values, and say which.
- 3
Fetch one more
Ask for limit + 1 rows. If you get them, there is more; drop the extra one.
- 4
Make the cursor
Last row's sort values, plus the sort and filters it belongs to, signed.
- 5
Check it on return
Bad signature, or a cursor from another filter, is a 400 with a clear error.
Do
- Set a maximum page size
- Check the cursor's integrity
- Use one consistent sort
- Include has_more
- Return an empty list, not an error, at the end
Do not
- Allow unlimited pages
- Trust a cursor from the client blindly
- Mix methods in one endpoint
- Forget the error cases
- Skip the index
Contract
A page belongs to a question
A cursor made for *price ascending, electronics* means nothing for *newest, furniture*. Keep the sort and the filters, or a short hash of them, inside the token and compare on return. How to express the filters is the topic of search and filtering.
A cursor comes back
Edges
What still moves
A keyset keeps the place, not a frozen picture. Items that arrive before your place are not shown until you start again: feeds show a *new posts* button. An item whose sort value changes, such as a score, can move past the place and be seen twice or not at all. Sort by something that does not change, or page through a snapshot.
A cursor for a list that moves
Summary
The whole topic in one minute.
Send lists in pages with a maximum size and a fixed order that ends in a unique column. Offset is easy and allows jumping, but reads everything it skips and repeats or loses items when the list moves.
A cursor that carries the last sort values stays correct and fast at any depth. Keep it opaque, check it, return has_more, and leave the total count out unless somebody needs it.
- Always a limit, a maximum and a fixed order with a unique last column.
- Offset reads what it skips, and drifts when the list moves.
- A keyset seeks to the last sort values through an index.
- A cursor is opaque, checked, and never the permission check.
- Fetch one extra row to know whether there is more.
- Leave the total out unless it is needed.