ealeng

Episode 08 of 55 · Concurrency

Every call said OK: race conditions, lost updates and write skew

With one worker, 10,000 bank transfers were perfect. With 32 at once, every transfer still answered OK, and 492 of 1,000 balances were wrong, off by 14,277 coins in all. How race conditions hide, how to catch them with checks after a concurrent test, five fixes measured on real Postgres, 1,000 buyers told they got one of 100 seats, and two doctors who both went off call.

Lab 05 · Concurrency, Locks and Deadlocks18 min read
Video transcript8:02

0:00Cold open

0:01

I wrote a bank transfer. One clerk at a time, ten thousand transfers: perfect.

0:08

Then thirty-two clerks at once. Every single transfer answered OK.

0:14

And the balances were off by fourteen thousand coins.

0:19

My ticket service did worse. A thousand buyers were told they got one of a hundred seats.

0:26

No crash. No error in the logs. How?

0:32Intro

0:33

Hands-on system design, part eight.

0:36

Today: race conditions, the bugs that answer OK.

0:41Meet Lucía

0:43

I’m Lucía, a platform engineer.

0:46

This is a tiny bank, on a real Postgres database. A thousand accounts, a thousand coins each.

0:54

A transfer moves coins from one account to another, and writes a line in the ledger: a list of every transfer. Replay the list, and you should get every balance.

1:05

After every test, I check three things. The total never changes. No balance goes below zero. And every balance matches the ledger.

1:15

Think of an office. The database is one shared book of balances. Each worker, one request running the code, is a clerk with a notepad.

1:2601 · What you need

1:28

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

1:35

There are quick tests too. They check that my checker catches the bug you’re about to see. Those run without Docker.

1:43

No cloud, and no API keys.

1:4802 · The transfer, in code

1:49

Here’s the transfer.

1:52

Read both balances.

1:55

Check there’s enough.

1:58

Work out the new balances, in the app. Remember that one: the math happens outside the database.

2:05

Write them back, and add the line to the ledger.

2:1003 · One clerk, then 32

2:12

First, one clerk. Ten thousand random transfers.

2:17

Every check passed.

2:20

Now thirty-two clerks, the same ten thousand transfers.

2:25

Ten thousand answers: OK. But four hundred ninety-two balances were wrong. Off by fourteen thousand two hundred seventy-seven coins in all.

2:36

Some accounts gained coins from nowhere, others lost them. So the total was off by only seven hundred ninety-three. The ledger check showed the real damage.

2:4804 · How a transfer gets lost

2:49

Here’s how. One account holds a hundred coins. Two clerks take money out at the same moment.

2:56

Clerk A copies the balance to her notepad: a hundred.

3:01

Clerk B copies it too: a hundred.

3:05

A writes ninety. A hundred minus ten.

3:09

B writes eighty. A hundred minus twenty. A’s ten is gone.

3:15

The book says eighty. It should say seventy.

3:19

This is called a lost update. A race condition: right when clerks go one at a time, wrong when they overlap. I played it step by step on the real database.

3:31

With one clerk, it can never happen. That’s why a test with one worker never finds it.

3:3905 · Five fixes, measured

3:40

So how do you fix it? I measured five ways, with thirty-two clerks.

3:46

The broken code ran about seven thousand one hundred transfers a second.

3:52

First fix: one step. Tell the database: subtract ten, if there’s enough. The clerk walks to the book once, not twice.

4:01

Correct, and the fastest of all: eight thousand six hundred a second. Faster than the broken code, probably because it skips the read: one fewer trip to the database.

4:13

Second: put a hand on the page. In the database, each account is a row: one page of the book. Lock both rows first, so others wait. About seven thousand four hundred.

4:25

Third: give every page a version number that goes up on each write. Check it before writing, and retry if it changed. Six percent of transfers needed a retry.

4:37

Fourth and fifth: keep the same code, but ask the database for a stricter mode: repeatable read, or serializable. It refuses one of two clashing writes, and the app retries.

4:50

Both correct. Repeatable read: about six thousand eight hundred a second, six percent needed a retry. Serializable was the slowest: about five thousand eight hundred, thirteen percent needed a retry.

5:0506 · The last seat

