ealeng

Episode 16 of 55 · Replication

Replication lag and read-your-writes

A user books a seat and then reads their bookings from a database replica. From a small, slow replica the booking was missing one time in five, and under write load about half the time. Nothing was lost: the replica hadn't caught up yet. How far behind a Postgres replica really is, why a dashboard of medians hides the bad seconds, and the reads that lag breaks: your own writes, and reads that go back in time. Then the fix that knows instead of guessing: a receipt number from the database's own log.

Lab 09 · Replication and Consistency18 min read
Video transcript7:45

0:00Cold open

0:01

I booked a seat. Then I looked at my bookings.

0:05

Reading from a small, slow copy, one time in five, my booking wasn’t there.

0:13

Under load, about half the time.

0:17

Nothing was lost. I was reading a copy of the database that hadn’t caught up yet. So how do you read from copies without this?

0:27Intro

0:28

Hands-on system design, part sixteen.

0:32

Today: how far behind a database copy is, and which reads that breaks.

0:38Meet Lucía

0:39

I’m Lucía, a platform engineer.

0:42

My service has one Postgres database that takes every write. It’s called the primary.

0:49

And two copies, called replicas, that can answer reads, to share the reading work. The second one is small on purpose, a quarter of a CPU, so we can see what a slow copy does.

1:02

Think of an office. The primary is the main notice board. Each replica is a copy board in another room. A runner carries every change to each room, and a clerk there pins it up. That pinning is called replaying. And lag is how far behind a copy board is.

1:2101 · What you need

1:22

To run it yourself: Python with a few packages, and Docker for the primary, two replicas, and the app.

1:30

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

1:35

No cloud, and no API keys.

1:4002 · How far behind?

1:41

First: how far behind is a copy? Every fifty milliseconds I write a heartbeat, a tiny note, to the primary, and check when each copy has it. About six hundred per run.

1:53

At idle, the typical lag, called the median, was under a millisecond. On both copies.

2:01

Then I added four thousand updates a second. From now on, that’s what under load means. Take the slowest heartbeat in every hundred. Replica one: two milliseconds in the first run, five in the second.

2:15

Replica two, the small one: twenty-seven and thirty milliseconds. Six to thirteen times more.

2:23

Same changes, each carried by its own runner. But replica two’s clerk has a quarter of a CPU, so most likely it just replays them more slowly.

2:3503 · One big update

2:37

Now one big update: a single statement that changes all two hundred thousand rows of a table. On the primary, it took under a second, and produced a hundred and four megabytes of changes to copy.

2:51

Replica one fell fifty-five milliseconds behind.

2:56

Replica two fell nine hundred seventy-six milliseconds behind. Almost a second. At the worst moment, every read on it saw the database as it was almost a second ago.

3:09

And the median lag over that run? Under a millisecond, on both. A dashboard of medians would have shown nothing.

3:1804 · My own booking

3:20

Now the test that matters to a user. Eight users each book a seat, and right after, read their bookings.

3:28

Reading from the primary: the booking was always there.

3:33

Reading from replica one: missing four point six percent of the time at idle. Eleven and a half percent under load.

3:41

Replica two: twenty percent at idle. Under load, about half.

3:47

The read was sent right after the write finished. It was sent within a microsecond, so even a fraction of a millisecond of lag is sometimes too late.

3:5905 · A receipt number

4:00

The fix: a receipt number. Postgres keeps every change in a log, the write-ahead log, and each change has a position in it. That position is called the LSN.

4:13

After the write, the service notes that position and sends it back with the answer. The user’s app includes it with the next read.

4:22

Before that read, the service asks replica one, the only copy it uses here: have you replayed that far yet?

4:30

If yes, read the copy. If not, read the primary.

4:3506 · Never missing

4:37

With the receipt number, the booking was never missing. Not once, at idle or under load.

4:44

And it still used the copy for most reads. Only four percent went to the primary at idle. Twenty-eight percent under load.

4:53

It adapts: when the copy is busier, more reads go to the primary. It’s careful, so it sends some that didn’t strictly need it: twenty-eight percent, when only about eleven would have missed.

5:0707 · Or wait a moment?

5:09

A simpler idea: after a write, send that user’s reads to the primary for a few milliseconds. This is a new run, and it came out a little higher than before: with no window, under load, fourteen percent of reads missed the booking, not eleven and a half.

