API-32Required
Accept idempotency keys on POST that creates or charges
Let clients send an Idempotency-Key header on every POST or PATCH that creates a record, sends a message or moves money. Return the first result for a repeated key instead of acting twice.
How to do it
A POST that is already safe to repeat needs no key. One example is a create where the client picks the ID, so a repeat finds the record and answers 200 or 409. So does a call only your own backend makes inside one transaction. Scope each key to the caller. Store it with a hash of the request body and the response, for at least 24 hours. A repeat with the same body gets the stored response. A repeat with a different body gets 422, and a repeat while the first is still running gets 409. Require the key on payments and orders, and answer 400 when it is missing. Insert each key under a unique constraint in the same transaction as the write. Then two copies sent at once cannot both act. Queue, job and webhook consumers drop repeats as Process each message once describes. Clients resend keys as Send the same idempotency key when you retry a write says. The header comes from the expired IETF draft draft-ietf-httpapi-idempotency-key-header, so name it and your expiry in the docs. See also save each form only once.
Examples
HTTP example
POST /payments HTTP/1.1
Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324
Content-Type: application/json
{"orderId":"ord_8f2k","amount":12950,"currency":"SEK"}
JavaScript example
async function withIdempotency(callerId, key, body, handle) {
const bodyHash = sha256(canonicalJson(body))
const claimed = await store.claim({ callerId, key, bodyHash, ttlHours: 24 })
if (!claimed.isNew) {
if (claimed.bodyHash !== bodyHash) return problem(422, 'idempotency-key-reused')
if (!claimed.response) return problem(409, 'request-in-progress')
return claimed.response
}
const response = await handle(body)
await store.saveResponse({ callerId, key, response })
return response
}
Python example
def with_idempotency(caller_id, key, body, handle):
body_hash = sha256(canonical_json(body))
claimed = store.claim(caller_id=caller_id, key=key, body_hash=body_hash, ttl_hours=24)
if not claimed.is_new:
if claimed.body_hash != body_hash:
return problem(422, "idempotency-key-reused")
if claimed.response is None:
return problem(409, "request-in-progress")
return claimed.response
response = handle(body)
store.save_response(caller_id=caller_id, key=key, response=response)
return response
SQL example
CREATE TABLE idempotency_keys (
caller_id bigint NOT NULL,
key text NOT NULL,
request_hash text NOT NULL,
response jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (caller_id, key)
);
-- Inside the order transaction: 0 rows back means the key was used before
INSERT INTO idempotency_keys (caller_id, key, request_hash) VALUES ($1, $2, $3)
ON CONFLICT (caller_id, key) DO NOTHING RETURNING key;
How to check
Send the same POST with the same key twice, both at once. One order exists, and both answers are identical. The same key with a changed body gets 422. A payment POST without the header gets 400.
Sources
Related rules
- API-2 Use each method for what it means in API design
- API-91 Return a result for each item in a batch in API design
- EVT-11 Process each message once in Integration and events
- API-76 Send the same idempotency key when you retry a write in API design
- APP-20 Save each form only once in Web app interface
- API-89 Set a deadline on every gRPC call and pass it on in API design
- DAT-78 Import files through a staging table in Data and databases
- PAY-14 Create each charge with an idempotency key in Payments and billing
- PAY-38 Refund through the provider with a key and a reason in Payments and billing
- AIF-17 Make tools that change things safe to repeat in AI features
- APP-51 Give every request a time limit in Web app interface
- NTF-21 Send the current subscription to the server on every start in Notifications
- STK-35 Use BullMQ or RQ for background jobs in Software choices
- STK-104 Use RabbitMQ for messages between services and Kafka for event streams in Software choices
- STK-105 Use Temporal for long workflows that must survive restarts in Software choices
- MOB-26 Queue offline changes and resolve conflicts on the server in Mobile apps
- USG-1 Give every usage event a key and count it once in Usage-based billing
- DEN-7 Make every load safe to rerun in Data engineering
- ECM-26 Buy each shipping label once in E-commerce and fulfilment
- EVT-22 Run each scheduled job once at a time in Integration and events
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/reliability/idempotency-keys">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.