5:07

Remember the thousand buyers? A hundred seats. A thousand buyers, sixty-four at a time.

5:14

The booking code checks for a free seat, then books it. Two steps.

5:19

Can you see what goes wrong?

5:24

Sixty-four buyers check at once. Many see the same free seat, and they all book it.

5:31

All thousand were told “booked”. But only seventy-four different seats were taken. Nine hundred twenty-six bookings landed on a seat someone already had.

5:43

Fix one: a rule in the database, one booking per seat. The second booking for a seat fails, and that buyer looks again. Correct, but buyers kept colliding: about three thousand eight hundred retries.

5:57

Fix two: one step. A counter that hands out the next seat number, if any are left. Exactly a hundred booked. No retries.

6:0807 · Two doctors

6:09

One more, and it’s the sneakiest. A hospital rule: at least one doctor stays on call.

6:16

Two doctors are on. Each doctor’s on-call status is her own page. Each may leave if someone else is still on call.

6:25

Both check at the same moment. Both see two. Both leave. Nobody is on call.

6:32

Five hundred shifts, both doctors trying at once. Four hundred seventy-eight shifts ended with nobody on call.

6:41

The stricter mode that stopped the lost update, repeatable read? Four hundred fifty-eight. Barely better. Each doctor changed only her own row, so nothing clashed.

6:53

This is called write skew: a rule that spans two rows.

6:58

Two fixes worked. Serializable also remembers what each doctor read, and refuses one of the two: four hundred forty-four retries. Or lock the rows you read, so the second doctor waits, then sees only one left. Zero empty shifts, no retries.

7:18Back to Lucía

7:19

So, three lessons.

7:22

Write down what must stay true, and test it with many clerks at once. One at a time, the bug never shows.

7:30

Let the database read and write in one step. Here it was correct, and the fastest.

7:37

And when a decision reads other rows, lock what you read, or use serializable and retry.

7:44

Next time: requests that wait for each other, forever.

7:49

For today: if it only works one at a time, it doesn’t work.Lucía: Test it with many at once.

7:54Summary

7:55

Test with many at once, do it in one step, and lock what you read.

Key takeaways

  • ✓A race condition is a bug that depends on timing: the code is right when requests run one after another and wrong when they overlap. The naive transfer passed 10,000 transfers with one worker. With 32 workers, every transfer answered OK and 492 of 1,000 accounts ended up wrong.
  • ✓The classic race is the lost update: two requests read the same balance, each works out a new one in the app, and the second write erases the first. Played step by step on Postgres: 100 − 10 − 20 ended at 80, not 70.
  • ✓Write down what must stay true (the invariants) and check it after a test with many workers at once. Check each balance against a ledger, not just the total: gains and losses cancel, so the total was off by only 793 coins while 14,277 were in the wrong place.
  • ✓All five fixes kept the balances right in 3 of 3 runs. The one-step atomic update was also the fastest, 8,626 transfers a second against 7,140 for the broken code. The row lock did 7,415, the version check 7,081 (6.2% of transfers retried), repeatable read 6,756 (6.1%) and serializable 5,755 (13.2%).
  • ✓Stricter isolation and version checks fix the race by refusing one of two clashing transactions. That's only a fix if the app retries, with the whole transaction read again.
  • ✓Check, then act is a race too. 1,000 buyers checked for a free seat and then booked it: all 1,000 were told “booked”, on only 74 different seats. A unique rule in the database fixed it with 3,799 retries; a one-step counter fixed it with none.
  • ✓Write skew breaks a rule that spans rows. Two doctors each saw two on call and both left: 478 of 500 shifts ended with nobody on call, and 458 under repeatable read. Serializable (444 retries) or locking the rows you read (no retries) left none.

A race condition is a bug that answers OK. Nothing crashes and nothing is logged; the data is just wrong afterwards. This chapter shows three of them on a real database: a bank transfer that with 32 workers left 492 of 1,000 balances wrong while every transfer said OK, a ticket service that told 1,000 buyers they got one of 100 seats, and a hospital rule that two doctors broke together. It measures five ways to fix the transfer, and shows how to write a test that can find these bugs at all.