5:26

Ten milliseconds: none missed.

5:30

But twenty milliseconds let four reads through, out of about five thousand. Most likely the laptop stalled during that run: it managed fewer than half the usual reads, so some came later than the window. A window has to cover the worst case, and the worst case comes on bad days.

5:48

And with five milliseconds or more, ninety-nine to a hundred percent of reads went to the primary, because here every read came right after its write. The receipt number sent twenty-eight. The window guesses. The receipt number knows.

6:0508 · Back in time

6:06

A different test: forget bookings. Picture a number on the main board that goes up five hundred times a second, and eight readers reading it over and over.

6:17

Sending each read to a random copy: four and a half percent of reads were older than one the reader had already seen. Under load, almost nine percent.

6:28

Up to forty-two counter values back. Each copy only moves forward, but the two copies are at different points, so switching between them can go backwards.

6:39

Keeping each reader on one copy, here replica one, fixed it completely. So did a receipt number for reads: each answer carries how far that copy had got, and the next read goes only to a copy at least that far. It spread reads over both copies and never needed the primary.

6:59Back to Lucía

7:01

So, three lessons.

7:03

Watch the worst lag, not the median: the slowest one in a hundred, and the furthest behind. The median hides the bad seconds.

7:13

If users must see their own writes, read from a copy only with a receipt number.

7:19

And keep each reader on one copy, or carry the receipt number, so nobody goes back in time.

7:27

Next time: what happens when the primary waits for its copies.

7:32

For today: keep the receipt.Lucía: Keep the receipt.

7:36Summary

7:37

Watch the worst lag, read your writes with a receipt number, and keep readers on one copy.

Key takeaways

  • ✓A replica is a copy of the database that replays the primary's changes a little later. Measured as a reader sees it, with a heartbeat row every 50 ms, the median lag was under a millisecond on both replicas, at idle and under write load.
  • ✓The tail is what matters. At 4,000 updates a second, the slowest 1 in 100 heartbeats (p99) were 2.1 and 4.6 ms behind on the full-CPU replica and 27.3 and 30.3 ms on the one with a quarter of a CPU, in two rounds: six to thirteen times more, with the same changes to replay.
  • ✓One UPDATE of 200,000 rows (0.8 s on the primary, 104 MB of changes) put the small replica 976 ms behind, and every read on it saw the database as it was almost a second earlier. The median lag over that run was 0.67 ms on both: a dashboard of medians would have shown nothing.
  • ✓Reading your own write from a replica fails even at idle, because the read comes right after the write. A booking was missing on 4.6% of reads from the full-CPU replica and 20.1% from the small one at idle; 11.5% and 50.9% under load. From the primary, never.
  • ✓A receipt number fixes it while still using the replica. The write returns its position in the database's change log (the LSN); the read goes to the replica only if it has replayed that far, else to the primary. 0 misses in about 26,000 reads, with 4% of reads sent to the primary at idle and 28% under load.
  • ✓Reading from the primary for a few milliseconds after each write guesses the lag. Under load, 10 ms had no misses but 20 ms let 4 of 5,254 through in a run where the laptop most likely stalled, and any window of 5 ms or more sent 99–100% of these immediate reads to the primary.
  • ✓Spreading one reader's reads over two replicas sends them back in time: 4.5% of reads at idle and 8.8% under load were older than a value the reader had already seen, by up to 42 steps of a counter. Keeping each reader on one replica fixed it, and so did a receipt of how far the last answer's replica had got, which still used both replicas.

A user books a seat, then opens "my bookings". The service sends that read to a copy of the database, to share the reading work. From a small, slow copy, the booking wasn't there one time in five; with other writes going on, about half the time. Nothing was lost. The copy simply hadn't caught up yet. This chapter measures how far behind a database copy really is, which reads that breaks, and how to read from copies without it.

