Difficulty: Advanced
A client's payment request times out. How do you prevent charging the customer twice on retry? Design idempotency keys.
Picture paying at a shop when the card machine freezes. You do not know whether the payment went through, and pressing pay again might charge you twice. Networked APIs have this exact problem, called the two generals issue: a timeout is ambiguous. The client cannot tell if the request never arrived, was processed but the response was lost, or is still running. Retrying is required for reliability, but for POST /payments a naive retry double-charges. Idempotency keys turn a non-idempotent operation into one that is safe to retry.
The protocol: the client generates a unique key, typically a UUID v4, per logical operation and sends it in an Idempotency-Key header. The server stores the key with a fingerprint of the request and the outcome. If the same key arrives again with the same request, the server returns the stored response instead of executing again. The client reuses the same key on every retry of the same intent, but generates a fresh one for a new payment.
Server-side design has several subtle parts. First, atomically claim the key. Use a table with a unique constraint on (account_id, key). Insert a row with status in_progress before doing work. If the insert fails due to a duplicate, you know another attempt exists. Second, handle concurrency: if the original is still in progress, a concurrent retry should get 409 Conflict (or wait briefly) rather than start a second charge. Third, store the request hash. If a client reuses a key with a different body, that is a client bug, so return 422 or 409 rather than silently returning an unrelated response. Fourth, store the final response, status code and body, when the operation finishes, and replay it exactly, including error responses if you choose to cache failures; Stripe caches results, including 500s, once execution started.
Atomicity matters: the key record and the business side effect should commit together, or at least the flow must be recoverable. With a single database, wrap the charge record creation and the key completion in one transaction. When an external call is involved, such as a bank or gateway, pass a derived idempotency key downstream too, so that your own retry to the provider is also safe, and reconcile using webhooks or status queries after ambiguous failures.
Key lifetime: keep keys long enough to cover realistic retry windows, commonly 24 hours; Stripe prunes after 24 hours. Scope keys per merchant or user so one tenant cannot collide with another. Consider only enforcing them on POST and PATCH, since GET, PUT and DELETE are already idempotent by design.
Alternatives and complements: natural business keys, such as a unique order id or a client generated payment reference with a unique constraint, achieve the same protection, and a database unique index is the final backstop against duplicates regardless of any cache. Redis SET NX can implement the claim step quickly, but durable storage is safer for money.
Edge cases: crash after the charge but before saving the response, which recovery jobs must resolve by checking provider state; clock skew for expiry; and clients that generate a new key on each retry by mistake, defeating the purpose. Good SDKs generate the key once per call and reuse it across automatic retries.
In short: unique key, atomic claim, request fingerprint, stored response, concurrency guard, downstream propagation and reconciliation.
POST /v1/payments HTTP/1.1
Idempotency-Key: 6f1c2a9e-4b3d-4d0a-9d55-1a2b3c4d5e6f
Content-Type: application/json
{ "amount": 49900, "currency": "INR", "order_id": "ord_123" }
# first attempt times out; retry sends exactly the same key and body
HTTP/1.1 201 Created
Idempotent-Replayed: true
{ "id": "pay_abc", "status": "captured" }
The retry returns the stored result; no second charge is created.
async function withIdempotency(req, res, handler) {
const key = req.header('Idempotency-Key');
if (!key) return res.status(400).json({ title: 'Idempotency-Key required' });
const hash = sha256(JSON.stringify(req.body));
try {
await db.query(
'INSERT INTO idempotency_keys(account_id,key,request_hash,status) VALUES($1,$2,$3,$4)',
[req.account.id, key, hash, 'in_progress']);
} catch (e) {
if (e.code !== '23505') throw e; // unique violation
const row = await db.one('SELECT * FROM idempotency_keys WHERE account_id=$1 AND key=$2', [req.account.id, key]);
if (row.request_hash !== hash) return res.status(422).json({ title: 'Key reused with different request' });
if (row.status === 'in_progress') return res.status(409).json({ title: 'Request in progress' });
return res.status(row.response_status).set('Idempotent-Replayed', 'true').json(row.response_body);
}
const result = await handler(req);
await db.query('UPDATE idempotency_keys SET status=$3, response_status=$4, response_body=$5 WHERE account_id=$1 AND key=$2',
[req.account.id, key, 'done', result.status, result.body]);
res.status(result.status).json(result.body);
}
Atomic insert claims the key; duplicates are replayed, mismatched bodies are rejected, and concurrent duplicates get 409.
idempotency keys, payments, retries, exactly-once effect