ealeng

Episode 10 of 55 · APIs

Retries, idempotency keys and deadlines

1,000 payments, a 150 ms client timeout and some slow answers: 466 extra charges, one for every timeout. In a chain of three services at 40 checkouts a second, 2% of normal checkouts were answered in time while 99% of the last service's work was for customers who had already left. What happens after a timeout, and the two fixes: an idempotency key saved with the payment, and a deadline passed from service to service.

Lab 06 · APIs and Service Communication16 min read
Video transcript8:04

0:00Cold open

0:01

My payment service made four hundred sixty-six extra charges. Out of a thousand payments.

0:09

Nothing crashed. The app just tried again, after an answer came too slowly.

0:15

And a second system, a checkout made of three services, broke at forty checkouts a second. Only two percent of its quick, normal checkouts came back in time.

0:27

Its busiest service spent ninety-nine percent of its cooking time on customers who had already left.

0:35

Both start the same way: a client gives up. What then?

0:41Intro

0:42

Hands-on system design, part ten.

0:45

Today: what happens after a timeout, and how to make retries safe.

0:51Meet Lucía

0:53

I’m Lucía, a platform engineer.

0:56

This is a real running service that saves payments in a real database. No real money moves. A payment saves a charge, then answers.

1:06

I made thirty percent of the answers slow on purpose: four hundred milliseconds. And the app gives up after a hundred and fifty, then sends the same payment again.

1:17

Think of a burger counter. The app is a customer. A request is an order slip. A timeout is the customer giving up. And a retry is ordering again.

1:2901 · What you need

1:31

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

1:38

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

1:43

No cloud, and no API keys.

1:4802 · Every timeout, a charge

1:50

A thousand payments. Each one is retried until it gets an answer.

1:55

Case A: the charge is saved, then the answer is slow.

2:00

Four hundred sixty-six timeouts. And four hundred sixty-six extra charges. Every timeout became a charge.

2:09

Case B: the server is slow, then saves.

2:13

Three hundred eighty-two extra charges, from three hundred eighty-nine timeouts. Almost every timeout.

2:2303 · Why

2:24

Here’s case A. The app pays, and waits.

2:28

The server saves the charge. But its answer is slow, so the app gives up.

2:35

The app pays again. The server can’t tell it’s the same payment, so it charges again.

2:42

In case B, the first payment is still in progress when the retry arrives. Both get saved.

2:49

To the app, both cases look the same: a timeout. It can’t know whether it paid.

2:5704 · An order number

2:58

The fix: the app writes an order number on the slip. The number is made once, when the person clicks Pay. The app then sends that same number on every retry.

3:10

The server tries to save the number.

3:13

If it’s already there with a different amount, refuse it with an error. That’s a bug in the app, reusing a number.

3:21

If it’s there with the same payment, this is a retry. Send back the saved answer.

3:27

Otherwise, do the payment, and save its answer next to the number, in one step with the charge. That one step is called a transaction: either both are saved, or neither.

3:39

That order number is called an idempotency key.

3:4405 · Charged once

3:46

Same thousand payments, now with order numbers.

3:50

A thousand charges. Zero charged twice, in both cases.

3:56

In case A, three hundred retries got the saved answer back.

4:02

Here the fix costs time. In case B, the retry finds the number taken by a payment that isn’t finished yet, and waits for it. The app gives up on that wait too: six hundred forty-nine timeouts, instead of three hundred eighty-nine. But no extra charges.

4:20

Sometimes a double click sends two copies at the same moment. I tried that two hundred times: each pair charged once.

4:29

The same number with a different amount: refused, fifty times out of fifty.

4:35

And the cost when nothing goes wrong: the typical payment got a hair slower, from zero point seven five to zero point eight nine milliseconds.

4:4706 · A chain of services

4:48

Second problem. A checkout goes through three services. A gateway takes the request, an orders service builds it, and an inventory service does the slow part.

5:00

In the restaurant: the waiter, the kitchen, and the grill. The grill has four cooks.

5:06

Most checkouts need twenty milliseconds on the grill. One in ten needs a full second.

5:13

The customer waits three hundred milliseconds. So those slow checkouts can never be ready in time.