The examples come from Lab 09 (Replication and Consistency) of the system design labs, scripts 01_lag.py (how far behind each copy is), 03_read_your_writes.py (does a user see their own booking) and 04_monotonic_reads.py (does a reader go back in time), with the lab's modules consistency.py (violation counts and their intervals), probe.py (the probes that write and read) and service/app.py (the booking service and its read policies). Chapter 17 covers the rest of the lab: synchronous replication (02_sync_replication.py) and a quorum store (05_quorum.py). The setup is the earlier chapters' laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): Postgres 18.6 and a Python web service (FastAPI), all in Docker. The lab's 367 unit tests (the interval, the violation count, the percentile code, the quorum rule) run in about 2 seconds without Docker; they all pass. Other work kept the laptop busy (a load average, the number of processes wanting a core, of about 10 to 30), so read the shapes, not the last digit.

One primary, two copies

The service has one Postgres database that takes every write: the primary. Before a change counts as done, Postgres records it in its write-ahead log (WAL), an append-only list of every change, in order. Two copies, called replicas, receive that log as it's written and apply it to their own data, so they hold the same data a little later and can answer reads. Applying the log is called replaying it, and in Postgres each replica replays it in a single process. This is streaming replication. Here it's asynchronous: the primary confirms a write without waiting for any replica (chapter 17 measures what waiting costs).

The two replicas are called replica1 and replica2 in the lab. replica1 has as much CPU as it wants. replica2 is small on purpose, a quarter of a CPU (cpus: 0.25 in Docker), to see what a slow copy does. Real replicas differ too: a smaller machine, a replica busy with long reports.

Lag is how far behind a replica is: how long after the primary confirms a change a reader on the replica can see it.

Think of an office. The primary is the main notice board. Each replica is a copy board in another room. A runner carries every change to each room (Postgres runs one sender per replica), and a clerk there pins it up: that's replaying. Lag is how far behind a copy board is. The clerk in room 2 has a quarter of a CPU.

How far behind is a copy?

Postgres reports its own estimates of lag, but the lab measures what a reader would see. Every 50 ms it writes a heartbeat, a tiny row, to the primary, and then polls each replica every half a millisecond until the row is there. The time from the primary's confirmation to the row being visible is that heartbeat's lag. About 590 heartbeats per 30 s run.

The lab ran it at idle and with background updates on the primary (random rows of a 200,000-row table), in two rounds interleaved so a slow moment on the laptop doesn't land on one load only. p99 is the 99th percentile: the lag that only the slowest 1 in 100 heartbeats exceeded.

Load Replica Lag p50 p99 (round 1 / 2) Max (round 1 / 2)
idle replica1 0.62 ms 4.8 / 2.7 ms 8.4 / 10.6 ms
idle replica2 (¼ CPU) 0.63 ms 5.4 / 2.9 ms 47.1 / 7.8 ms
1,000 updates/s replica1 0.39 ms 1.9 / 3.5 ms 7.4 / 21.6 ms
1,000 updates/s replica2 0.39 ms 5.8 / 4.0 ms 55.8 / 21.7 ms
4,000 updates/s replica1 0.38 ms 2.1 / 4.6 ms 16.6 / 26.1 ms
4,000 updates/s replica2 0.38 ms 27.3 / 30.3 ms 70.3 / 53.3 ms

The median was under a millisecond everywhere: one network hop and one replay. (It's a little lower under load than at idle; the lab doesn't say why.)

Under 4,000 updates a second, the small replica's tail grew. Its p99 was 27–30 ms, against 2–5 ms on the full-CPU replica: six to thirteen times more. The changes were the same, each carried by its own runner. But the small replica's clerk has a quarter of a CPU, so most likely it just replays them more slowly. From here on, "under load" means 4,000 updates a second.

Try it · The office and its copy boardsLab 09 · 01_lag.py · a heartbeat every 50 ms

The office · drawing of the mechanism; the numbers on the boards are recorded

Main boardthe primarytakes every write+ 4,000 updates/srunnerCopy board 1replica1 · clerk with a full CPUbehind by (p99)2.1 msrunnerCopy board 2replica2 · clerk with ¼ of a CPUbehind by (p99)27.3 ms

Round 1: median, p99 and max of about 593 heartbeats · log scale

0.1 ms1 ms10 ms100 ms1,000 msreplica1replica2 ¼writer p99the primary's own update latency, 15.2 ms

At 4,000 updates a second the median was still 0.37 ms, but the small copy's slowest 1 in 100 heartbeats were 27.3 ms behind, against 2.1 ms for the full-CPU copy: 12.8 times more. Same changes, each carried by its own runner; most likely the small clerk just pins them up more slowly.

