A customer taps Pay. Your app sends POST /payments, the provider charges the card, and your API saves the payment. Then the response is lost on its way to a phone on train Wi-Fi. After 10 seconds the app retries, and without protection the customer pays twice.
The client cannot tell "the request never arrived" from "it worked, but the answer got lost". An idempotency key closes that gap: the server stores the client's unique key with the result, so a retry gets the first result back instead of a second charge.
This post covers idempotent HTTP methods, the Idempotency-Key header, server and client rules, key storage, idempotent consumers, and a sequence diagram of a retry that charges once.
Why retries create duplicates
A timeout can hide three different failures:
| Where it failed | What the server did | A blind retry |
|---|---|---|
| Before the server received it | Nothing | Charges once |
| While the server was working | Maybe charged, maybe saved nothing | May charge again |
| After the server finished | Charged and saved the payment | Charges again |
Only the first row is safe to retry blindly, and the client cannot know which row it is in. Retries also come from SDKs, proxies, redelivering brokers and double clicks, and the circuit breaker pattern post explains why you need them anyway.
Which HTTP methods are idempotent
RFC 9110 calls a method idempotent when "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request." Clients should not retry other requests automatically unless they know the request is idempotent or was never applied; proxies must not retry them at all.
| Method | Idempotent | Retry without a key? |
|---|---|---|
| GET, HEAD, OPTIONS, TRACE | Yes (also safe) | Yes |
| PUT, DELETE | Yes | Yes; a second DELETE may return 404, which is fine |
| POST | No | No |
| PATCH | No (RFC 5789) | Only if it sets absolute values, not relative ones |
The effect repeats, not necessarily the response. A client-chosen ID makes PUT /payments/{id} idempotent by design, but actions such as charging a card rarely fit that shape. They need idempotency keys.
The Idempotency-Key header
The IETF HTTPAPI working group is standardizing the header in draft-ietf-httpapi-idempotency-key-header. At the time of writing (November 2026) it is at revision 08 (22 October 2026), intended for the Standards Track and not yet an RFC. The value is a quoted Structured Field String, and the draft recommends a UUID or a similar random value:
POST /payments HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"
{"amount": 4000, "currency": "usd", "source": "card_123"}
The draft's rules: never reuse a key with a different payload (the server may fingerprint payloads to detect it), and servers publish their rules, including how long keys stay valid. Errors are 400 for a missing required key, 422 for a reused key with a different payload, and 409 while the first request still runs.
Stripe is the best-known implementation. On API v1 it saves the first response once the endpoint starts executing and replays it on retries, 500 errors included, marked with Idempotent-Replayed: true. Keys can be up to 255 characters and may be pruned once they are 24 hours old, and a retry with different parameters fails. Stripe's examples send the key unquoted, so accept both forms.
The server algorithm, step by step
The core rule, as the AWS Builders' Library puts it: record the caller's token and its changes atomically, and answer retries with an equivalent response, not an "already exists" error. For a payment endpoint:
- Validate and scope the key. Reject a missing key with 400 and store it per account, as
(account_id, key), so clients cannot reach each other's responses, following the draft's security section. - Fingerprint the request: a SHA-256 hash of the method, path and canonical body.
- Claim the key atomically with status
in_progress. A unique constraint lets exactly one request win. - Do the work. Call the provider with an idempotency key of your own, derived from your payment ID, so a recovery run cannot charge twice either.
- Store the outcome. In one transaction, write the payment row and mark the key
completedwith the status code and body. - Answer duplicates from the record, as the next section shows.
CREATE TABLE idempotency_keys (
account_id bigint NOT NULL,
key text NOT NULL,
fingerprint bytea NOT NULL,
status text NOT NULL, -- in_progress | completed
response_code int,
response_body jsonb,
locked_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, key)
);
INSERT INTO idempotency_keys (account_id, key, fingerprint, status)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT (account_id, key) DO NOTHING
RETURNING key; -- no row back: the key already exists
Commit the claim in its own short transaction. PostgreSQL makes a second inserter wait while a conflicting insert is uncommitted, so a claim held open during a 10-second provider call stalls duplicates instead of answering 409 (INSERT … ON CONFLICT).
If the process dies after the claim, the record stays in_progress. Once locked_at is older than your longest request timeout, let a retry take it over with a conditional UPDATE and run the work again. The provider's own key makes that safe.
What the API answers
| Case | Record found | Response |
|---|---|---|
| New key | None | Process, store and return the result |
| Retry after success | completed, same fingerprint |
The stored status and body, no new work |
| Retry while the first attempt runs | in_progress, same fingerprint |
409 Conflict; retry later with the same key |
| Same key, different body | Different fingerprint | 422 Unprocessable Content |
| Key already purged | None | Processed as new, so a duplicate is possible |
Decide which failures you store. Stripe's v1 replays even a 500 but saves nothing when validation fails or a concurrent request holds the key; its v2 APIs finish failed work on a retry when they can. If a transient error stopped a request before any side effect, delete the record so the retry can run.
Where to store keys
| Database table with a unique constraint | Redis with a TTL | |
|---|---|---|
| Claim | INSERT … ON CONFLICT DO NOTHING |
SET key value NX EX 86400 |
| Atomic with your business write | Yes, same transaction | No, separate system |
| Expiry | A cleanup job deletes old rows | Built in |
| After a failover | As durable as your database | Replication is asynchronous by default; a recent key can be lost |
| Good fit | Payments, orders, anything with money | High-volume deduplication where a rare duplicate is acceptable |
If the operation writes to a relational database, keep the keys there too, so the response and the payment row commit together. Keep keys longer than any client retries; Stripe's 24 hours is a useful floor.
Idempotent message consumers
Most brokers deliver at least once. The Amazon SQS documentation tells you to make consumers idempotent because a message copy can come back, and a Kafka consumer that crashes before committing its offset reads the same records again. SQS FIFO deduplication covers only sends within a 5-minute interval. Consumers need a dedupe table, written in the same transaction as the side effect:
BEGIN;
INSERT INTO processed_messages (consumer, message_id)
VALUES ('billing', $1)
ON CONFLICT DO NOTHING; -- 0 rows inserted: already handled, roll back and skip
-- apply the side effect here, in the same transaction
COMMIT;
For an external side effect, pass the message ID downstream as the idempotency key. Events from a transactional outbox arrive at least once, and saga steps must be idempotent for the same reason; the pub/sub versus message queue comparison covers delivery guarantees.
Client rules
- One key per operation, not per attempt. Create it when the user presses Pay and save it with the order, as Stripe's error handling guide advises for retries across restarts.
- Same key, same body. A changed body with an old key gets a 422; a new operation gets a new key, once you know the first one failed and is not running.
- On 409, wait and retry with the same key.
- Back off with jitter, then stop within the server's retention window. Stripe says to retry within 24 hours, then reconcile.
- Treat a 5xx or a timeout as unknown. Check the payment's status before you start over.
- Use random keys such as UUIDv4, never timestamps, counters or personal data.
import random, time, uuid
import requests
def create_payment(url, body, key=None):
key = key or str(uuid.uuid4()) # one key per payment, saved with the order
for attempt in range(5):
try:
r = requests.post(url, json=body, timeout=10,
headers={"Idempotency-Key": key})
if r.status_code not in (409, 429) and r.status_code < 500:
return r
except (requests.Timeout, requests.ConnectionError):
pass
time.sleep(random.uniform(0, min(30, 2 ** attempt))) # backoff with jitter
raise RuntimeError(f"Outcome unknown; reconcile payment {key}")
The idempotency key sequence diagram
Diagram contents
- Client
- Payments API
- Idempotency store
- Payment provider
- key completed, same body
- POST /payments, Idempotency-Key: k1
- INSERT k1 + fingerprint: in_progress
- charge 40.00 USD, own idempotency key
- charge succeeded
- UPDATE k1: completed, save 201 + body
- 201 Created (lost)
- retry: POST /payments, same key k1
- look up k1, compare fingerprint
- completed: stored 201 + body
- 201 Created, replayed
- 409 Conflict: retry later
How to read it:
- Participants. Three lifelines, plus the Idempotency store drawn as an entity, the participant that holds data.
- First attempt. The API claims key k1 as
in_progress, charges 40.00 USD with its own key, then marks k1completedwith the 201 response. - The lost response. The red dashed reply ending in a cross never arrives. After a 10-second timeout and a backoff, the client retries with k1.
- The retry. The API looks up k1 and compares fingerprints. The alt block shows the answers: the stored 201 replayed, or 409 Conflict while the first attempt still runs. The provider is not called again.
- The Markdown block lists the server rules and the example's settings.
Drawing idempotency flows clearly
- Draw the failure. The lost response is why the pattern exists; mark it with a red dashed reply and a cross.
- Show every write to the key store, so reviewers can check the order: claim first, response saved with the business write.
- Label the key on each message, including the downstream key to the provider.
- Use an alt fragment for the outcomes, guarded by the key state.
- Leave out authentication, logging and the provider's internals.
- Watch for a check and an insert drawn as separate steps (a race) and a new key per attempt.
For notation, see the sequence diagram example; the payment gateway integration post shows the full checkout flow, from authorization to webhooks.
Build it in Archboard
- Sign in with Google or GitHub and create a diagram.
- Add three Lifeline nodes from the Sequence pack (Client, Payments API, Payment provider) and an Entity from the Sequence pack (Idempotency store) between the API and the provider, all with the same top and height.
- Draw the first attempt as straight edges, top to bottom: the POST with key k1, the INSERT, the charge, its reply and the UPDATE. Calls get solid lines and block arrows; replies get dashed lines and open arrows.
- Draw the lost 201 as a red dashed edge that stops short of the Client with a cross, add a Core Text note about the timeout, then draw the retry: the second POST, the lookup and the store's reply.
- Add a Fragment from the Sequence pack with the operator
altover the replayed 201 and the 409. Its label is the first guard; a Core Text holds the second. - Add a Core Text by the provider saying it is not called again, and a Markdown block from the Core pack with the rules.
The payment flow diagrams page shows other payment sequences. The example uses 6 diagram nodes, within the Free plan.
FAQ
What is an idempotency key? A unique value, usually a UUID, sent with a request that changes state. The server stores it with the result and answers retries with that result instead of repeating the work.
Is POST idempotent? No. RFC 9110 lists GET, HEAD, OPTIONS, TRACE, PUT and DELETE as idempotent, but not POST, and PATCH (RFC 5789) is not idempotent either. An idempotency key makes a POST endpoint safe to retry.
How long should idempotency keys be stored? Longer than any client keeps retrying. Stripe's v1 API keeps them at least 24 hours; the IETF draft lets each API choose but asks it to publish the policy.
What should the server return when an idempotency key is reused? The stored response if the first request finished with the same body, 409 Conflict while it is still running, and 422 Unprocessable Content if the body differs, as the IETF draft recommends.
Should I store idempotency keys in Redis or in the database?
Prefer the database the operation writes to, so the key, the response and the business change commit together. Redis with SET NX EX is fast and expires keys on its own, but a failover can lose recent keys.