ealeng

Episode 11 of 55 · APIs

Pagination and breaking schema changes: no error, wrong answer

Paging through 5,000 orders while the data changed returned 5,000 orders and no errors, but 98 of them were never in the list. After one small change to the order format, an old app read a total of 0, also without an error. Offset vs. cursor pagination on 10 million orders (page 100,000: 606 ms against 2.3 ms), what changing data does to each, and which JSON and Protobuf schema changes break old clients, caught by a contract test.

Lab 06 · APIs and Service Communication17 min read
Video transcript9:39

0:00Cold open

0:01

I paged through my newest five thousand orders, a hundred at a time, while the data changed.

0:08

Five thousand orders came back. No errors.

0:13

But ninety-eight orders were never in the list.

0:18

And after one small change to the order format, my old app read an order’s total as zero. No error either.

0:27

Nothing crashed. So how do you catch bugs like these?

0:33Intro

0:34

Hands-on system design, part eleven.

0:37

Today: API bugs that never raise an error.

0:42Meet Lucía

0:43

I’m Lucía, a platform engineer.

0:46

My service has an orders API. Ten million orders, each with a number, newest first.

0:54

Apps ask it for lists, a hundred at a time. A nightly export pages through all of them.

1:01

Think of a stack of paper receipts, newest on top: one receipt per order. The API is a clerk who hands them out, a hundred at a time.

1:11

And each receipt is a printed form. Apps read its boxes.

1:1701 · What you need

1:19

To run it yourself: Python with a few packages, and Docker for Postgres and the services.

1:26

The tests run in a couple of seconds, without Docker.

1:31

No cloud, and no API keys.

1:3602 · Two ways to ask, in code

1:37

There are two ways to ask for the next page. Here they are, in the code.

1:43

The first one counts. Newest first, skip this many, then take a hundred. That’s called offset.

1:50

The second one remembers. Take a hundred with a lower number than the last one I saw. That’s called a cursor.

1:5903 · In clerk terms

2:00

In clerk terms, offset asks for page one hundred like this: skip the first nine thousand nine hundred, then give me a hundred. The clerk counts down from the top, every time.

2:13

The cursor says: the last receipt I saw was number nine million, nine hundred ninety thousand, one hundred one. Give me the hundred older than it. The stack is in number order, so the clerk opens it right there.

2:2804 · Deep pages

2:30

So how fast is each? Page one: both about two milliseconds. Page one hundred: both under three.

2:38

Page ten thousand: offset, fifty milliseconds. The cursor: still about two.

2:45

Page one hundred thousand: offset, six hundred milliseconds. The cursor: two.

2:52

About two hundred sixty times slower, for the same hundred orders.

2:5905 · Why offset slows down

3:00

Why? For page ten thousand, I asked the database what it did. Both returned the same hundred orders.

3:08

Offset read a million entries from the index, the database’s sorted list of order numbers, and threw away all but the last hundred.

3:18

The cursor read a hundred.

3:22

Offset’s cost grows the deeper you go. The cursor’s stays flat.

3:2806 · New receipts on top

3:30

Speed is the obvious problem. The silent one shows up when the stack changes while you read.

3:37

A small example, five per page. You already have page one: number fifty down to forty-six.

3:44

Now two new receipts land on top.

3:48

Offset asks: skip five, give me five.

3:53

Forty-seven and forty-six come back again. Two twice.

3:58

The cursor asks for five older than forty-six. Nothing twice.

4:0507 · Receipts removed

4:06

Now the other way. Two receipts you already read are removed. Fifty and forty-nine.

4:13

Offset skips five again. But everything below moved up by two.

4:18

Forty-five and forty-four are never shown. Two skipped.

4:24

A duplicate, you might spot. A missing one is much harder to notice.

4:30

The cursor: nothing twice, nothing skipped.

4:3508 · The real run

4:37

Now the real test. Page through the newest five thousand orders, fifty pages, while the data changes.

4:45

Five new orders on top after each page. With offset, two hundred forty-five orders came back a second time.

4:54

Two already-read orders removed after each page. Ninety-eight skipped.

5:01

Both at once: a hundred forty-seven came back a second time, and none were skipped.

5:07

Not luck. Fifty pages have forty-nine gaps between them. Five new orders per gap: two hundred forty-five repeats. Two removed per gap: ninety-eight skipped. Both: the two removals cancel two of the five repeats, so nothing is lost, just three repeats per gap: a hundred forty-seven.

5:28

The cursor: zero, every time.

5:32

Neither method showed orders added after the paging started. Those appear the next time you start from the top.

5:4109 · The receipt form

5:42

The second silent bug lives on the form itself. A field is a box on the form.

5:49

In JSON, every value has its name written next to it. An old app finds the total by its name: total cents.

5:58

Protobuf is a compact format used by gRPC, a common way for services to talk. On the wire, it has no names, only box numbers. The old app keeps last year’s blank form, which says box five is the total.

6:1610 · Changing a JSON order

6:17

