Retries and idempotency keys
A request times out. Did it fail, or did it work and the reply get lost? You cannot tell, so you retry. That is only safe when doing it twice is the same as doing it once.
01 The reply that never came
Your code sends a request and the timeout fires. Either the request never arrived, or it arrived and did its work and the reply was lost. From the sender’s side the two look identical. Retrying fixes the first case and doubles the work in the second.
- just happened
- lost in transit
A shop’s server is about to ask the payment provider to charge a card £20. Nothing has been sent and the card has no charges.
You cannot fix this by being careful about when to retry: the information is simply not there. The fix is on the other side. Make the operation idempotent, so that doing it twice has the same effect as doing it once. Then retrying is always safe.
02 Which operations are safe to repeat
An operation is idempotent when running it again changes nothing more. Setting a value is; adding to one is not.
| Operation | Twice = once? | Why |
|---|---|---|
| UPDATE accounts SET balance = 50 | Yes | The second run sets the same value again. |
| UPDATE accounts SET balance = balance - 20 | No | Each run takes another 20. |
| PUT /users/7 {"name": "Ana"} | Yes | Replaces the whole resource with the same thing. |
| DELETE /carts/7 | Yes | The cart is gone after one or two; the second may return 404, but the state is the same. |
| POST /charges | No | Each call creates a new charge. |
HTTP builds this into its methods: GET, PUT and DELETE are defined as idempotent, and POST is not. Some HTTP clients and proxies retry an idempotent request on their own for exactly this reason. Payments, orders and transfers are almost always POST, so they need help.
03 Idempotency keys
An idempotency key turns a non-idempotent request into an idempotent one. The client makes a unique key for each logical operation, such as one purchase, and sends it with every attempt. The server remembers which keys it has finished and what it replied.
- just happened
- lost in transit
- key already done
Same shop, same £20 charge. Before sending anything, the shop makes a random key for this one purchase, 7f3a, and stores it with the order.
Stripe’s API popularised this design with an Idempotency-Key header, and many payment APIs now accept something similar. The same idea appears without the name: a unique order number, or a message id that a consumer checks before processing.
04 Storing keys on the server
The server side is a table of keys with a unique constraint. Inserting the key is how a request claims the work.
| Found | Reply |
|---|---|
| done, same request hash | The saved response, unchanged |
| done, different request hash | An error such as 422: the key was reused for a different request |
| started | An error such as 409: the first attempt is still running; try again shortly |
Never check for the key with a SELECT and then insert it. Two retries arriving together can both see "no key" and both charge. The unique constraint makes the database decide which one wins. When the work is in the same database, write the key, the effect and the saved response in one transaction.
When the work is a call to someone else, such as a card network, a transaction cannot cover it. That is why the started status exists: a key stuck in started after a crash needs a recovery step that asks the downstream system what happened, ideally passing your key on to it.
05 Retry well: backoff and jitter
Once retries are safe, make them polite. Retry only errors that might go away: timeouts, dropped connections, 429, 502, 503, 504. A 400 or 402 will fail the same way every time.
Each wait doubles (exponential backoff) so a struggling server gets more room each time. The wait is also random (jitter). Without it, a thousand clients that failed at the same instant all retry at the same instant too, and knock the server over again.
If the server sends a Retry-After header with a 429 or 503, wait at least that long instead.
06 Where retries still go wrong
key = uuid4() # inside the loopA new key on every attemptEach retry then looks like a new purchase, and the key protects nothing. Make the key once per logical operation, and store it with the order so a restart reuses it.