Idempotency keys: making retries safe
A request times out. Did the payment go through? You can't know, so you retry, and now you might have charged twice. How idempotency keys turn every retry into a safe one, and the details that make them actually work.
A client sends "charge this card £40" and waits. Thirty seconds later, the connection drops. No response. Three things could have happened:
- The request never reached the server.
- The server charged the card, and the response got lost on the way back.
- The server is still working on it.
From the client's side, all three look the same. If it gives up, the customer might not get what they paid for. If it retries, the customer might pay twice. Neither is acceptable, and "be careful" isn't a strategy.
Idempotency keys solve this. They're a small idea with a few sharp edges, and they belong in almost every API that changes something.
The idea
An operation is idempotent if doing it twice has the same effect as doing it once. Reading a record is idempotent. Setting a field to a value is idempotent. "Charge £40" and "send this email" are not.
An idempotency key makes a non-idempotent operation behave like one:
- The client makes up a unique key, usually a UUID, for each logical operation: this particular payment, not this particular HTTP request.
- It sends the key with the request, and sends the same key on every retry.
- The server remembers each key it has finished, along with the response it gave. If the key comes in again, it doesn't do the work again. It returns the saved response.
POST /payments
Idempotency-Key: 5f1c2a9e-8d43-4b0e-9a7f-2f6c1d3e4b5a
Content-Type: application/json
{ "amount": 4000, "currency": "GBP", "card": "card_7Hq2" }The first time, the server charges the card and replies 201 with the payment. The second time,
it replies with the same 201 and the same payment, and nothing is charged. From the client's
side, a retry is now always safe. It can retry on timeouts, on dropped connections, on a 503,
and the worst case is a wasted round trip.
The details that make it work
The idea fits in a paragraph. Getting it right takes a few more decisions.
Store the key and the work in one transaction
If you save the key in one step and do the work in another, a crash in between leaves you with a key and no payment (and every retry now returns a success that never happened), or a payment and no key (and the next retry charges again). The key and the side effect have to commit together, or not at all.
Handle two copies arriving at once
Retries aren't always polite. A client with a short timeout can send the second copy while the first is still running. The server needs to make sure only one of them does the work. A unique constraint on the key does this for you: the second insert waits for the first transaction to finish, then sees the key already exists.
Reject the same key with a different request
If a key arrives a second time with a different body, something is wrong: usually a client bug that reuses keys. Don't silently return the old response, and don't run the new request. Store a hash of the request with the key and reply with an error if it doesn't match.
Scope keys to the caller
Two different customers can generate the same key by accident, or on purpose. Make the key unique per account (or per tenant), not globally, so one caller can never see another's saved response.
Decide what counts as "finished"
If the request fails validation, save that response too: retrying a bad request won't make it good. If the server fails partway with an unexpected error and the transaction rolls back, don't save anything, so the retry can try again for real.
Expire them
Keys don't need to live forever. They need to outlast the client's retry window. A day is a common choice. After that, a cleanup job can delete them.
What it looks like
Here's a table and a handler for the case where the work is a write to your own database.
create table idempotency_keys (
account_id text not null,
key text not null,
request_hash text not null,
response_code int,
response_body jsonb,
created_at timestamptz not null default now(),
primary key (account_id, key)
);def create_payment(db, account_id: str, key: str, body: dict):
request_hash = sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
with db.transaction() as tx:
# Claim the key. A concurrent request with the same key waits here.
claimed = tx.fetchone(
"""insert into idempotency_keys (account_id, key, request_hash)
values (%s, %s, %s) on conflict do nothing returning key""",
(account_id, key, request_hash),
)
if not claimed:
saved = tx.fetchone(
"""select request_hash, response_code, response_body
from idempotency_keys where account_id = %s and key = %s""",
(account_id, key),
)
if saved.request_hash != request_hash:
return 422, {"error": "This key was already used for a different request."}
return saved.response_code, saved.response_body
payment = tx.insert_payment(account_id, body)
response = {"id": payment.id, "status": payment.status}
tx.execute(
"""update idempotency_keys set response_code = 201, response_body = %s
where account_id = %s and key = %s""",
(json.dumps(response), account_id, key),
)
return 201, responseEverything happens in one transaction. If anything fails, the key and the payment both roll back
and a retry starts clean. If two copies arrive together, the database makes the second one wait
on the insert, then hands it the saved response.
When the work isn't in your database
The neat single-transaction version only works when the side effect is a write to the same database. Often it isn't: you're calling a payment provider, sending an email, or publishing to a queue. You can't hold a database transaction open across a slow call to somebody else.
The pattern then becomes a small state machine on the key's row:
- Insert the key with status
startedand commit. - Call the external service, passing an idempotency key of your own, derived from the client's. Most payment providers accept one.
- Save the response and mark the row
done.
If a retry finds the row started, either the first attempt is still running (reply 409 and
let the client try again shortly), or it crashed partway. In the crash case, it's safe to call the
external service again, because you're sending it the same key and it will do its own
deduplication. That's the important part: idempotency has to go all the way down. A key that
stops at your API and isn't passed on to the provider protects you from nothing.
For services with no idempotency support at all, like most email sending, you're down to "probably once". Record what you sent and check before sending again, and accept that a crash at exactly the wrong moment can still cause a duplicate.
Queues have the same problem
Message queues almost always deliver at least once. A consumer that crashes after doing the work but before acknowledging the message will see it again. The fix is the same idea: use the message ID, or a business key like the order number, as the idempotency key, and record it in the same transaction as the work.
"Exactly once" delivery is mostly a marketing phrase. What you can build is at-least-once delivery plus idempotent processing, which gives you exactly-once effects. That's what you actually wanted.
And agents have it worse
AI agents retry constantly. A tool call times out, the model sees an error, and it tries again, sometimes with slightly different arguments. Sometimes the harness retries on its own first. If the tool behind it creates a ticket, issues a refund or sends a message, a flaky network can turn one intention into three actions.
Give every tool that changes something an idempotency key, generated by the harness per tool call, not by the model. Pass it through to the system behind the tool. It's the same pattern, for a caller that's even more eager to retry than the usual client.
The short answer
Let the client retry as much as it wants. Make sure the server only acts once.
A client-generated key, saved in the same transaction as the work, checked against the request it came with, scoped to the caller, and passed on to every system downstream. It's a table and twenty lines of code, and it turns "did that go through?" into a question nobody has to ask.