Key takeaways
- ✓Offset pagination (skip n rows, take 100) makes the database walk every row it skips. On 10 million orders, page 10,000 took 50 ms and page 100,000 took 606 ms; a cursor (take 100 older than the last one seen) took about 2 ms at every depth, about 260 times less on the last page.
- ✓For page 10,000, offset read 1,000,000 index entries and 13,964 pages of 8 KB to return 100 orders. The cursor read 100 entries and 5 pages.
- ✓Offset pages shift when the data changes between requests. Paging 50 pages of 100: 5 new orders on top per page brought 245 orders back a second time, and 2 already-read orders removed per page made 98 orders never appear. The errors are exact: 49 gaps between pages, times the shift per gap.
- ✓With both changes at once the shifts partly cancel: 147 orders twice and none lost. The cursor had 0 repeats and 0 skips in every run, and neither method showed orders added after paging started.
- ✓To an old JSON client, a renamed field is a removed field. Adding a field was the only change both test clients survived; a rename, a removal and a field that may be null broke both, and a number turned into text broke one of them.
- ✓Protobuf sends box numbers, not names. Renaming a field kept old clients working; moving the total to a new number, or making it text, left the old client reading a total of 0 with no error. Once used, a field number is never changed or reused.
- ✓A contract test keeps the published v1 schemas in the repository and checks the current API against them on every build, so a breaking change fails CI before any client sees it. Change on purpose by adding fields, or by publishing v2 next to v1.
Some API bugs never raise an error. This chapter measures two. An export paged through 5,000 orders while the data changed: 5,000 orders came back, no errors, and 98 orders were never in the list. Then one small change to the order format left an old app reading an order's total as 0, again with no error. The first comes from how the next page is asked for; the second from how a schema change looks to a client built for the old one. The lab measures both, and the fixes: a cursor instead of an offset, and a contract test that fails the build before an app finds out.
The examples come from Lab 06 (APIs and Service Communication) of the system design labs, scripts 02_pagination.py (offset and cursor pages on 10 million orders, and paging while orders are added and removed) and 06_contracts.py (five schema changes each for JSON and Protobuf, tried on old clients and on a checker), with the lab's modules pagination.py (the two queries, the cursor and the duplicate counter) and compat.py (the compatibility checker). The same lab's retry and deadline scripts (03 and 04) are covered in Chapter 10; its REST vs. gRPC and connection-reuse scripts (01 and 05) aren't covered in this track. The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): a Python web service (FastAPI) in front of Postgres 18.6, both in Docker, with the client on the same machine. The schema script runs offline in a few seconds, with no services. The lab's 390 unit tests, the contract test among them, run in under two seconds without Docker; they all pass. Other work kept the laptop busy during the paging runs (a load average, the number of processes wanting a core, of about 11), so read the shapes, not the last digit.
A stack of receipts
The service has an orders API over the 10-million-row orders table from Chapter 6, with ids 1 to 10,000,000. Apps ask for orders newest first, 100 at a time, and a nightly export pages through all of them.
Think of a stack of paper receipts, one per order, newest on top. The API is a clerk who hands them out 100 at a time. Each receipt is a printed form, and apps read its boxes: a field is one box on the form, and the form itself, the list of fields and what each holds, is the schema. Both bugs in this chapter live in that picture: one in how you ask the clerk for the next 100, the other in what happens when the form changes.
Two ways to ask for the next page
There are two ways to say "the next 100". The lab's pagination.py has both:
OFFSET_SQL = "SELECT {cols} FROM {table} ORDER BY id DESC LIMIT $1 OFFSET $2"
CURSOR_SQL = "SELECT {cols} FROM {table} WHERE id < $1 ORDER BY id DESC LIMIT $2"
- Offset counts: newest first, skip this many, take 100 (
LIMIT 100takes 100 rows;OFFSET 9900skips 9,900 first). The request isGET /api/orders?limit=100&offset=9900. In clerk terms, page 100 is "skip the first 9,900, then give me 100", and the clerk counts down from the top every time. - Cursor remembers: take 100 with a lower id than the last one I saw. Page 100 is "the last receipt I saw was #9,990,101; give me the 100 older than it". The stack is in number order, so the clerk opens it right there. This is also called keyset pagination.
Each answer carries a next_cursor, which the app sends back as ?after=… to get the next page. The lab makes it opaque: the last id, encoded and signed with an HMAC (a keyed hash: only the server, which holds the key, can make a valid signature). The cursor after #9,990,101 is eyJpZCI6OTk5MDEwMX0.tsLUvAZidsblJxOb. A client can't build its own or edit one (a tampered cursor gets HTTP 400, Bad Request), and it can't come to depend on the format, which the server may want to change.
Deep pages
02_pagination.py times page k both ways: 15 requests each through the API, after one warm-up, reporting the median (p50). It also checks that both methods return the same 100 orders.
| Page | Rows offset skips | Offset p50 | Cursor p50 |
|---|---|---|---|
| 1 | 0 | 1.95 ms | 1.92 ms |
| 100 | 9,900 | 2.72 ms | 2.54 ms |
| 10,000 | 999,900 | 50.5 ms | 1.88 ms |
| 100,000 | 9,999,900 | 606 ms | 2.32 ms |
On shallow pages, you can't tell them apart. Page 1 and page 100 cost about 2–3 ms either way, which is why offset looks fine in testing. On deep pages, offset's cost grows with depth; the cursor's stays flat. Page 100,000 took 606 ms by offset and 2.3 ms by cursor: about 260 times slower (606 ÷ 2.32 ≈ 262), for the same 100 orders.
Why, from Postgres itself. EXPLAIN ANALYZE runs a query and reports what the database did; for page 10,000:
| Page 10,000 | Index entries read | 8 KB pages touched |
|---|---|---|
| offset | 1,000,000 | 13,964 |
| cursor | 100 | 5 |
The index here is the database's sorted list of order ids, the primary key (Chapter 6 covers indexes and pages). Offset read a million entries from it and threw away all but the last 100: there's no way to skip 999,900 rows without walking past them. The cursor's WHERE id < 9000101 is one lookup to the right place in the index, then 100 entries.
What Postgres did for page 10,000 (EXPLAIN ANALYZE, one run)
Offset read 999,900 entries only to throw them away, then the 100 it returned. The cursor read the 100. Both pages held the same orders (the script checks).
The stack is to scale: the shaded part is what offset counts past, out of 10M. Each time is the median (p50) of 15 requests through the lab's REST API on a busy laptop (load average about 11). Offset is ORDER BY id DESC LIMIT 100 OFFSET n; the cursor is WHERE id < last_seen ORDER BY id DESC LIMIT 100.
When the stack changes
Speed is the obvious problem. The silent one shows up when the stack changes while someone is reading it.
A small example, five per page (an illustration, as in the video). You already have page 1: #50 down to #46.
- Two new receipts land on top (#52, #51). Offset asks: skip 5, give me 5. Everything moved down by two, so skipping 5 lands on #47: #47 and #46 come back a second time. The cursor asks for 5 older than #46: nothing twice.
- Two receipts you already read are removed (#50, #49). Offset skips 5 again, but everything below moved up by two: it lands on #43, and #45 and #44 are never shown. The cursor: nothing twice, nothing skipped.
A duplicate, someone might spot. A missing order is much harder to notice: the page is full, and the list looks complete.
The real run
Then the lab's version. It copies the 20,000 newest orders into a small table called feed, so it can change it freely, and pages through the newest 5,000 of them: 50 pages of 100, reading the pages through the API. Between pages, it adds new orders on top and removes orders the reader has already seen (picked at random). Then it counts, with duplicates_and_skips in pagination.py:
- a duplicate is an order the reader got twice;
- a skip is an order that was there for the whole run, inside the range the reader covered, and never came back. Orders that were removed don't count as skips, and neither do the new ones.
| Between each page | Method | Orders returned | Twice | Skipped |
|---|---|---|---|---|
| nothing changes | offset / cursor | 5,000 / 5,000 | 0 / 0 | 0 / 0 |
| 5 new orders on top | offset | 5,000 | 245 | 0 |
| cursor | 5,000 | 0 | 0 | |
| 2 already-read orders removed | offset | 5,000 | 0 | 98 |
| cursor | 5,000 | 0 | 0 | |
| both | offset | 5,000 | 147 | 0 |
| cursor | 5,000 | 0 | 0 |
The errors are exact, not luck. 50 pages have 49 gaps between them. Each new order on top pushes every later order down by one, and each removal above the reader pulls them up by one:
5 new per gap: 49 × 5 = 245 orders twice
2 removed per gap: 49 × 2 = 98 orders skipped
both: 49 × (5 − 2) = 147 orders twice, 0 skipped
With both at once, the two removals cancel two of the five repeats in each gap: the stack still moves down, by three, so nothing is lost; three orders per gap come back twice. (The lab's README and its printed observation say the skips are "hidden inside the shift". The counter, which checks every order that was there all along, recorded 0 skips: none is missing.) The flip side: had the removals matched the additions, offset would have looked perfect, by luck.
The cursor had zero of either, every time. "Older than #N" doesn't move when orders are added above or removed elsewhere. And if #N itself is removed, id < N still works: the cursor holds a value, not a position.
Neither method showed orders added after paging started (0 in every run). Offset never went back to the top; the cursor only looks below. Those orders appear the next time someone starts from the top. For a feed with "load more", that's what users expect; for an export, it means the export is a picture of the moment it began, plus whatever later changes it happens to see.
A small stack, 5 per page · illustration
Two new receipts pushed everything down by two, so skipping five lands on #47: #47 and #46 come back a second time.
The lab's run, replayed · simulation of the lab's own paging loop
49 gaps between 50 pages × 3 net shift (5 added − 2 removed) = 147 returned twice
Recorded in the lab at this setting: offset 147 twice and 0 skipped, the cursor 0 and 0. The replay gives the same. Every run returned 5,000 orders, and neither method showed an order added after paging started (0).
The replay runs the lab's loop on a list of the 20,000 newest orders (#9,980,001 to #10,000,000) in your browser: read a page, add orders on top, remove random already-read orders, repeat 50 times; then the lab's counter. A repeat is an order seen twice; a skip is an order present the whole time, inside the range read, never seen. The lab ran it against Postgres through the API. The small stack is an illustration, as in the video.
The receipt form
The second silent bug lives on the form itself. The order has six fields: id, customer_id, status, created_at, total_cents (the total in cents, a whole number) and note (free text, such as "leave at the door"). It travels in one of two formats.
- JSON writes every value with its name next to it:
"total_cents": 12345. An old app finds the total by its name. - Protobuf (Protocol Buffers) is a compact binary format, used by gRPC, a common way for services to call each other. Its schema is a
.protofile that gives each field a number:int32 total_cents = 5;(int32 is a 32-bit whole number). On the wire there are no names, only box numbers. The total 12,345 is three bytes,28 b9 60:0x28says "box 5, a whole number follows" (5 × 8 + 0), andb9 60is 12,345. The old app keeps last year's blank form, which says box 5 is the total.
The schema an API has promised its clients is its contract. To see which changes break it, 06_contracts.py makes five changes to version 1 (v1) of the order, one at a time, and asks two things about each: what the lab's checker in compat.py says, by comparing the v1 schema with the new one, and what old apps actually do with an order written in the new format. The "apps" are small test programs in the same script, not deployed clients.
Changing a JSON order
Two old JSON apps, both built for v1:
- a careful one that knows each field's type: a pydantic model of v1 (pydantic is a Python library that checks data against declared types, and converts where it can);
- a plain one that just reads by name, like a lot of front-end code:
order["total_cents"] / 100,order["note"].upper(),order["id"] + 0.
| Change | Checker | Careful app | Plain app |
|---|---|---|---|
add a field, currency |
✅ safe | ok | ok |
rename total_cents → amount_cents |
❌ breaking | error: missing | error: KeyError |
id: number → text |
❌ breaking | ok | error: TypeError |
note may now be null |
❌ breaking | error: string_type | error: AttributeError |
remove note |
❌ breaking | error: missing | error: KeyError |
The errors are Python's: KeyError is a missing key in a dictionary, TypeError adding a number to text, AttributeError calling .upper() on nothing (null arrives as Python's None); "missing" and string_type are pydantic's reports for a required field that isn't there and a value that isn't text.
- Adding a field is the one change both survived. Old apps ignore fields they don't know.
- A rename is a removal. To an old app,
total_centsis simply gone; thatamount_centsholds the same number doesn't help. - The checker marked every change that broke an app, and one more. The careful app survived
idturning into text: pydantic converted"9876543"back to a number. The plain app crashed. A checker can't know how lenient each of your clients is, so flagging the change is the right default. - Null is a change of type. "The note may be null" (null: no value at all) breaks code that always found text there.
Changing a Protobuf order
Now one old Protobuf app: the v1 generated class, reading bytes written with each new form. Each change starts from the original form.
| Change | Checker | Old app reads |
|---|---|---|
add box 7, currency |
✅ safe | ok |
rename total_cents → amount_cents, keep box 5 |
⚠️ warning | ok |
move total_cents from box 5 to box 7 |
❌ breaking | no error, but total_cents = 0 |
total_cents int32 → int64 (box 5) |
❌ breaking | ok |
total_cents int32 → string (box 5) |
❌ breaking | no error, but total_cents = 0 |
- A rename is invisible on the wire. The bytes are identical; the box is still 5. The checker only warns, because code generated from the
.proto, and Protobuf's own JSON form, still use the name. - Moving the total to box 7 is worse than an error. The old app reads box 5, finds nothing, takes the default, and reports a total of 0. Box 7 is a box its form doesn't have, so it skips it. And a total of 0 looks like real data: an invoice for nothing, a free order, a sum that's quietly wrong.
- Making the total text does the same. Box 5 is still there, but it now holds the five characters "12345" (
2a 05 31 32 33 34 35: box 5, a length, then the text). The old app can't read text as a number, skips it, and reports 0. - A bigger number type (int64, 64 bits) still read 12,345, because it fits: the bytes are the same. The checker flags it anyway, because a total too big for 32 bits wouldn't fit. (The lab didn't try one.)
So in Protobuf, a field number, once used, is never changed or reused. To remove a field, delete it and mark its number reserved in the .proto, so nobody can give it to a new field later.
The new form (v2), box by box
The old app's blank form says: box 5 is total_cents, a whole number.
The total on the wire
v1: 28 b9 60
v2: … 38 b9 60
tag 0x38 = box 7. The old app has no box 7, skips it, and finds no box 5.
The old app reads total_cents
0
No error. A total of 0 looks like real data.
The checker
❌ breaking
field number removed: old readers silently get the default (0); and it isn't reserved, so it could be reused
Recorded by 06_contracts.py: each change is made to the v1 schema on its own, and the "apps" are small test functions in the same script, not deployed clients. The bytes were written with each v2 form by the lab's own code. A tag byte is the box number × 8 plus the kind of value: 0x28 is box 5 holding a whole number, 0x38 box 7, 0x2a box 5 holding a length-prefixed value such as text.
The contract, in a test
How do you catch this before an app does? Keep the promised form on file and compare against it in a test. The lab keeps the v1 contract in its repository as two files: contracts/orders_v1.schema.json (the order's JSON Schema, a standard format for listing JSON fields and their types, as pydantic writes it) and contracts/orders_v1.binpb (the compiled v1 .proto). Its contract test, tests/test_contract.py, runs the same checker against the API as it is now (shortened):
def test_rest_responses_are_compatible_with_v1():
v1 = json.loads((CONTRACTS / "orders_v1.schema.json").read_text())
for name, model in (("Order", orders_api.Order), ("OrderList", orders_api.OrderList)):
problems = breaking(json_schema_changes(v1[name], model.model_json_schema(), "response"))
assert not problems, f"{name} breaks the v1 contract: {problems}"
and the same for the .proto, compiled fresh and compared with the v1 file. Rename total_cents in the order model, or renumber it in the .proto, and the test fails. CI (continuous integration: the service that runs the tests on every change) goes red, before any app sees the change.
The contract files are snapshots: nobody edits v1. A change on purpose either keeps v1 intact (only add fields), or ships as a new version served alongside v1 until logs show no client still uses the old one. To rename a JSON field: add the new name, keep sending the old one too, move clients over, and stop sending the old name only when no app version that reads it is still in use.
A schema check has a limit: it sees types and names, not meaning. Switching total_cents from cents to euros, still a whole number, passes it.
Caveats
- One run per setting, on a busy laptop. The deep-page times are medians of 15 requests each, at a load average of about 11. The ratios and the shapes (flat for the cursor, growing for offset) are the result; the exact milliseconds will move.
- The
EXPLAIN ANALYZEtime isn't the page time. The same page-10,000 offset query reported 107 ms inside the database, against the 50 ms median through the API: that was a single run, and timing every row it reads adds its own cost. Use its row and page counts, which don't depend on timing. - The paging run used a 20,000-row copy, and removed only orders the reader had already seen. Removing orders the reader hasn't reached yet doesn't shift offset's later pages; the lab didn't try it.
- The small receipt stacks are illustrations. The replay in the second widget is a simulation: the lab's own paging loop and counter, run in your browser on a list instead of Postgres. At the lab's four settings it gives the recorded numbers; other settings are the simulation only.
- The schema "apps" are small test functions in one script, not deployed clients, and the plain one is Python. Plain JavaScript would still crash on a missing or null
note(calling a method on nothing), but get silent wrong values on others: a missingtotal_centsdivided by 100 isNaN, and"9876543" + 0is the text"98765430". Not tested in the lab. - The int32 → int64 case was only tried with a total that fits. What an old client makes of a bigger one wasn't measured.
The checklist
- Page with a cursor, not a count, for anything that pages deep or while the data changes: an export, a sync, a feed. Make the cursor opaque and signed.
- If you must offer offset (a "jump to page 500"), cap how deep it goes, or offer search and filters instead.
- Sort on something unique. A cursor on a column with ties (
created_at) needs a tiebreaker:(created_at, id). - Test paging while the data changes, and count repeats and missing rows against the rows that were there all along. A full page proves nothing.
- Only add fields. To rename one, add the new name and keep sending the old until no client reads it. Treat "may now be null" as a breaking change.
- In Protobuf, never change or reuse a field number; reserve the numbers of removed fields.
- Keep the published contract in the repository and check it in CI, so a breaking change fails the build, not an app.
Practice: count the repeats
Write the lab's logic: offset and cursor pages, the lab's duplicate-and-skip counter, a paging run on a list that changes between pages (the tests check it against the recorded 245, 98, 147 and zeros), the prediction from the number of gaps, a small Protobuf reader that finds the total in box 5 (fed the exact bytes the lab's code wrote for each change), and a JSON checker that flags removals and type changes.
Quiz
1.Why does page 100,000 by offset take hundreds of times longer than page 1, when both return 100 orders?
2.A nightly export pages through orders by offset while 2 already-read orders are deleted between each pair of pages. Over 50 pages, what happens?
3.In the lab, 5 inserts and 2 deletes per page gave 147 orders returned twice and 0 skipped. Why 0 skipped?
4.Your API returns orders as JSON and you want to rename total_cents to amount_cents. Mobile apps can't be forced to update. What's the safe way?
5.A Protobuf change moves total_cents from field number 5 to 7. What does an old client do with the new bytes?
6.The checker flagged changing id from a number to text as breaking, yet the careful (pydantic) client still worked. Was the checker wrong?
Check your understanding
Try each question before opening its answer.
Why does offset get slower the deeper you page, while a cursor doesn't?
Offset has to walk past every row it skips: for page 10,000, Postgres read 1,000,000 index entries and 13,964 pages to return 100 orders, and page 100,000 took 606 ms. A cursor asks for rows below the last id seen, which is one lookup in the sorted index, then 100 entries: about 2 ms on every page.
Offset pagination returned the same order on two consecutive pages. What happened, and what's the worse failure?
Orders were added above the reader between the two requests, pushing everything down, so the next page started on orders already seen: 5 per gap gave 245 repeats over 50 pages. The worse failure is the opposite: removals above the reader pull everything up, and orders are skipped without a trace: 2 per gap gave 98 missing orders, with full pages and no error.
With 5 orders added and 2 removed between each page, why were 147 orders returned twice and none skipped?
The shifts add up: 5 down, 2 up, so 3 down per gap. Three orders per gap come back twice, 49 gaps × 3 = 147, and since the stack only moved down, nothing was jumped over. The lab's counter checks every order that was there throughout and found none missing.
Does a cursor show orders that were added after you started paging?
No, and neither did offset in the lab (0 new orders seen in every run). The cursor only looks below the last order seen; new orders are on top. They show up when the reader starts again from the top, which for a feed is the refresh.
Why is renaming a JSON field breaking, but renaming a Protobuf field (keeping its number) isn't on the wire?
JSON sends the name with every value, so an old app looking for total_cents finds nothing: both test apps broke. Protobuf sends only the field number; the bytes after a rename are identical, so the old app read 12,345. The checker still warns, because generated code and Protobuf's JSON form use the name.
Why is moving a Protobuf field to a new number worse than a crash?
The old app looks in the old box, finds nothing, takes the default and reports a total of 0, with no error. A crash gets noticed and fixed; a total of 0 looks like real data and flows into invoices and reports. That's why a field number is never changed or reused.
How do you stop a breaking API change from reaching production?
Keep the published schema (JSON Schema, the compiled .proto) in the repository, and run a compatibility check of the current API against it in CI, so a breaking change fails the build. Make breaking changes only as a new version served alongside the old one until logs show no client still uses it. A schema check won't catch a change of meaning, such as cents to euros in the same field.
Next up: Chapter 12, load balancing. Every service so far was one process behind one port. Next, several copies behind a load balancer: what the balancer costs, how it picks a server, and what one slow server does to the slowest requests.