I tried five changes on two kinds of old app: small test programs. A careful one that knows each box’s type, and a plain one that just reads by name.

6:29

Adding a field: both fine.

6:32

Renaming total cents: both broke. To an old app, a rename is a removal.

6:39

Changing the id from a number to text: the careful app still worked. It knows the id is a number, so it converted the text back. The plain app crashed.

6:50

Removing the note, or letting the note be null, no value at all: both apps broke.

6:57

A checker compares the promised blank form with the new one. It marked every change that broke an app. It also marked the id change: one app crashed on it, and it can’t know which apps your users run.

7:1111 · Changing a Protobuf order

7:13

Now Protobuf. The old app reads bytes written with the new form. Each change is tried on its own, starting from the original form.

7:23

Adding a new box, seven, for a currency: fine.

7:27

Renaming total cents, but keeping box five: fine. On the wire, a box is just its number. The checker only warns.

7:37

Now move the total from box five to box seven. What does the old app do?

7:45

No error. It reads box five, finds nothing, and reports a total of zero.

7:52

And a total of zero looks like real data.

7:56

A bigger number type still read twelve thousand three hundred forty-five, because it fits. The checker flags it anyway, because a bigger total wouldn’t. Making the total text: box five is still there, but the old app can’t read text as a number, skips it, and reports zero.

8:15

So a box number, once used, should never be changed or reused.

8:2112 · The contract, in a test

8:23

So how do you catch this before an app does? Keep the promised blank form on file. That’s the contract, version one. Then compare against it in a test.

8:33

This test loads that promised form.

8:37

It runs the same checker against the API as it is now.

8:42

If anything breaks the promise, the test fails. CI, the robot that runs the tests on every change, goes red, before any app sees it.

8:54Back to Lucía

8:55

So, three lessons.

8:58

Page with a cursor, not a count. Fast at any depth, and in these tests, nothing twice or skipped while the data changed.

9:07

Only add fields. To rename one, add the new name, and keep sending the old one until no app reads it.

9:15

And put the contract in a test, so the build fails before an app does.

9:21

Next time: spreading requests across several servers.

9:26

For today: no error isn’t the same as right.Lucía: No error isn’t the same as right.

9:30Summary

9:31

Cursor, not offset. Only add fields. And a contract in a test.

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 100 takes 100 rows; OFFSET 9900 skips 9,900 first). The request is GET /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.

Try it · Page k, by counting and by rememberingLab 06 · 02_pagination.py · 10M orders, 100 per page, p50 of 15
10M receipts, newest on topoldest: #1offsetcounts past 999,900cursoropens below #9,000,101p50 through the API (log scale)1 ms10 ms100 ms1,000 msoffset50 mscursor1.88 msOffset: 27× the cursor's time, same 100 orders.
Receipts counted past
999,900
Offset p50
50 ms
Cursor p50
1.88 ms
Offset ÷ cursor
27×

What Postgres did for page 10,000 (EXPLAIN ANALYZE, one run)

index entries read8 KB pages touchedoffset1,000,00013,964cursor1005

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.

Try it · The stack changes while you readLab 06 · 02_pagination.py · 50 pages of 100

A small stack, 5 per page · illustration

Before: page 1 read#50#49#48#47#46#45#44#43#42#41#40#39#38#37#36After: page 2 by offset#52new#51new#50#49#48#47again#46again#45#44#43#42#41#40#39#38#37#36+ #52, #51 on top

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

Offset: twice
147
Offset: skipped
0
Cursor: twice
0
Cursor: skipped
0

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 .proto file 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: 0x28 says "box 5, a whole number follows" (5 × 8 + 0), and b9 60 is 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_cents is simply gone; that amount_cents holds the same number doesn't help.
  • The checker marked every change that broke an app, and one more. The careful app survived id turning 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.

Try it · Change the form, ask the old appLab 06 · 06_contracts.py · offline, in one script

The new form (v2), box by box

1id9876543
2customer_id42
3status"shipped"
4created_at_us1748781000000000
5total_centsno longer sent
6note"leave at the door"
7total_cents12345

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 ANALYZE time 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 missing total_cents divided by 100 is NaN, and "9876543" + 0 is 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

  1. 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.
  2. If you must offer offset (a "jump to page 500"), cap how deep it goes, or offer search and filters instead.
  3. Sort on something unique. A cursor on a column with ties (created_at) needs a tiebreaker: (created_at, id).
  4. 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.
  5. 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.
  6. In Protobuf, never change or reuse a field number; reserve the numbers of removed fields.
  7. 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.

Try it · Practice in PythonRuns in your browser · ⌘/Ctrl + Enter to run
page_practice.py79 lines

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.Why does page 100,000 by offset take hundreds of times longer than page 1, when both return 100 orders?

  2. 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. 3.In the lab, 5 inserts and 2 deletes per page gave 147 orders returned twice and 0 skipped. Why 0 skipped?

  4. 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. 5.A Protobuf change moves total_cents from field number 5 to 7. What does an old client do with the new bytes?

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

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.