The examples come from Lab 05 (Concurrency, Locks and Deadlocks) of the system design labs: script 01_lost_updates.py (the transfer, written six ways, under load), 03_isolation.py (isolation levels, played step by step, and the two doctors) and Exercise 1 of 04_hot_row.py (the last seat). The same lab's scripts 02_deadlocks.py and 05_pool_deadlock.py, on transactions and requests that wait for each other forever, are Chapter 9. Not covered here: the lab's runs where every transfer touches one "hot" account and with a 1 ms pause between read and write (the rest of script 01), how many bookings a second one row can take (script 04, Exercise 2; Chapter 5 has the rule behind it), and the Redis lock of script 06.

Everything runs on one laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs): Postgres 18.6 and the lab's small Python service in Docker, the test code on the same machine. The concurrency test harness is the lab's hammer.py: it runs one operation from N workers at once (N connections, each running one request after another), with random timing, and records each answer, its latency and any retries. The money is made-up coins.

A tiny bank, and three checks

The bank has 1,000 accounts with 1,000 coins each. A transfer moves coins from one account to another and adds a line to the ledger, a table with one row per transfer that happened. Replay the ledger from the starting balances and you should get every balance.

The transfer runs as a transaction: a group of database statements that succeed or fail together. Commit makes its changes final and visible to everyone else. Each account is one row in the accounts table. The obvious way to write the transfer, which the lab calls naive (in bank.py):

read both balances
check there's enough in the source account
work out the two new balances in the app
write both, add the line to the ledger, commit

The math happens in the app, outside the database. Remember that; it's the bug.

After every test the lab checks three invariants, statements that must be true whatever order things ran in:

  1. The total never changes. Transfers move coins; they don't make or destroy them.
  2. No balance goes below zero.
  3. Every balance matches the ledger: its start, plus what the ledger says came in, minus what went out.

Think of an office. The database is one shared book of balances. Each worker, one request running the code, is a clerk with a notepad: she copies a balance from the book, does the math on her notepad, and writes the result back. A row is a page of the book.

One clerk, then 32

Script 01 sends 10,000 random transfers between random pairs of accounts, first from one worker, then from 32 at once:

Every transfer answered Total Balances ≠ ledger Coins in the wrong place Transfers/s
1 worker OK, 10,000 times unchanged 0 0 738
32 workers OK, 10,000 times off by 793 492 of 1,000 14,277 6,417

One worker: perfect. That's the test most code gets, and continuous integration (CI), the tests that run on every change, would have said green. With 32 workers, the same code left almost half the balances wrong, and not one transfer reported a problem.

Try it · Every call said OKLab 05 · 01_lost_updates.py, Exercise 1 · the naive transfer
Transfers
10,000
Answered OK
10,000
Transfers a second
6,417

The three checks, after the run

  • ✗The total never changesoff by 793 coins
  • ✓No balance below zero0 accounts below zero
  • ✗Every balance matches the ledger492 of 1,000 accounts wrong

Coins that shouldn't be where they are

appeared
+6,742
vanished
−7,535
the total moved
−793

14,277 coins in the wrong place across 492 accounts, out of 1,000,000 in the bank. Most of it cancels in the total, which moved by only 793. In three more runs of the same setup the total was off by 48, 187 and 1,198 coins, while 466, 462 and 452 accounts disagreed with the ledger.

Appeared and vanished are the positive and negative gaps between each balance and what the ledger says it should be, summed over the accounts.