5:21

And each service waits up to two seconds for the next, whether the customer is still there or not.

5:2907 · Work for nobody

5:30

At ten checkouts a second, every normal checkout was answered in time.

5:36

But sixty-one percent of the grill’s work was for customers who had already left. That’s mostly the slow checkouts: their customer leaves at three hundred milliseconds, but the grill keeps cooking for a full second.

5:50

Now forty checkouts a second. What do you think happens?

5:57

In thirty seconds there were a thousand and eighty-four normal checkouts. Twenty-five were answered in time. Two percent.

6:06

And ninety-nine percent of the grill’s work was for nobody.

6:11

Here’s why. On average, one in ten of forty is four slow checkouts a second. Each holds a cook for a second. That’s about all four cooks, and the quick checkouts need a little on top.

6:24

The normal checkouts wait behind them, and their customers give up too.

6:3108 · Pass the deadline along

6:32

The fix: write the customer’s deadline on the slip, and pass it along.

6:38

Each service passes on the time that’s left, and the grill stops cooking when the deadline passes.

6:45

Same forty checkouts a second: every normal checkout answered in time. A thousand eighty-four out of a thousand eighty-four.

6:56

Added up across the four cooks: fifty seconds of cooking instead of a hundred and three. Half. And almost none of it for nobody.

7:05

The slow checkouts still failed. But for most of them, a hundred of a hundred and sixteen, the chain answered with an error at the deadline, instead of leaving the customer to time out. And the cook was free for the next checkout.

7:21Back to Lucía

7:22

So, three lessons.

7:25

A timeout doesn’t mean it didn’t happen.

7:29

Give every payment an order number, made once per click, and saved with the payment. If the payment goes to another company, send them the number too.

7:39

And pass the deadline along, so nobody keeps cooking for a customer who left.

7:46

Next time: API bugs that don’t make a sound.

7:51

For today: a timeout isn’t a no.Lucía: A timeout isn’t a no.

7:55Summary

7:56

A timeout isn’t a no, an order number per click, and a deadline passed along.

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.

Try it · One slow payment, then 1,000Lab 06 · 03_idempotency.py · timeout 150 ms, 30% of answers 400 ms

One payment whose first answer is slow · illustration, not a recorded trace

0 ms100 ms200 ms300 ms400 ms500 msAppthe customerPayment servicethe counterCharges savedslip 1✕gave upcharge saved; the answer is slowslip 2✓ answered$1$2
Working / answered Slow on purpose Waiting for the number Saved answer sent back
  1. 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.
  2. The retry looks like a new payment to the service, so it charges again.

The recorded run: 1,000 payments, each retried until answered

Extra charges
466
Timeouts
466
Attempts
1,466
Saved answer sent
0

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_hash is 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.)

Try it · Cooking for customers who leftLab 06 · 04_deadlines.py · client waits 300 ms · inventory has 4 workers

One average second at the grill · modelled from the lab's setup, not a trace

past 1 s: doesn't fit, waits0 s0.25 s0.5 s0.75 s1 s1.25 scustomer leaves: 300 mscook 1cook 2cook 3cook 4
Quick checkout, 20 ms Slow checkout, customer still waiting Cooking for nobody

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

Normal ones in time
25/1,084
Client gave up
1,175
504 at the deadline
0
Cooking for nobody
99%
Inventory's work, added up over 4 cooks103.3 s · 102.0 s after the client left

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

  1. Assume a timeout means "unknown". The work may be done, in progress, or never started.
  2. Give every call that changes something an idempotency key, made once per user action (one click), sent on every retry.
  3. Save the key in the same transaction as the side effect, with the answer, and send the saved answer back to retries.
  4. Compare the request, not just the key. Same key, different body: refuse it.
  5. 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.
  6. 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.
  7. 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.

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

Quiz

Try it · Check your understanding0 of 6 answered
  1. 1.A client's payment request times out after 150 ms. What does the client know about the payment?

  2. 2.Where should a payment service save the idempotency key?

  3. 3.When should the client generate the idempotency key?

  4. 4.A retry arrives with a key that is already saved, but the amount is different. What should the service do?

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

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.