Highlights

Contents

Part II
02

Pagination

We learn to return long lists in pages that stay fast and correct as the data grows and changes. The obvious approach, page numbers with OFFSET, gets slower with every page and shows duplicates when rows are inserted. We will cover offset pagination and its costs, cursor pagination, and keyset pagination with stable ordering.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1REST resources2Pagination3Bulk APIs, partialupdates, versioning4Idempotency keys5RPC, GraphQL and gRPC6API contracts7Application architecture8Error handling9Backend testing10Code quality and the fullrequest

#Section 5Offset pagination and its cost

A restaurant manager scrolls through order history, 20 orders per page. The simplest implementation passes a page number, and the server translates it into SQL: page 5,001 becomes SELECT ... ORDER BY created_at DESC LIMIT 20 OFFSET 100000. This is offset pagination, and it is what most tutorials show. It is easy to build, it supports “jump to page 400”, and it can show “page 4 of 250,000” if you also run a count.

It has two problems, one of cost and one of correctness. The cost problem is that the database cannot jump to row 100,000. Even with an index on created_at, it walks the index from the beginning, reads 100,000 entries, throws them away and then returns the next 20. That is 100,020 rows read for 20 returned. The work grows linearly with the page number, so page 5,000 costs 5,000 times page 1. At an illustrative microsecond per row, page 5,001 takes about 0.1 s of database time, and a crawler walking every page of 5,000,000 orders performs work that grows with the square of the number of pages.

LIMIT 20 OFFSET 100000: THE DATABASE READS 100,020 ROWS TO RETURN 20LIMIT 20 OFFSET 100000: THE DATABASE READS 100,020 ROWS TO RETURN 20100,000 rows read and thrown away20 keptcost grows with the page number: page 5,000 is 5,000 times the work of page 1
Figure 5.7100,000 rows read and discarded to return 20. Deep pages are slow by construction.

The COUNT(*) that drives “page 4 of 250,000” has the same problem. Counting 5,000,000 rows that match a filter is a scan in PostgreSQL, so many APIs drop exact totals or show estimates such as “about 5 million”.

#Section 6Offset pagination under concurrent writes

The correctness problem appears whenever rows are inserted or deleted between page requests, which in an order system is all the time. The manager loads page 1, orders o50 to o48, newest first. A new order, o51, arrives. The manager loads page 2 with offset 3. The list has shifted down by one, so offset 3 now points at o48, which appears again at the top of page 2. A deletion does the opposite and silently skips a row. For a human scrolling, a duplicate is a small annoyance. For a sync job copying orders to an accounting system, a skipped row is a missing invoice that nobody notices for a month.

A NEW ROW ARRIVES BETWEEN PAGES: OFFSET SHOWS ONE ORDER TWICEA NEW ROW ARRIVES BETWEEN PAGES: OFFSET SHOWS ONE ORDER TWICEpage 1 at 20:00o50o49o48o51o50o49o48o47o46o51 arrives, the list slides down by onepage 2: offset 3o48o47o46o48 twicea delete between pages would skip a row instead
Figure 5.8One insert between page loads, and o48 appears twice. A delete would make a row vanish.

Offset still has its place. For small, slowly changing collections, such as a restaurant’s 40 menu items, or for admin screens where jumping to a page number matters more than perfect consistency, it is fine. For large, constantly changing collections and especially for machine consumers, it is the wrong tool.

#Section 7Cursor pagination

Cursor pagination replaces the page number with a bookmark. Each response includes the items and a next_cursor, an opaque string that encodes where the page ended. The client sends it back as ?cursor=... to get the next page. Wren’s cursor is the base64url encoding of {"created_at":"2026-10-06T10:00:00Z","id":812345}, the sort values of the last row returned. The server decodes it and asks for rows after that position, which is the keyset query in Section 8.

A CURSOR IS AN OPAQUE BOOKMARK: "CONTINUE AFTER THIS ROW"A CURSOR IS AN OPAQUE BOOKMARK: "CONTINUE AFTER THIS ROW""next_cursor": "eyJjcmVhdGVkX2F0Ijoi…"created_at 10:00:00id 812345sign it if clients must not edit it
Figure 5.9The cursor encodes the last row’s sort key. Clients treat it as opaque and pass it back.

Opacity matters. If clients parse the cursor, Wren can never change its internals, for example adding a field or switching to a different sort key. So the documentation says “treat it as an opaque string”, and some APIs sign or encrypt cursors with an HMAC to make tampering detectable. A cursor should also carry the filters and sort it was created with, or be rejected if the client changes them mid-stream, since a cursor from one sort order makes no sense in another.

Cursors give up two things. A client cannot jump to page 400, only move forward (and backward, if the API also returns a prev_cursor). And there is no cheap total count. Infinite scroll in feeds and timelines needs neither, which is why Twitter, Facebook, Slack, Stripe and GitHub’s newer APIs all use cursors.

#Section 8Keyset pagination, stable ordering and concurrent writes

The query behind the cursor is keyset pagination, also called the seek method. Instead of skipping rows, it filters on the sort key of the last row seen: WHERE (created_at, id) < ('2026-10-06 10:00:00', 812345) ORDER BY created_at DESC, id DESC LIMIT 20. With an index on (created_at, id), the database seeks straight to that position in the index and reads 20 rows. Page 5,001 costs the same as page 1. The comparison (a, b) < (x, y) is a row-value comparison, supported directly by PostgreSQL and MySQL 8, and it means “a is less than x, or a equals x and b is less than y”.

KEYSET PAGINATION: SEEK INTO THE INDEX, READ 20 ROWSKEYSET PAGINATION: SEEK INTO THE INDEX, READ 20 ROWS(created_at, id)WHERE (created_at, id) < ('2026-10-06 10:00', 812345) LIMIT 20same cost on page 1 and page 5,000; inserts never shift the window
Figure 5.10Seek to the bookmark, read 20 rows. The cost does not depend on the page number.

The sort order must be stable, meaning every row has a unique position. Ordering by created_at alone is not stable, because several orders can share a timestamp, especially at Wren’s 50 orders per second with second-precision timestamps. If the page boundary falls in the middle of three orders created at 10:00:00, “after 10:00:00” skips the rest of them and “at or after” repeats some. Adding a unique tiebreaker, the id, to both the ORDER BY and the cursor gives every row a distinct position, and the index must cover both columns in the same order.

ORDER BY created_at ALONE IS NOT STABLE: ADD A UNIQUE TIEBREAKERORDER BY created_at ALONE IS NOT STABLE: ADD A UNIQUE TIEBREAKER10:00:00id 81234610:00:00id 81234510:00:00id 812344page boundarythree orders share a timestamp: the cursor stores (created_at, id), and the index covers both
Figure 5.11Three rows share a timestamp. The id breaks the tie, so the boundary is exact.

Keyset pagination also behaves well under concurrent writes. A new order inserted at the top does not shift any later position, so no row repeats or vanishes on the pages that follow. New rows that arrive behind the cursor are simply not seen in this pass, which is usually acceptable for a scroll. A sync job that must catch everything can page by an updated_at and id pair and come back later for rows updated since its last run.