Key takeaways
- ✓A timeout doesn't tell the client whether the work happened. With 30% of answers made slow on purpose and a 150 ms client timeout, 1,000 payments retried until answered made 466 extra charges from 466 timeouts when the charge was saved before the slow answer, and 382 from 389 timeouts when the payment was still in progress.
- ✓An idempotency key is an id the client makes once per intent (one click on Pay) and sends with every attempt. The service saves it in the same database transaction as the payment, with the answer, and sends the saved answer back to any retry. Result: 1,000 charges for 1,000 payments, in both cases.
- ✓The key handles the hard cases too: 200 pairs of identical requests sent at the same moment gave one charge per pair, and the same key with a different amount was refused (HTTP 422) 50 times out of 50. It cost 0.14 ms at the median (0.75 → 0.89 ms).
- ✓A key doesn't make waiting shorter. When the first attempt is still running, a retry waits for it and can time out again: 649 timeouts with the key against 389 without, but no extra charges.
- ✓In a chain where each service waits up to 2 s for the next while the client gives up at 300 ms, the services behind keep working for nobody. At 10 checkouts a second that was 61% of the last service's work, and harmless. At 40 a second the slow requests needed all 4 of its workers: 25 of 1,084 normal checkouts (2%) were answered in time, and 99% of its work was for clients that had left.
- ✓Deadline propagation passes the time left to each service (here the x-timeout-ms header), which refuses late work and stops when the deadline passes. At the same 40 a second: 1,084 of 1,084 normal checkouts in time, about half the work, almost none of it after the client left.
- ✓Retries and timeouts are design decisions, not library defaults: generate the key once per user action, save it with the side effect, give every call a deadline and pass it on.
When a call to another service takes too long, the caller gives up and usually tries again. This chapter measures what happens next. A payment service saved 466 extra charges for 1,000 payments, one for every timeout, though nothing crashed. A checkout built from three services answered 2% of its normal requests in time at 40 a second, while its slowest service spent 99% of its time on requests whose caller had already left. Both problems start with a client giving up, and both have a fix that the lab measures: an idempotency key for the payment, and a deadline passed along the chain.
The examples come from Lab 06 (APIs and Service Communication) of the system design labs, scripts 03_idempotency.py (retrying a payment after a timeout, with and without a key) and 04_deadlines.py (a chain of three services, with and without deadline propagation), with the lab's modules idempotency.py and deadline.py. The same lab's pagination and schema-change scripts (02_pagination.py and 06_contracts.py) are the next topic; 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) and Postgres 18.6 in Docker, with the client on the same machine. No real money moves: a "payment" is a row saved in a payments table. The lab's 390 unit tests (its request fingerprint, deadline arithmetic and the rest of its building blocks) run in a few seconds without Docker; they all pass. Other work kept the laptop busy (its load average, the number of processes wanting a core, was about 13 during the payment runs and 41 during the chain runs), so read the shapes, not the last digit.
A timeout isn't a no
Think of a burger counter. The app is a customer, a request is an order slip handed over the counter, a timeout is the customer giving up on waiting, and a retry is ordering again. The question is what happened to the first slip.
The lab's service saves payments in Postgres. It makes 30% of its answers slow on purpose: 400 ms. The client gives up after 150 ms, waits 10–30 ms, and sends the same payment again, until it gets an answer. A slow answer can happen at two points:
- Slow after saving (the lab calls it after commit): the payment is saved, then the answer is slow. The work is done; the client just never hears about it.
- Slow before saving (before commit): the payment is still in progress when the client gives up, and is saved later. A transaction is a group of database changes saved together or not at all; commit is the moment they're saved.
To the client, both look the same: no answer in 150 ms. It can't know whether it paid.
One payment whose first answer is slow · illustration, not a recorded trace
- The first slip is saved, then the answer is slow. The app gives up at 150 ms and doesn't know the payment went through.
- The retry looks like a new payment to the service, so it charges again.
The recorded run: 1,000 payments, each retried until answered
466 timeouts, 466 extra charges: every timeout became a charge. 1,466 charges stored for 1,000 payments.
The timeline is drawn from the lab's settings, not recorded: the app gives up after 150 ms, a slow answer takes 400 ms, and the app pauses 20 ms before a retry (the lab pauses 10–30 ms at random). Only the first answer is slow in the picture. The counts are the recorded runs (one run per row, 16 payments in flight at a time). #A17 stands for the order number; the lab uses a random 32-character id.
Every timeout, a charge
1,000 payments, 16 in flight at a time, each retried until answered, without any key:
| Slow answer | Attempts | Timeouts | Charges saved | Extra charges |
|---|---|---|---|---|
| after saving | 1,466 | 466 | 1,466 | 466 |
| before saving | 1,389 | 389 | 1,382 | 382 |
Every timeout became a charge. When the answer was slow after saving, 466 timeouts gave exactly 466 extra charges: each retry looked like a new payment, and the service did its job each time. (An extra charge is one beyond the one payment the customer meant; a payment that timed out twice was charged three times.) When the payment was still in progress, 382 of the 389 timeouts became charges: the first attempt finished and saved, and so did the retry. The lab didn't trace where the other 7 attempts stopped, so read that as what happened in this run, not a rule.
Retrying wasn't the bug. The client had to retry: it couldn't tell a lost answer from a lost request. The bug is that the service couldn't tell a retry from a new payment.
An order number: the idempotency key
The fix is to write an order number on the slip. An operation is idempotent when doing it twice has the same effect as doing it once. An idempotency key makes a payment idempotent: a random id the client makes once per intent, when the person clicks Pay, and sends with every attempt (here in an HTTP header called Idempotency-Key). The service then does the work once per key and sends the saved answer to every retry.
The lab's idempotency.py does it in one transaction, on a table idempotency_keys with the key as its primary key (shortened):
async with conn.transaction():
inserted = await conn.fetchval(
"INSERT INTO idempotency_keys (key, request_hash) VALUES ($1, $2) "
"ON CONFLICT (key) DO NOTHING RETURNING true", key, req_hash)
if not inserted: # the key is already there
row = await conn.fetchrow("SELECT request_hash, status_code, response ...")
if row["request_hash"] != req_hash:
return 422, {"error": "Idempotency-Key reused with a different request"}, False
return row["status_code"], json.loads(row["response"]), True # replay
body = await handler(conn) # the payment itself
await conn.execute("UPDATE idempotency_keys SET status_code = 200, response = $2 ...")
Three outcomes:
- The key isn't there: save it, make the payment, save the answer next to the key. All in one transaction, so the key and the payment are saved together or not at all. A crash can't leave a payment without its key, or a key without its payment.
- The key is there, for the same request: this is a retry. Send back the saved answer, and don't charge.
- The key is there, for a different request: refuse it.
req_hashis a fingerprint (a SHA-256 hash) of the method, path and body, so the same key with a different amount doesn't match. That's a bug in the client, and replaying the old answer would tell it a payment went through that didn't. The lab answers with HTTP 422 (Unprocessable Content: the request is well-formed but can't be processed).
ON CONFLICT (key) DO NOTHING is Postgres for "insert this row unless one with the same key exists". If another transaction has inserted that key but not committed yet, the insert waits until it does. That's what handles a retry that arrives while the first attempt is still running, with no extra lock or "in progress" flag.
Who makes the key matters. A key made on each attempt is useless: every retry looks new. A key made by the server never reaches the client if the first answer is lost, so the client can't send it again. And keys don't need to live forever: longer than any client keeps retrying (the lab's README suggests 24 hours is common), expired by the table's created_at column.
Charged once
The same 1,000 payments, with a key:
| Slow answer | Key | Attempts | Timeouts | Charges saved | Extra charges | Answered from the saved copy |
|---|---|---|---|---|---|---|
| after saving | none | 1,466 | 466 | 1,466 | 466 | 0 |
| after saving | yes | 1,419 | 419 | 1,000 | 0 | 300 |
| before saving | none | 1,389 | 389 | 1,382 | 382 | 0 |
| before saving | yes | 1,649 | 649 | 1,000 | 0 | 312 |
1,000 charges for 1,000 payments, in both cases. When the answer was slow after saving, 300 payments got their saved answer back on a retry. There are more timeouts than that (419) because a saved answer can be slow too: the lab's slowdown applies to every answer, replays included.
When the first attempt is still running, the key costs time. The retry finds the key taken by an unfinished transaction and waits for it, and the client gives up on that wait as well: 649 timeouts against 389 without a key, about two for each of the 312 payments answered from the saved copy. No extra charges, but the client waited longer. That's the trade: the key makes a retry safe, not fast.
The lab also tried the cases that break naive versions:
- Two copies at the same moment (a double click, or a proxy retrying while the client retries): 200 pairs of identical requests with the same key, sent together. One charge per pair, and both copies of each pair got the same payment back. The second copy's insert waited on the first one's key, then replayed it. That's a race condition, two requests acting on the same thing at once, settled by the database's unique key rather than by code that checks first and inserts after (Chapter 8 covers race conditions).
- The same key with a different amount: refused with 422, 50 times out of 50.
- The cost when nothing goes wrong (1,000 payments each way, one at a time): median 0.75 → 0.89 ms, p99 2.12 → 3.09 ms. One more indexed insert and one update, inside a transaction that commits anyway.
One limit: this works because the payment is a row in the same database as the key. If the charge happens at another company (a card network), it can't join your transaction. Then you need to record a "started" state before calling out, send them a key too (many payment providers accept one for this reason), and run a recovery job for payments stuck in "started".
A chain of services
The second problem. A checkout goes through three services in a chain: a gateway takes the request, an orders service builds it, and an inventory service does the slow part. In the restaurant: the waiter, the kitchen, and the grill. The grill has 4 cooks: inventory runs at most 4 requests at a time, and the rest wait for a free one.
- 90% of checkouts need 20 ms of inventory work. 10% hit a slow path that needs 1,000 ms, so they can never be ready in time.
- The client waits 300 ms.
- Without propagation, each service waits up to 2 s for the next, a common library default. When the client gives up, nobody behind it knows.
- Checkouts arrive open-loop (as in Chapter 2: each one is sent on schedule whether or not earlier ones have answered, like real users), at random times averaging 10 or 40 a second (a Poisson process), for 30 s per run.
The lab's service counts the work inventory does after the moment the client gave up: work for nobody.
Work for nobody
| Checkouts a second | Deadline passed along | Normal checkouts answered in time | Client gave up | 504s from the chain | Inventory work | After the client left |
|---|---|---|---|---|---|---|
| 10 | no | 288 of 288 (100%) | 24 | 0 | 29.8 s | 18.1 s (61%) |
| 10 | yes | 286 of 288 (99%) | 12 | 14 | 11.3 s | 0.2 s (2%) |
| 40 | no | 25 of 1,084 (2%) | 1,175 | 0 | 103.3 s | 102.0 s (99%) |
| 40 | yes | 1,084 of 1,084 (100%) | 16 | 100 | 50.1 s | 0.1 s (0%) |
"Inventory work" is added up over the 4 workers. A 504 (Gateway Timeout) is the HTTP status a service returns when the one behind it didn't answer in time.
At 10 a second, wasted work is just waste. Every normal checkout was answered in time (median 30 ms), yet 61% of inventory's work came after its client had left. That's mostly the 24 slow checkouts: the client leaves at 300 ms, and the grill keeps cooking for a full second. There were spare cooks, so nobody noticed.
At 40 a second, it's an outage. 25 of 1,084 normal checkouts were answered in time, and 99% of the work was for nobody. The arithmetic is the utilization from Chapter 4, how busy the workers are on average:
slow: 40 × 10% × 1 s = 4.0 worker-seconds every second
quick: 40 × 90% × 20 ms = 0.72 worker-seconds every second
total: 4.72 ÷ 4 workers = 118% busy
On average, the slow checkouts alone fill all 4 cooks. The quick ones need a little on top, so a line forms and never clears; the normal checkouts wait in it until their clients give up too. (The run had 116 slow checkouts in 30 s, 3.9 a second, close to the average of 4.)
One average second at the grill · modelled from the lab's setup, not a trace
4 slow × 1 s + 36 quick × 20 ms = 4.72 cook-seconds a second, for 4 cooks: 118% busy. More than the grill has: a line forms and never clears.
The recorded run: 30 s, open-loop arrivals
scale: 0–110 s · capacity in 30 s: 120 cook-seconds · busy 86%
25 of 1,084 normal checkouts answered in time (2%). The slow ones held the cooks for a full second each, the normal ones queued behind them, and their customers gave up too. When the counters were read, 3 s after the last arrival, inventory had finished only 913 of its 1,200 requests: the 103 s is what it had done by then, not the whole bill.
The grill is the lab's own arithmetic for an average second: 40 × 10% = 4 slow checkouts and 36 quick ones. Real arrivals are random (Poisson), so some seconds bring more slow ones and some fewer; in this run 116 of 1,200 checkouts were slow. With the deadline, the slow ones' 0.25 s is their average cooking time in the run: (inventory work − normal checkouts × 20 ms) ÷ slow checkouts. 504 Gateway Timeout is the HTTP status for "a service behind me didn't answer in time". One run per row, on a busy laptop (load average 41).
Pass the deadline along
The fix is to write the customer's deadline on the slip and pass it along. Deadline propagation: the client says how long it will wait, and each service passes on what's left. In the lab the header is x-timeout-ms (gRPC has the same thing built in, as grpc-timeout). Each service, in deadline.py and service/chain.py:
- turns the time it receives into a deadline on its own clock when the request arrives;
- gives the next service the time left minus a margin of 5 ms for its own work and the reply;
- refuses a request whose deadline has already passed, including one that waited too long for a free worker;
- and stops a long task when the deadline passes (inventory checks it every 10 ms of work).
The time passed along is relative ("285 ms left"), not a clock time ("until 14:59:02.300"): the services' clocks don't agree exactly.
At the same 40 checkouts a second: 1,084 of 1,084 normal checkouts answered in time (median 28 ms). Inventory did 50 s of work instead of 103, and almost none of it after a client had left. The slow checkouts still failed, as they had to: 1 s of work can't fit in 300 ms. But inventory stopped each one at the deadline, after about a quarter of a second on average, and its worker was free for the next checkout. For 100 of the 116, the chain answered with a 504 at the deadline instead of leaving the client to time out; the other 16 timed out on the client.
At 10 a second, propagation cut the work from 29.8 s to 11.3 s. Two normal checkouts and some slow ones still timed out on the client: on a laptop with a load average of 41, the 5 ms margin per hop wasn't always enough.
Caveats
- One run per row, on a busy laptop. The load average was about 13 during the payment runs and 41 during the chain runs. The lab repeated the chain run once and got the same 2% against 100% at 40 a second, but the smaller numbers (12 client timeouts, 0.2 s after the deadline) are the kind that move between runs.
- The 103 s at 40 a second is not the whole bill. The counters were read 3 s after the last checkout arrived. Inventory had finished 913 of its 1,200 requests by then, and was still working through the backlog. Had it cooked every request in full, the lab's arithmetic gives about 138 s (116 × 1 s + 1,084 × 20 ms), so "half the work" with the deadline understates the saving.
- The timelines in the first widget and the grill in the second are drawn, not traced. The first is the lab's settings applied to one payment; the second is the average-second arithmetic above. The tables are the measurements.
- The key only covers your own database. A side effect outside it (a card network, an email) needs a "started" state, a key on the outside call and a recovery job.
- 7 of the 389 timed-out attempts without a key left no extra charge, and the lab didn't trace why. Don't read "382 of 389" as a property of retries.
- The margin is a guess. 5 ms per hop was usually, not always, enough here. Real services measure how long their own work after the call takes.
The checklist
- Assume a timeout means "unknown". The work may be done, in progress, or never started.
- Give every call that changes something an idempotency key, made once per user action (one click), sent on every retry.
- Save the key in the same transaction as the side effect, with the answer, and send the saved answer back to retries.
- Compare the request, not just the key. Same key, different body: refuse it.
- Test the races: two identical requests at once, and a retry that arrives while the first is still running. Expect one charge, and expect the waiting retry to be slower.
- Give every network call a timeout, and pass the caller's deadline along as time left, minus a margin, so every service can refuse late work and stop when nobody is waiting.
- Count the work done after the caller gave up. If it's large, slow requests can take down fast ones once the workers fill up.
Practice: safe retries and deadlines
Write the lab's logic: count extra charges, the request fingerprint (request_hash, checked against hashes from the lab's own code), a handler that saves a key and replays or refuses, the time each service in a chain receives, and how busy the grill gets with and without a deadline. The tests use the recorded runs: 466 and 382 extra charges, 118% busy at 40 a second, 61% and 99% of the work for nobody, and about 0.245 s of work per slow checkout once it's cut off.
Quiz
1.A client's payment request times out after 150 ms. What does the client know about the payment?
2.Where should a payment service save the idempotency key?
3.When should the client generate the idempotency key?
4.A retry arrives with a key that is already saved, but the amount is different. What should the service do?
5.A client waits 300 ms; the three services behind it each wait up to 2 s for the next. 10% of requests need 1 s of work on the last service, which has 4 workers. At 40 requests a second, what happens?
6.What does deadline propagation change in that chain?
Check your understanding
Try each question before opening its answer.
Why did every timeout turn into an extra charge, when the service had no bug?
The client couldn't tell a lost answer from a lost request, so it retried, and the service couldn't tell a retry from a new payment, so it charged again. When the answer was slow after the charge was saved, 466 timeouts gave exactly 466 extra charges; when the payment was still in progress, 382 of 389 did.
Why must the idempotency key be saved in the same transaction as the payment?
So they're saved together or not at all: a crash can't leave a payment without its key (the retry would charge again) or a key without its payment (the retry would be told "done" for nothing). It also makes a retry that arrives during the first attempt wait on the key until the first one commits, then send back its answer, with no extra locking.
With a key, the case where the payment was still in progress had 649 timeouts instead of 389. Did the key make things worse?
No extra charges, so no. But the retry found the key taken by an unfinished payment and waited for it, and the client gave up on that wait too: about two timeouts for each of the 312 payments answered from the saved copy. The key makes a retry safe, not fast.
Two identical requests with the same key arrive at the same moment. What happens in the lab's design?
Both try to insert the key. One succeeds and charges; the other's insert waits until that transaction commits, finds the key, and sends back the saved answer. In the lab, 200 such pairs gave one charge each, and both copies got the same payment back.
A client waits 300 ms, but each service behind it waits up to 2 s. Why can that be harmless at one load and an outage at another?
The services keep working after the client has left. At 10 a second, 61% of the last service's work was for nobody, but it had spare workers and every normal request was answered. At 40 a second the slow requests alone needed about 4 worker-seconds every second, all 4 workers, so normal requests queued behind them and timed out: 2% answered in time.
What does each service do with a propagated deadline, and why pass time left rather than a clock time?
It passes on the time left minus a margin (5 ms here), refuses requests that arrive or wait past the deadline, and stops long work when it passes. Relative time doesn't depend on the services' clocks agreeing. At 40 a second this took normal requests from 2% to 100% answered in time, with half the work.
Your service charges cards through an outside payment provider. Is an idempotency key in your own database enough?
No. The provider's charge can't join your database transaction, so a crash between the two can still lose track of it. Record a "started" state before calling, send the provider a key of its own so its side is safe to retry, and run a recovery job for payments stuck in "started".
Next up: Chapter 11, pagination and breaking schema changes. API bugs that don't make a sound: offset pagination that skips rows while the data changes, and a schema change that leaves old clients reading a total of 0 without an error.