Lag here is the time from the primary acknowledging a heartbeat row to the row being readable on the replica, polled every 0.5 ms, so it includes one small query. Asynchronous replication; the background updates change random rows of a 200,000-row table. Two rounds per load, interleaved (0, 1,000, 4,000 then 4,000, 1,000, 0 updates/s). The office is a picture of the mechanism; the runner is Postgres's WAL sender and the clerk its replay process.

Is it the replica, or the machine? The lab also records the primary's own update latency (the "writer p99" in the widget: 15 and 23 ms at 4,000 updates a second). The lab's README describes an earlier run where both replicas showed a 2-second spike at 1,000 updates a second, and so did the primary's own latency: the whole laptop had stalled. That's why the script now runs two rounds and prints the writer's latency next to the lag. Before blaming a replica, compare its lag with the primary's own latency in the same moment.

One big update

Now one statement that changes every row of the 200,000-row table, during a 40 s heartbeat run. On the primary it took 0.8 s and produced 104 MB of log to copy.

Replica Furthest behind Back under 10 ms, after the peak Lag p50 over the run
replica1 55 ms 1.0 s 0.67 ms
replica2 (¼ CPU) 976 ms 1.4 s 0.67 ms

One statement put the small replica almost a second behind. And lag isn't per row: while replica2 replayed those 104 MB, every read on it saw the whole database as it was up to a second earlier, not just the updated rows.

The median doesn't show it. Over the run, the median lag was 0.67 ms on both replicas. A dashboard of medians would have said "under a millisecond" through the worst second. The p99 over the run (25 ms on replica2) hints at it; only the maximum shows it. Choose "One big update" in the widget above to see it per 2-second slice. There's a second, smaller bump about 20 s in (89 ms on replica2) that the lab doesn't explain.

The lab's advice for a nightly job that updates millions of rows in one transaction: split it into small batches, so the replicas fall a little behind many times instead of far behind once.

Reading my own booking

Now the test that matters to a user. Read-your-writes consistency means a user always sees their own writes (other users may still see old data for a moment). The lab's probe has 8 users; each books a seat and right away reads "my bookings", in a loop, for 12 s per row. A read misses if the new booking isn't in the list.

The service (service/app.py) has a few read policies, chosen per request. Writes always go to the primary. Reads go:

  • primary: always to the primary.
  • replica1, replica2: always to that replica.
  • lsn: the receipt number, below.
Reads go to Load Booking missing Rate (95% interval) Reads sent to the primary
the primary idle 0 of 13,636 0% (0–0.03%) 100%
replica1 idle 700 of 15,275 4.6% (4.3–4.9%) 0%
replica2 (¼ CPU) idle 2,569 of 12,778 20.1% (19.4–20.8%) 0%
the primary under load 0 of 10,296 0% (0–0.04%) 100%
replica1 under load 1,344 of 11,721 11.5% (10.9–12.1%) 0%
replica2 (¼ CPU) under load 4,277 of 8,395 50.9% (49.9–52.0%) 0%

The 95% interval is the range the true rate probably lies in, given how many reads there were (the lab uses a Wilson interval, which stays sensible even at 0 misses). "0 of 13,636" isn't "never": its interval says up to 0.03%.

Even at idle, 1 in 22 reads from the fast replica missed the user's own booking. The read was sent right after the write was confirmed: a median of under a microsecond later. So even a fraction of a millisecond of lag is sometimes too late. Under load, half the reads from the small replica missed.

A receipt number

The fix: a receipt number. Every position in the write-ahead log has a number, the LSN (log sequence number), written as two hexadecimal numbers like 0/BDBA518. On the primary, pg_current_wal_lsn() says how far the log has got; on a replica, pg_last_wal_replay_lsn() says how far it has replayed.

  1. After the write, the service notes the primary's LSN and sends it back with the answer. That's the receipt.
  2. The user's app includes it with the next read (the lab passes it as min_lsn; a real app could keep it in a cookie or a response header).
  3. Before that read, the service asks replica1, the only replica this policy uses: have you replayed that far yet? If yes, read the replica. If not, read the primary.

The code, from choose() in service/app.py (shortened):

