Topic 4 of 5 · 5 min read
Idempotency keys and safe retries
Goal: Find where a retried request would create a duplicate charge and design an idempotency-key scheme that prevents it.
An operation is idempotent when doing it twice has the same effect as doing it once, and anything that charges, sends or creates must be made idempotent because the network will repeat requests. Timeouts, mobile reconnects, queue redeliveries, load balancer retries and AI agents that "try again" all send the same request twice. The client often cannot tell whether the first one worked.
Check yourself · 1 of 3
Which HTTP method is not idempotent by definition?
Why it matters
A customer taps Pay, the connection drops after the server charged the card but before the reply arrived, and the app retries. Without protection the card is charged twice. A model writing a POST /payments handler will usually write exactly that: validate, charge, insert, respond.
Which methods are safe to retry
RFC 9110 says GET, PUT and DELETE are idempotent by definition, so PUT /carts/9 with the same body leaves the same cart. POST is not, so creation and payment need help.
How an idempotency key works
- The client generates a unique key (a UUID) per intended operation and sends it in an
Idempotency-Keyheader. The same key is reused on every retry of that operation. - The server looks up the key before doing any work.
- New key: store it as "in progress", do the work, then save the response (status and body) under the key.
- Seen key, finished: return the saved response without repeating the work.
- Seen key, still in progress: return
409or ask the client to wait. - Same key, different request body: reject with an error. Stripe does this, and its keys can be removed after at least 24 hours. A reuse of one key for two different operations is a client bug worth surfacing.
The key check and the write must be atomic: a unique constraint on the key, or a transaction, not "read, then write". Otherwise two parallel retries both pass the check.
Before and after
app.post("/payments", async (req, res) => {
const charge = await gateway.charge(req.body.amount, req.body.card);
const row = await db.payments.insert({ chargeId: charge.id });
res.status(201).json(row);
});
A retry charges again. Reviewed: read Idempotency-Key, insert it with a unique constraint first, pass the same key on to the gateway, and return the stored response on a repeat.
What goes wrong
- Checking, then acting. Two concurrent requests both see "not used".
- A fresh key per retry. The client library regenerates the key on each attempt, which defeats it.
- No expiry or scoping. Keys must be scoped to the account and cleaned up on a schedule.
Examples
The double charge
const charge = await gateway.charge(amount, card);
await db.orders.insert({ chargeId: charge.id });
If the response is lost, the client retries and the card is charged twice. Fix: accept an Idempotency-Key, store it first under a unique index, forward it to the payment gateway, and return the saved result on a repeat.
Check-then-write race
if (await db.keys.exists(key)) return saved(key);
await doWork();
await db.keys.insert(key);
Two parallel requests both see no key and both do the work. Insert the key first and let the unique constraint reject the second one.
Key points
- Idempotent means repeating a request has the same effect as sending it once, and retries from networks, queues and agents are normal.
- GET, PUT and DELETE are idempotent by definition, but POST needs an idempotency key for payments and creates.
- The server stores the key with the saved response and returns that response on a repeat instead of redoing the work.
- The key check and the write must be atomic, using a unique constraint or transaction, or parallel retries slip through.
- Reusing a key with a different body should be rejected, and keys should be scoped to the account and expire.
Common mistakes
- Assuming a retry only happens when the first request failed.
- Generating a new idempotency key on every retry attempt.
- Checking for the key and writing it in two separate steps.
- Making the endpoint idempotent but not the downstream call to the payment gateway.
Check yourself · 2 of 3
A client retries POST /payments after a timeout, using the same Idempotency-Key. What should the server do if the first request finished?
Check yourself · 3 of 3
A model's handler checks whether the key exists, then does the work, then saves the key. What is the flaw?
Practice items, not counted towards your mastery.
Start here
- Google API Improvement Proposals (AIP) (opens in a new tab)DocsFree
A large, consistent rulebook for resource naming, standard methods, pagination, errors and compatibility.
- RFC 9457: Problem Details for HTTP APIs (opens in a new tab)StandardFree
The standard JSON error shape with type, title, status, detail and instance members.
- Idempotent requests (Stripe API reference) (opens in a new tab)DocsFree
A widely copied idempotency-key design: key reuse, parameter mismatch and key expiry.
More for this topic
- The Idempotency-Key HTTP Header Field (IETF draft) (opens in a new tab)StandardFree
A draft standard for sending an idempotency key on POST and PATCH requests.