AlgoViz

API pagination

easy 24 min

Pagination sends a long list in small pages.

Video lesson · Chapter 1 of 6

Count past the first page

0:00 / 3:24

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

  1. 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.

  2. 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.

  3. August 2017

    Slack's engineers describe how their API moved from several older methods to cursors.

  4. 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.

Step 1 of 3

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.

Three ducks per photo
ABCDEFGHIThree, pleaseFirst photo9 ducks

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 pagesWith pages
RequestGET /products?search=headphonesGET /products?search=headphones&limit=20
Items2,50020
Size, at 2 KB eachabout 5 MBabout 40 KB
Transfer at 5 Mbit/s8 s0.064 s
ClientMay run out of memory on a phoneScrolls smoothly
2,500 times 2 KB is 5 MB, which is 40 megabits. The item size and the connection are assumptions.
  • 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

Asking for one row more than the page is the cheap way to know whether there is more.

Method 1

Offset: skip and take

The most familiar form, like page numbers in a book.

SQL
-- GET /products?page=3&limit=20SELECT * FROM productsORDER BY created_at DESC, id DESCLIMIT 20 OFFSET 40;        -- (page - 1) * limit
Without ORDER BY the database may return rows in any order, and pages mean nothing.

What a deep page reads

rows read=offset+limit1,000,000+20=1,000,020 rows for 20 items\text{rows read} = \text{offset} + \text{limit} \qquad 1{,}000{,}000 + 20 = 1{,}000{,}020 \text{ rows for } 20 \text{ items}
The skipped rows still have to be produced inside the database, then thrown away.

Exporting everything with offsets

L⋅P(P+1)2=100⋅10,000⋅10,0012≈5,000,000,000 rowsL\cdot\frac{P(P+1)}{2} = 100\cdot\frac{10{,}000\cdot 10{,}001}{2} \approx 5{,}000{,}000{,}000 \text{ rows}
One million rows in P = 10,000 pages of L = 100. A keyset reads one million: 5,000 times fewer.

Data drift with OFFSET 3 and three per page

What happensThe list becomesPage 2 showsResult
NothingA B C | D E F | GD E FRight
X inserted at the startX A B | C D E | F GC D EC is repeated
A deletedB C D | E F GE F GD is never seen
The reader had already seen A, B and C. An insert in front repeats items, a delete in front loses them.

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.

HTTP
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 }
The token is base64 of {"id":3}. The equals sign must be percent-encoded in a URL; base64url without padding avoids that.

A cursor on its round trip

The client app sends a limit and a cursor to the products API. The API checks the signature of the cursor with a key from the secret store, then asks the database for the rows after the last sort values through an index, and returns the items with the next cursor to the client.
Blue goes in, pink comes back. The server keeps nothing between pages: the place is inside the token.

How to write the token

WayExampleProperty
Base64 of JSON{"id":100} becomes eyJpZCI6MTAwfQ==Simple and easy to debug. Anyone can read and change it: encoding is not protection
Signedbase64(data).hmac(data)Readable, but changes are detected
Encryptedencrypt(data, key)Unreadable. Use an authenticated mode, so changes are detected too
Server sideA random id for stored stateShort, but needs storage and an expiry
A cursor must never be the permission check. Filter by the caller on every page, whatever the token says.

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.

SQL
-- 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;
The two do not need to return the same rows: an id is a place, an offset is a count, and ids have gaps.

Rows read for the same twenty items

Two requests for the same depth. Offset: the API asks PostgreSQL to skip 100,000 rows; it reads 100,020 rows and returns 20. Keyset: the API asks PostgreSQL for rows after the last sort values; it goes down the index, reads 20 rows and returns 20.
The depth of an index grows very slowly, so a seek costs about the same on page 1 and on page 5,000.

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.

SQL
-- 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);
The row form uses the index best. It only works when all columns sort in the same direction.

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

OffsetCursor (opaque)Keyset (visible)
Deep pagesSlow, work grows with the offsetAs fast as what is inside; with a keyset, a seekA seek: depth of the index plus the page
Jump to a pageYesNoNo
Total countUsual, but costs its own queryUsually left outUsually left out
When data movesRepeats and lossesStableStable
To buildSimpleMediumMedium
Client must knowPage numberNothing, pass it backThe sort value of its last item
Best forAdmin panels, small listsFeeds, infinite scroll, public APIsInternal APIs, exports, analytics
Cursor and keyset are not rivals: the cursor is the envelope, the keyset is usually the letter inside. The order by name is OCK.

Which one?

10,000 is a rule of thumb. Measure your own deepest allowed page.

Who uses what

APIMethod
Stripe list endpointsstarting_after with an object id, limit 1 to 100, has_more
Slackcursor and next_cursor; an empty one means the end
Facebook Graph APIafter and before cursors; the docs say not to store them
X API v2pagination_token, from next_token
GitHub RESTLink header; page numbers on many endpoints, cursors on some
DynamoDB QueryLastEvaluatedKey back as ExclusiveStartKey, a visible keyset
Elasticsearchfrom and size up to 10,000 hits, then search_after
From each product's public documentation.

Answer

What a page should contain

JSON
{  "data": [ { "id": 7, "name": "Mouse Pad XL", "price": 19.99 } ],  "pagination": {    "next_cursor": "eyJpZCI6N30",    "has_more": true  }}
With offsets you would return page, total_pages and total instead. A Link header with rel="next" can carry the whole next URL.

Build it in five steps

  1. 1

    Fix the order

    Sort columns plus a unique tiebreaker, and an index that starts with the filter columns.

  2. 2

    Cap the limit

    A default such as 20 and a maximum such as 100. Reject or reduce larger values, and say which.

  3. 3

    Fetch one more

    Ask for limit + 1 rows. If you get them, there is more; drop the extra one.

  4. 4

    Make the cursor

    Last row's sort values, plus the sort and filters it belongs to, signed.

  5. 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

The last box applies permissions again. A token from a colleague must not show the colleague's rows.

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.

Sources