Check each balance, not just the total. Coins in the wrong place counts how far each balance is from what the ledger says it should be, added up over the accounts: 6,742 coins appeared from nowhere and 7,535 vanished. In the total they cancel, so the total was off by only 793, less than 0.1% of the million coins in the bank. In three more runs of the same setup (script 01's Exercise 2), the total was off by just 48, 187 and 1,198 coins, while 466, 462 and 452 accounts disagreed with the ledger. A check on the total alone would have looked almost fine.

Spreading the load doesn't save you. With 1,000 accounts, two transfers rarely pick the same one. But with 32 in flight, each transfer runs alongside 31 others touching about 60 accounts, and over 10,000 transfers that's plenty of collisions.

How a transfer gets lost

One account holds 100. Two clerks take money out at the same moment. Clerk A copies the balance to her notepad: 100. Clerk B copies it too: 100. A writes 100 − 10 = 90. B writes 100 − 20 = 80, and A's 10 is gone. The book says 80; it should say 70.

This is a lost update: two requests read the same value, each works out a new one, and the second write erases the first. It's the classic race condition, a bug that depends on timing: right when the clerks go one at a time, wrong when they overlap. With one clerk it can never happen, which is why a test with one worker never finds it.

Script 03 played exactly this on real Postgres, with two connections and the steps in this order, and recorded "balance 80, should be 70". Step through it below, then switch how the database runs it. The first three modes are the lab's recorded plays; the other three are the fixes from the next section, walked through from the lab's code (the lab measured them under load, but didn't play them step by step).

Try it · The office: two clerks, one bookLab 05 · 03_isolation.py and bank.py · step through it

How the database runs it

Clerk Anotepad—Clerk Bnotepad—the book: the databaseAccount 1100
1/5Account 1 holds 100. Clerk A will take out 10 and clerk B 20, at the same moment. Done right, the page ends at 70.

Played on real Postgres with two connections in this exact order (03_isolation.py, Exercise 1); the outcome is the recorded one. Under load (32 clerks, 10,000 transfers, 3 runs): broke the checks in 3 of 3 runs, 7,140 transfers a second.

Five fixes, measured

There are five standard fixes. Two need new code, one needs a version column, and two keep the naive code but ask the database to be stricter. Script 01 ran each with 32 workers, 10,000 transfers among the 1,000 accounts, three times each, interleaved (one run of each, then the next round), and checked the invariants after every run. The lab's name for each version is in brackets.

  1. One step (atomic update). Tell the database: subtract 10, if there's enough (UPDATE accounts SET balance = balance − 10 WHERE id = 1 AND balance >= 10). The database reads and writes the row in one step, so there's no copy on a notepad to go stale. The clerk walks to the book once, not twice.
  2. A hand on the page (pessimistic (FOR UPDATE)). Read both rows with SELECT … FOR UPDATE, which takes a row lock: until this transaction commits, any other transaction that wants to lock or change those rows waits. Pessimistic because it assumes a clash and blocks it up front.
  3. A version number (optimistic (version)). Each row carries a version that goes up by one on every write. Write only if the version is still the one you read (… WHERE id = 1 AND version = 7); if nothing was written, someone got there first, so start over. Optimistic because it assumes no clash and checks at the end.
  4. Repeatable read (naive + repeatable read) and 5. serializable (naive + serializable). The same naive code under a stricter isolation level, the setting that says how much a transaction sees of others running at the same time and which overlaps the database refuses. Postgres's default, read committed, lets each statement see whatever was committed when it started, and refuses nothing here. Under repeatable read, the whole transaction sees one snapshot of the data, taken at its first read, and the database refuses to let it write a row someone else changed after that snapshot. Serializable goes further: the outcome must be one that some one-at-a-time order could have produced, or a transaction fails. A refused transaction gets a serialization failure error, and the app must run it again.

Every version that can be refused runs inside the lab's retry loop (retrying() in hammer.py): it reruns the whole transaction, reading again, after a short random pause, so two transactions that clashed once don't clash again in lockstep.

Fix Balances right Transfers/s, median (range) p99 Transfers retried
None: the naive code, read committed ❌ wrong in 3 of 3 runs 7,140 (7,033–7,414) 12 ms 0
One step (atomic update) ✅ 8,626 (8,428–8,749) 8 ms 0
A hand on the page (FOR UPDATE) ✅ 7,415 (7,379–7,494) 10 ms 0
A version number ✅ 7,081 (6,020–7,169) 14 ms 6.2%
Repeatable read ✅ 6,756 (6,729–6,952) 14 ms 6.1%
Serializable ✅ 5,755 (5,503–6,027) 21 ms 13.2%

p99 is the time 99 transfers in 100 finished within (Chapter 1). "Transfers retried" is the share that needed at least one retry.

Try it · Five fixes, measuredLab 05 · 01_lost_updates.py, Exercise 2 · 32 clerks, 1,000 accounts, 3 runs each

atomic update. One step: subtract the amount if there's enough (balance = balance − amount WHERE balance ≥ amount).

Correct in 3 of 3 runs. 8,626 a second, 21% faster than the broken code; p99 8.4 ms; no retries.

Medians of 3 interleaved runs of 10,000 transfers each; the thin line is the range. p99: 99 transfers in 100 finished within this time. Only the low-contention runs (random pairs of 1,000 accounts) are shown; the lab also ran every fix on one hot account, which this chapter doesn't cover.

  • Every fix was correct, in every run. Only the naive code under the default isolation level broke the balances, and it did in all three runs.
  • The one-step update was correct and the fastest of all, 21% faster than the broken code, with the lowest p99. It also skips the read: two UPDATEs and the ledger line, against the naive code's SELECT, two UPDATEs and the ledger line. That one fewer trip to the database is the likely reason; the lab didn't test it separately.
  • The fixes that refuse cost retries. The version check and repeatable read each retried about 6% of transfers. Serializable retried 13.2%, twice as often, because it also refuses transactions whose reads were changed under them, not just clashing writes. It was the slowest, about 19% below the broken code. Every refusal is an error your code must catch and retry.
  • The row lock never retried, because a clash makes the second transfer wait instead of fail. At this low contention (how often two requests want the same row at once) the waits were short, and it ran slightly faster than the broken code.

The last seat

The same bug hides in check, then act: look whether something is free, then take it. Script 04 sends 1,000 buyers for 100 numbered seats through the lab's booking service (booking.py, behind POST /events/{id}/book), 64 buyers at a time. The naive booking finds the lowest free seat, then inserts a booking for it. Two steps.

Sixty-four buyers check at once, many see the same free seat, and they all book it:

How it books Told "booked" Bookings stored Different seats Bookings on a taken seat Retries Seconds
Check, then book 1,000 1,000 74 926 0 0.52
One booking per seat (a unique rule) 100 100 100 0 3,799 1.16
One step (a counter) 100 100 100 0 0 0.45
Try it · The last seatLab 05 · 04_hot_row.py, Exercise 1 · 1,000 buyers, 100 seats, 64 at a time

Find the lowest free seat, then insert a booking for it: two steps.

Told “booked”
1,000
Different seats
74
On a taken seat
926
Retries
0

All 1,000 buyers were told "booked", but only 74 different seats were taken: 926 bookings landed on a seat someone already had, and seats 75–100 were never sold. (The code always books the lowest free seat, so the taken ones are 1–74.)

  • All 1,000 buyers were told they had a seat. 900 more bookings than seats, all on seats 1–74, and seats 75–100 were never sold.
  • A unique rule makes the database the referee. A unique constraint, UNIQUE (event_id, seat_no), means the database refuses a second booking for the same seat; that buyer looks again. Correct, but 64 buyers kept looking for the same lowest free seat and only one won each round: 3,799 retries, and the slowest of the three.
  • One step needs no retries. The counter version keeps a "sold" count on the event row and runs UPDATE events SET sold = sold + 1 WHERE id = 1 AND sold < capacity RETURNING sold: the database hands out the next seat number, if any are left, in one statement. Exactly 100 booked, no retries, the fastest run. Its cost shows up only at much higher rates: every booking waits for that one row's lock (the "hot row" of Chapter 5).

Two doctors, one rule

The sneakiest one. A hospital rule: at least one doctor stays on call. Two doctors are on call, and each doctor's on-call status is her own row. Each may leave if someone else is still on call. Both check at the same moment, both see two, both leave. Nobody is on call.

Switch the office widget above to "Two doctors, one rule" to step through it. Script 03 played each of three problems with two connections, in a fixed order, under each isolation level (the plays are exact, so the results are the same on every run):

Problem Read committed Repeatable read Serializable
Lost update ❌ balance 80, should be 70 ✅ B's write refused, B must retry ✅ B's write refused
Non-repeatable read ❌ read 100, then 50 ✅ 100 both times ✅ 100 both times
Write skew (the doctors) ❌ 0 doctors on call ❌ 0 doctors on call ✅ B's commit refused, B must retry

A non-repeatable read is reading the same row twice in one transaction and getting two answers, because someone else committed a change in between. Write skew is the doctors: two transactions each check a rule that spans several rows, each writes a different row, and together they break the rule.

Then 500 shifts, two doctors each, both trying to go off call at once with random timing:

How it runs Shifts left with nobody on call Retries
Read committed 478 of 500 0
Repeatable read 458 of 500 0
Serializable, with retries 0 444
Read committed, counting with SELECT … FOR UPDATE 0 0
  • Repeatable read, which stopped the lost update, barely helped. It refuses a write to a row someone else changed. Each doctor changed only her own row, so nothing clashed, and nothing was reported either.
  • Serializable fixes it by remembering what each transaction read. Doctor B's count read doctor A's row, which A then changed, so one of them is refused and retried: 444 retries for 500 shifts.
  • Or lock what you read. Counting with FOR UPDATE locks the rows the decision is based on. The second doctor waits, then counts again and sees only one left. No empty shifts and no retries, under the default isolation level.

How to test for a race

Every result above came from the same method, and it's the main thing to take from this chapter:

  1. Write the invariants down as code. The total is unchanged, each balance matches the ledger, no seat is sold twice, someone is on call.
  2. Run the code from many workers at once, with random timing, as many operations as you can afford.
  3. Check the invariants after every run. The answers won't tell you: they all said OK.
  4. Prove the test can fail. Run it against the naive code first; it must find the bug. The lab's own tests check its harness this way, in memory with no database: the naive transfer must break the checks with 8 workers, must pass them with 1, and must pass them with 8 workers once a lock is added (test_harness_finds_the_race_in_naive_code, test_one_worker_never_finds_it and test_a_lock_removes_the_race in the lab's tests/test_hammer.py). All 376 of the lab's tests pass in about 2 seconds.
  5. Repeat runs. A race lives in a timing window; a run that doesn't reach into it shows nothing.

Which fix to pick

  • If the logic fits in one statement, do it in one statement. The one-step update and the counter were correct, never retried, and the fastest here.
  • If the app must decide between the read and the write, lock the rows you read (SELECT … FOR UPDATE): no retries, little waiting at low contention.
  • If you can't hold a lock across the gap (a user editing a form for a minute), use a version number, and expect retries when clashes are common.
  • Stricter isolation fixes existing code without rewriting it, at the cost of retries. Serializable is the one that also catches write skew.
  • Let the database enforce rules it can: a unique constraint for "one booking per seat".
  • Every fix that refuses needs a retry loop that reruns the whole transaction, reads included, with a random pause and a cap.

Caveats

  • One laptop, busy with other work. Other jobs kept the laptop's load average (the number of processes wanting a core) between 8 and 22 when these results were written; each result file records it. The fixes ran three times each, interleaved, so they faced the same conditions; the other tables are single runs. Read the order and the size of the gaps, not the last digit.
  • How often a race shows depends on how much requests overlap. With a slower load-generating client (an early version of the lab used a slower HTTP library), the same naive booking sold 167 tickets for the 100 seats, not 1,000. A race that looks rare in a test can be common in production, and the other way round.
  • Low contention only. Here transfers picked random pairs among 1,000 accounts. The lab also ran every fix with all transfers touching one account, where locks and retries cost far more; that part isn't covered here.
  • Small transactions. Each transfer is a few statements with nothing slow inside. A transaction that also calls another service holds its locks longer, and retrying it may repeat that call.
  • The plays are exact; the load runs aren't. The step-by-step results in script 03 come out the same every time. The counts under load (492 accounts, 478 shifts, 3,799 retries) change from run to run.

The checklist

  1. Write down the invariants for anything concurrent requests change: totals, balances against a ledger, "at most one", "at least one".
  2. Test with many workers at once and check the invariants after the run. One worker proves nothing about races.
  3. Make sure the test can fail: run it against the naive version first.
  4. Check each item, not just the total. Errors that cancel in a sum are still errors.
  5. Do read-modify-write in one statement when the logic fits, and let constraints enforce what they can.
  6. When a decision reads other rows, lock what you read or use serializable.
  7. Retry refused transactions from the start, with a random pause and a cap, and count the retries.
  8. Repeat the runs. A race that shows up once in three runs is still a race.

Practice: catch the race

Write the lab's checks and replay the races: the bank's three invariants against a ledger, how many coins appeared and vanished, the booking checks, and two clerks and two doctors played in the same fixed order as script 03, with each fix. The plays are a model of the order of steps, not the database. The tests use the recorded numbers: 14,277 coins misplaced as 6,742 appeared and 7,535 vanished, 80 instead of 70, 74 different seats for 1,000 bookings, 0 doctors on call, and the fixes' speed against the broken code.

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

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.The naive transfer passed a test with one worker 10,000 times out of 10,000. With 32 workers every transfer answered OK, yet 492 balances were wrong. Why did the one-worker test pass?

  2. 2.After the 32-worker run the bank's total was off by 793 coins. How much money was actually in the wrong place?

  3. 3.Which fix was correct and the fastest at low contention, faster even than the broken code?

  4. 4.You switch the naive transfer to repeatable read and the balances come out right. What must the app now do?

  5. 5.1,000 buyers, 100 seats. The booking code checks for the lowest free seat, then books it. All 1,000 were told “booked”. How many different seats were taken?

  6. 6.Two doctors are on call; each may leave if someone else is still on call. Repeatable read stopped the lost update. Why didn't it stop both doctors leaving?

Check your understanding

Try each question before opening its answer.

Two withdrawals from one account run at the same moment and money disappears, yet every test passed. What happened?

A lost update. Both requests read the same balance, both worked out a new one in the app, and the second write erased the first. Both committed and both answered OK. The tests ran one request at a time, and one at a time the code is correct: in the lab, the naive transfer passed 10,000 transfers with one worker and left 492 of 1,000 balances wrong with 32.

Why isn't "the total is unchanged" a good enough check?

A lost update creates coins in one account and destroys them in another, and in a total those cancel. In the 32-worker run 6,742 coins appeared and 7,535 vanished, but the total moved by only 793; in another run, by 48. Checking each balance against the ledger found 492 wrong accounts.

Name the five fixes for the transfer. Which was fastest, and which needed retries?

The one-step update (subtract in the database, only if there's enough), a row lock with SELECT … FOR UPDATE, a version check, and the naive code under repeatable read or serializable. All were correct in 3 of 3 runs. The one-step update was fastest (8,626 a second against 7,140 for the broken code). The version check (6.2% of transfers), repeatable read (6.1%) and serializable (13.2%) needed retries; the one-step update and the row lock didn't.

"We'll just switch to serializable." What else has to be true?

The app must catch the refusal and rerun the whole transaction, reading again, not just the failed statement, with a random pause so the two don't clash again, and a cap on retries. Nothing outside the database (an email, a payment call) should have happened inside the transaction, or the retry repeats it. And expect a cost: serializable retried 13.2% of transfers and ran about 19% slower than the naive code.

A ticket service checks for a free seat, then books it. How does it oversell, and what are two fixes?

Buyers who check at the same moment all see the same free seat and all book it: 1,000 buyers were told "booked" on only 74 different seats. A unique constraint, one booking per seat, makes the second booking fail so that buyer looks again (correct, 3,799 retries). Or a one-step counter, UPDATE … SET sold = sold + 1 WHERE sold < capacity, hands out the next seat number with no retries.

What is write skew, and why doesn't repeatable read stop it?

Two transactions each check a rule that spans several rows, then each changes a different row, and together they break the rule: two doctors each see two on call and both leave. Repeatable read only refuses two writes to the same row, and here each doctor changed only her own, so 458 of 500 shifts still ended empty. Serializable, which tracks reads too, refused one doctor each time (444 retries); counting with SELECT … FOR UPDATE made the second doctor wait and see one left (no retries).

How would you test that a concurrency fix works?

Write the invariants as code, run the code from many workers at once with random timing, and check the invariants after every run. First run the same test against the naive version and make sure it fails; a test that can't find the bug proves nothing. Then repeat the runs, because a race only shows when the timing lands in its window.

Next up: Chapter 9, deadlocks and pools: the row locks that fixed the races here can wait for each other forever. The next chapter plays a deadlock exactly, measures what one costs under load, and finds a service that hangs with no error because each request waits for a connection that another request holds.

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.