# lsn: has replica1 replayed the client's last write yet?
if not min_lsn:
    return "replica1"
caught_up = await pools["replica1"].fetchval(
    "SELECT pg_last_wal_replay_lsn() >= $1::text::pg_lsn", min_lsn)
return "replica1" if caught_up else "primary"
Load Booking missing Rate (95% interval) Reads sent to the primary
idle 0 of 13,997 0% (0–0.03%) 4%
under load 0 of 12,198 0% (0–0.03%) 28%

With the receipt number, the booking was never missing. Not once, at idle or under load. And most reads still went to the replica.

It adapts, and it's careful. When the replica is busier, more reads go to the primary. Under load it sent 28% there, when reading replica1 blindly missed only 11.5%. The receipt is the primary's position read just after the booking commits, so it can include other writers' changes too (here, 4,000 background updates a second); the replica has to catch up past those before it qualifies. So some reads go to the primary that didn't strictly need to. The answer is never wrong.

Try it · Is my booking there?Lab 09 · 03_read_your_writes.py · 8 users, 12 s per row

Each user books a seat, then reads "my bookings" at once

read from the primary: 0.0% read from replica, booking there: 88.5% read from replica, booking missing: 11.5%
Booking missing
1,344 of 11,721
Rate
11.5%
95% interval
10.90%–12.06%
Sent to the primary
0%

11.5% of reads from the full-CPU copy missed a booking the user had just made. The read was sent a median 0.7 µs after the write was confirmed, so even a fraction of a millisecond of lag is sometimes too late.

One recorded run per row. A miss means the new booking wasn't in the list the read returned. The read is sent as soon as the write is confirmed, which is harsher than a real user who reads a moment later: with real users a window sends fewer reads to the primary, but the misses come from the same lag tail. The 95% interval is a Wilson interval on the miss rate.

Or wait a moment?

A simpler idea needs no log positions: after a user writes, send that user's reads to the primary for a few milliseconds, then back to the replica. The lab calls this policy sticky, with a window of N ms, measured from when the service recorded the user's last write. Under load, each window in its own run:

Window Booking missing Rate (95% interval) Reads sent to the primary
0 ms (always replica1) 1,781 of 12,758 14.0% (13.4–14.6%) 0%
1 ms 62 of 13,815 0.45% (0.35–0.57%) 50%
2 ms 9 of 12,834 0.07% (0.04–0.13%) 85%
5 ms 2 of 13,130 0.02% (0.00–0.06%) 99%
10 ms 0 of 9,041 0% (0–0.04%) 100%
20 ms 4 of 5,254 0.08% (0.03–0.20%) 99%
50 ms 0 of 14,033 0% (0–0.03%) 100%

These are new runs, and the 0 ms row came out a little higher than before: 14.0%, not 11.5%.

10 ms had no misses, and it didn't hold. A 20 ms window let 4 reads through. That run managed only 5,254 reads, fewer than half the usual: most likely the laptop stalled (the lab's README notes a load average of 30 around then), so some reads came more than 20 ms after their write while replica1 was still behind. A window has to cover the worst case of the lag, and the worst case comes on bad days.

A window that works sends almost everything to the primary. With 5 ms or more, 99–100% of reads went there, because here every read came right after its write. Real users read a moment later, so a real window would send fewer, but it still sends a read to the primary whether the replica is behind or not. The receipt number sent 28%. The window guesses; the receipt number knows. A window is still useful where there's no log position to compare: a cache, a search index, another company's service. Then measure the lag's tail and set the window above it, with margin.

Going back in time

A different test: forget bookings. The primary has a counter that goes up by 1, 500 times a second, and 8 readers read it over and over, 12 s per row. A read goes back in time if it returns a value below one this reader has already seen. Monotonic reads is the guarantee that this never happens: once you've seen some state, you never see an older one. Think of a comment count that says 12, then 9 on reload.

The read policies here:

  • random: a random replica for each read, like a load balancer spreading reads over replicas.
  • replica1: always replica1, so each reader is pinned to one copy.
  • lsn: each answer carries how far that replica had replayed; the next read goes only to a replica at least that far along (the service tries the two in random order), else to the primary.
  • primary: always the primary.
