Skip to content

Retries and idempotency keys

Working knowledgeConcept

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.

A retry without protection
Step 1 of 8
Messages and events, in order
Empty
Charges on the card
Empty
  • 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.

Twice the same as once?
OperationTwice = once?Why
UPDATE accounts SET balance = 50YesThe second run sets the same value again.
UPDATE accounts SET balance = balance - 20NoEach run takes another 20.
PUT /users/7 {"name": "Ana"}YesReplaces the whole resource with the same thing.
DELETE /carts/7YesThe cart is gone after one or two; the second may return 404, but the state is the same.
POST /chargesNoEach 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.

The same retry, with a key
Step 1 of 8
Messages and events, in order
Empty
Idempotency keys on the server
Empty
Charges on the card
Empty
  • 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.

idempotency.sql
CREATE TABLE idempotency_keys (
key text PRIMARY KEY,
request_hash text NOT NULL, -- hash of the request body
status text NOT NULL, -- 'started' or 'done'
response jsonb,
created_at timestamptz NOT NULL DEFAULT now()
);
-- First thing the handler does. One row back: this request owns the key.
-- No row back: someone has used this key before.
INSERT INTO idempotency_keys (key, request_hash, status)
VALUES ($1, $2, 'started')
ON CONFLICT (key) DO NOTHING
RETURNING key;
What the handler does when the key already exists
FoundReply
done, same request hashThe saved response, unchanged
done, different request hashAn error such as 422: the key was reused for a different request
startedAn 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.

charge.py
import random
import time
import uuid
import requests
RETRYABLE = {429, 502, 503, 504}
def create_charge(order, attempts=4, base=0.2):
key = str(uuid.uuid4()) # one key for this charge, made before the loop
for attempt in range(attempts):
try:
r = requests.post(
PROVIDER_URL,
json=order,

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.

Fixed or plain doubling waitsRetries arrive in wavesEvery client that failed together retries together.
Backoff with full jitterRetries spread outEach client picks a random wait up to the limit, so the load arrives evenly.

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.
Retries at every layerIf the app, its HTTP client and a proxy each try 3 times, one failing call becomes 3 × 3 × 3 = 27 requests at the bottom. Retry in one layer, usually the one closest to the user’s intent.
Keys that expire too soonServers delete old keys eventually. A retry that arrives after its key is gone is treated as new. Keep keys longer than your longest retry window, including retries from a job queue.
"Exactly once" from the networkNo network delivers exactly once. What you can build is at-least-once delivery plus idempotent handling, which has the effect of once.

07 Check yourself

Question

A charge request times out. What do you know about the charge?

Question

Which of these is idempotent?

Question

A retry arrives with key 7f3a while the first attempt with 7f3a is still running. What should the server do?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?