Reads go to Load Reads older than one already seen Rate (95% interval) Worst step back Served by primary / replica1 / replica2
a random replica idle 1,652 of 36,415 4.5% (4.3–4.8%) 42 0 / 50 / 50%
replica1 only idle 0 of 74,555 0% (0–0.01%) 0 0 / 100 / 0%
position check idle 0 of 26,985 0% (0–0.01%) 0 0 / 58 / 42%
the primary idle 0 of 73,221 0% (0–0.01%) 0 100 / 0 / 0%
a random replica under load 2,348 of 26,733 8.8% (8.4–9.1%) 34 0 / 50 / 50%
replica1 only under load 0 of 53,537 0% (0–0.01%) 0 0 / 100 / 0%
position check under load 0 of 23,124 0% (0–0.02%) 0 0 / 64 / 36%
the primary under load 0 of 59,288 0% (0–0.01%) 0 100 / 0 / 0%

Spreading reads over two replicas sent readers back in time on 4.5% of reads at idle and 8.8% under load, by up to 42 counter values (about 84 ms of history at 500 a second). Each replica only moves forward, but the two are at different points, so switching from the one ahead to the one behind is a step back.

Keeping each reader on one replica fixed it completely, and so did the position check, which still spread reads over both replicas (58/42% and 64/36%) and never needed the primary. Here the receipt isn't a write's position: it's how far the replica that gave the last answer had replayed.

The check costs a query per read. The service asks the replica how far it has replayed before every read, so the readers made 26,985 reads in 12 s instead of 36,415 at idle. The lab's README suggests caching the replay position for a millisecond or two; it isn't measured.

Try it · Going back in timeLab 09 · 04_monotonic_reads.py · a counter +1 500×/s, 8 readers, 12 s per row

One reader's reads · illustration: replica2 stalls for a moment, 42 values behind (the recorded worst step back)

countervalue read99911,00821,01911,0291−4221,04821,05911,0682
read from copy 1 (replica1) read from copy 2 (replica2) read from the primary a step back in time

The recorded run

Went back in time
1,652 of 36,415
Rate
4.5%
95% interval
4.33%–4.76%
Worst step back
42 values
served by primary: 0% served by replica1: 50% served by replica2: 50%

Each copy only moves forward, but the two are at different points, so switching between them can go backwards: 4.5% of reads, up to 42 counter values back (about 84 ms of history at 500 a second).

The walk above is an illustration: eight reads, a fixed copy order standing in for random picks, replica2 drawn stalling 42 values behind for two reads. The counts, rates, worst steps and served shares are the recorded runs, one per row. Under load, 4,000 background updates a second ran on the primary as well.

Pinning has its own cost, from the lab's README: if a replica dies, all its readers move at once, possibly to a replica that's further behind, which is a step back at that moment. The position check doesn't have that problem.

The README names a third guarantee, consistent prefix: never seeing a reply before the question it answers. With one primary and one log, each replica replays commits in order, so Postgres gives it for free; it breaks in stores whose parts replicate separately. It isn't measured here.

Caveats

  • One run per row, on a busy laptop. The load average was 10 to 30 while these ran. The 20 ms window's 4 misses are most likely from a stall, which the lab left in on purpose.
  • The lag is measured from the primary's confirmation to the row being readable, polled every 0.5 ms, so each value includes one small query. Sub-millisecond medians are an upper estimate of the replay itself.
  • The reads here are harsher than real users. Each read was sent within a microsecond of its write. A user who reads a second later misses far less often, but an app that redirects after a form submit reads within milliseconds.
  • Why the small replica falls behind is inferred. It has a quarter of a CPU and replays in one process; the lab doesn't trace the replay. Same for the bump 20 s into the big-update run.
  • One machine, one network. Between data centers, lag adds the network delay on top of the replay.
  • Not covered here: synchronous replication and quorum stores are chapter 17. Failover (promoting a replica when the primary dies) and replica query conflicts are left to later labs and the README's exercise ideas.

The checklist

  1. Measure lag as a reader sees it. Write a heartbeat to the primary and time how long until each replica has it. Postgres's own estimates are a starting point, not the answer.
  2. Watch the worst lag, not the median: the p99 and the maximum, at idle, under your real write load, and during your biggest transactions.
  3. Compare a lag spike with the primary's own latency before blaming the replica: a stalled machine looks like lag.
  4. Split big updates into small batches, so replicas fall a little behind often instead of a second behind once.
  5. If users must see their own writes, read from a replica only with a receipt number: the write's log position, compared with the replica's replayed position. Keep the receipt where the next request can find it (a cookie, a header).
  6. Treat "the primary for N ms" as a guess. If you have no log position to compare, measure the lag's tail and set the window well above it.
  7. Keep each reader on one replica, or carry the position of the last answer, so nobody goes back in time when reads are balanced over replicas.

Practice: lag, violations and receipt numbers

Write the lab's logic: the Wilson interval and the back-in-time count from consistency.py (checked against the lab's own tests), a linear percentile and a lag summary that shows why the median hides a big update, the comparison of two LSNs, and the three read routings from service/app.py: the receipt number, the time window, and the position check for monotonic reads. The tests use the recorded counts: 700 of 15,275 reads missing (4.26–4.93%), 0 of 13,997 with the receipt number, and a step back of 42.

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

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.At 4,000 updates a second, the median lag on both replicas was about 0.4 ms. What did the small replica's slowest 1 in 100 heartbeats show?

  2. 2.One UPDATE changed all 200,000 rows of a table. What did the lag look like over that 40 s run?

  3. 3.A user books a seat and reads their bookings at once from the full-CPU replica, with no other load. How often was the booking missing?

  4. 4.How does the receipt number (LSN token) decide where a read goes?

  5. 5.Under load, the receipt number sent 28% of reads to the primary, while reading the same replica blindly missed only 11.5%. Why the difference?

  6. 6.Reads are balanced at random over two replicas. What goes wrong, and what fixes it?

Check your understanding

Try each question before opening its answer.

How do you measure replication lag honestly, and why not just look at the median?

Write a heartbeat row to the primary and time how long until each replica has it, as a reader would. The median hides the bad moments: at 4,000 updates a second it was about 0.4 ms on both replicas, while the small replica's p99 was 27–30 ms. During one big update, the run's median was 0.67 ms while the small replica was 976 ms behind at the peak.

A nightly job updates 10 million rows in one transaction. What happens to reads on the replicas, and what would you change?

Every replica falls behind by however long it takes to replay that transaction, and during that time every read on it sees the whole database as it was before. In the lab, 200,000 rows (104 MB of log) put the small replica almost a second behind. Split the job into small transactions, so the lag stays small and spread out.

Idle lag is under a millisecond. Why did reads from a replica still miss the user's own booking?

Because the read came right after the write: under a microsecond later, at the median. Any lag at all is then sometimes too late. At idle, 4.6% of reads from the full-CPU replica and 20.1% from the small one missed; under load, 11.5% and 50.9%.

Walk through the receipt-number (LSN token) fix. What does it cost?

The write returns the primary's log position after the commit. The next read carries it, and the service asks the replica whether it has replayed at least that far: if yes it reads the replica, if not the primary. It never missed in about 26,000 reads. It costs a check per read, somewhere to keep the receipt, and some extra reads on the primary: 4% at idle, 28% under load, more than strictly needed because the receipt can include other writers' changes.

Why is "read from the primary for N ms after a write" worse than the receipt number?

It guesses the lag. A 10 ms window had no misses, but 20 ms let 4 reads through during a stall, because the worst case comes on bad days. And it sends every read inside the window to the primary whether the replica is behind or not: 99–100% of these immediate reads from 5 ms up, against 28% for the receipt number.

How can a load balancer over replicas send a user back in time, and what are two fixes?

The replicas are at different points, so a read from the one ahead followed by a read from the one behind steps back: 4.5% of reads at idle and 8.8% under load, by up to 42 counter values. Pin each user to one replica (0 of 74,555), or send each read only to a replica at least as far along as the last answer (0 of 26,985, still spread over both replicas).

Pinning each user to one replica fixed going back in time. What happens when that replica dies?

All its users move at once to another replica, which may be further behind, so they can step back at that moment. Checking the position of the last answer doesn't have that problem, at the cost of a query per read.

Next up: Chapter 17, synchronous replication and quorums. Everything here was asynchronous: the primary never waited for its copies. What happens when it does: what each level of waiting costs per write, what one frozen replica does to every write, and how a quorum of copies decides which reads can be stale.

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.