An idempotency key is a client-generated, unique value sent with a non-idempotent request, usually POST, so the server can recognise a retry and return the original result instead of doing the work twice. A correct design needs five things. Store the key, scoped per tenant, in the same database as the business data. Fingerprint the request so a reused key with a different payload is rejected (422). Hold a lease so a concurrent duplicate gets a 409, not a second execution. Replay the stored response for completed requests. Expire keys after a published window. Side effects that leave your database go through an outbox or a downstream idempotency key, because "exactly once" does not exist across a network.
The rest of this post is the version we would actually build: the schema, the claim query, the concurrency rules, the payment flow, and a conformance test matrix you can lift into your own test suite.
01Why retries create duplicates in the first place
A client sends POST /. The connection drops before the response arrives. The client cannot tell which of three things happened: the request never arrived, it arrived and failed, or it succeeded and only the response was lost. The only safe move is to retry. Without a way to match the retry to the original, the third case charges the customer twice.
HTTP already has a word for methods where this is harmless. RFC 9110 §9.2.2 defines a method as idempotent if "the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request", and names PUT, DELETE and the safe methods. POST and PATCH are not on the list. An idempotency key is how you give a POST that property for a bounded window.
The retries do not only come from your clients. They come from SDK retry loops, mobile apps replaying an offline queue, load balancers and service meshes with retry policies, message brokers redelivering, impatient humans pressing the button again, and, increasingly, AI agents looping in production on a tool call that timed out. You do not control most of these. Design as if every mutating request will arrive at least twice.
02Do you need idempotency keys at all?
Not always. Before adding a key table, check whether the operation can be made naturally idempotent:
- Client-chosen resource IDs.
PUT /with a UUID the client generated is idempotent by construction. The primary key does the deduplication. If your API can accept client IDs, this is simpler than any key scheme.orders/ {order_ id} - Conditional writes.
If-Matchwith an ETag (RFC 9110 §13.1.1) turns "set balance to X" into "set balance to X if it is still version 7". A retry after success fails the precondition harmlessly. - Set semantics rather than deltas. "Mark invoice paid" is idempotent. "Add £10 to balance" is not.
You need idempotency keys when the operation creates something with a server-assigned identity, moves money, sends something irreversible (an email, an SMS, a bank transfer), or calls a third party. That covers most payment and order APIs.
03How Stripe, AWS, Adyen and the IETF draft handle idempotency
There is no single standard, but the large APIs have converged on a recognisable shape. The differences are instructive, especially around what happens when the first attempt failed.
| Header / field | Key limits | Retention | Same key, different payload | Same key while in flight | Retry after a failed first attempt | |
|---|---|---|---|---|---|---|
| Stripe API v1 | Idempotency-Key |
≤255 chars | Pruned after at least 24 hours | Error | 409 Conflict (status codes) |
Replays the stored result, including 500s |
| Stripe API v2 | Idempotency-Key |
– | 30 days | – | – | Re-executes the failed part and returns a new response |
| AWS (client tokens) | ClientToken parameter |
Per API | Per API | "Validation error indicating a parameter mismatch" | Per API | Semantically equivalent response |
| Adyen | idempotency-key |
≤64 chars | 7 to 14 days | – | 422 or 409, error code 704 |
– |
| IETF draft-07 | Idempotency-Key (sf-string) |
– | Server SHOULD publish a policy | 422 |
409 |
Not specified |
Two points stand out.
Stripe's two namespaces disagree on failure replay, deliberately. v1 stores "the resulting status code and body of the first request made for any given idempotency key, regardless of whether it succeeds or fails", and tells you to treat a 500 as indeterminate (low-level error handling). v2 "re-executes the failed requests and returns the new response". The v2 behaviour is friendlier to clients but much harder to implement, because the server must know exactly which parts of the failed attempt took effect. That is the recovery-point design described below. If you cannot build that, the v1 behaviour is the honest one.
Rejected-before-execution requests are not stored. Stripe saves results "only after the execution of an endpoint begins". Validation failures, auth failures and rate limits run before the idempotency layer, so retrying them with the same key can produce a different result (source). Copy this. Caching a 429 under a key would turn a transient throttle into a permanent failure.
Where is the IETF Idempotency-Key header draft now?
The HTTPAPI working group's draft-ietf-httpapi-idempotency-key-header reached revision 07 on 15 October 2025. As of today the datatracker lists it as expired (it lapsed on 18 April 2026), still a WG document, with no IESG submission and no RFC. The working group's document list gives no sign yet of whether it will be revived or dropped.
It is still the best neutral reference for the wire contract, and we follow it for new APIs:
- The header is a Structured Field Item whose value MUST be a String. The draft cites RFC 8941, since obsoleted by RFC 9651 with the same String type. Strictly, that means a quoted value:
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"- Missing key on an operation that requires one:
400. - Key reused with a different payload:
422. - Retry while the original is still processing:
409. - The server SHOULD document its expiry policy.
In practice, Stripe and most SDKs send the value unquoted. Accept both: strip one pair of surrounding double quotes if present, then validate. Rejecting unquoted keys on the grounds of an expired draft will only break real clients.
04The anatomy of an idempotent request
Every request with a key resolves to one of five outcomes. Drawing them out first prevents most of the bugs.
POST /payments Idempotency-Key: K
│
▼
validate auth, rate limit, schema
(failures here are NOT stored)
│
▼
claim (tenant, K) with fingerprint F
│
├─ new row (we own it)
│ └─▶ execute from recovery_point = 'started'
│
├─ row exists, fingerprint ≠ F
│ └─▶ 422 mismatch
│
├─ row exists, completed
│ └─▶ replay stored response
│ Idempotent-Replayed: true
│
├─ row exists, in progress, lease live
│ └─▶ 409 + Retry-After
│
└─ row exists, in progress, lease expired
└─▶ take over lease (new fencing token),
resume from stored recovery_point05Idempotency key storage schema (Postgres)
Store keys in the same database as the data the request mutates. This is the single most important decision in the design. It lets the key's state change in the same transaction as the business rows, so there is never a moment where the payment exists but the key says "not started", or the reverse. A separate Redis instance cannot give you that.
The schema below follows the shape Brandur Leach described for Stripe-style keys in Implementing Stripe-like Idempotency Keys in Postgres (2017), with a fencing token and an explicit expiry added.
CREATE TABLE idempotency_keys (
tenant_id uuid NOT NULL,
key text NOT NULL CHECK (length(key) BETWEEN 1 AND 255),
operation text NOT NULL, -- e.g. 'POST /v1/payments' (route template, not raw path)
fingerprint bytea NOT NULL, -- SHA-256 of the canonical request
state text NOT NULL CHECK (state IN ('in_progress', 'completed')),
recovery_point text NOT NULL DEFAULT 'started',
lock_token uuid, -- fencing token for the current owner
locked_until timestamptz, -- lease expiry
response_status smallint,
response_headers jsonb,
response_body bytea,
resource_id text, -- e.g. the payment ID, for support and audit
created_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
expires_at timestamptz NOT NULL,
PRIMARY KEY (tenant_id, key)
);
CREATE INDEX idempotency_keys_expires_at ON idempotency_keys (expires_at);Decisions worth defending:
- Scope the key by tenant (or API credential), never globally. With a global key space, one customer's key can collide with another's, and in the worst case a guessed key replays someone else's stored response body. Adyen scopes at company-account level; Stripe v2 at "the same account or sandbox". If you already isolate tenants with row-level security in multi-tenant Postgres, put the key table under the same policy.
- Store the route template as
operation. A key reused acrossPOST /andpayments POST /is a client bug. Treat it as a mismatch.refunds - Store the response, not just "done". Replay means returning the same status, the same body and the relevant headers (
Location, for one). Rebuilding the response from current state is tempting and wrong: the resource may have changed since, and the client asked "what happened to my request", not "what does it look like now". - The response body is personal data. It probably contains names, addresses or card fingerprints. Your retention policy, encryption at rest and subject-access process have to cover this table.
06Request fingerprinting: detecting a reused key with a different payload
The fingerprint answers one question: is this retry the same request? Compute it over the parts of the request that define its meaning, and nothing else.
Include the tenant, method, route template, path parameters and a canonical form of the body. Exclude transport noise: Date, tracing headers, User-Agent, auth tokens (which rotate), and JSON whitespace or key order. Use RFC 8785 JSON Canonicalization Scheme rather than JSON., which preserves insertion order and so hashes two equal objects differently.
import { createHash } from "node:crypto";
import canonicalize from "canonicalize"; // RFC 8785 implementation
export function fingerprint(req: {
tenantId: string;
method: string;
routeTemplate: string; // "/v1/payments/:id/capture"
params: Record<string, string>;
body: unknown;
}): Buffer {
const material = canonicalize({
t: req.tenantId,
m: req.method.toUpperCase(),
r: req.routeTemplate,
p: req.params,
b: req.body ?? null,
});
return createHash("sha256").update(material!, "utf8").digest();
}Two judgement calls. First, fields the client legitimately varies on retry, such as a client-side sent_at timestamp, must be excluded or every retry looks like a mismatch. Find them in your schema, not in production. Second, the IETF draft also allows fingerprinting only selected fields. AWS Powertools exposes this as payload_, which raises Idempotency when, say, amount changes under the same key (docs). Full-body hashing is stricter and simpler to reason about. Start there.
07Handling concurrent requests with the same idempotency key
The dangerous case is not the retry that arrives a minute later. It is the retry that arrives 200 milliseconds later, while the original is still running. Two workers both see "no key", both execute, and the customer is charged twice. A SELECT followed by an INSERT has exactly this race.
The fix is to make the claim a single atomic statement, and to commit it before doing any work.
-- $1 tenant_id, $2 key, $3 operation, $4 fingerprint, $5 new lock_token, $6 lease interval
INSERT INTO idempotency_keys
(tenant_id, key, operation, fingerprint, state, lock_token, locked_until, expires_at)
VALUES ($1, $2, $3, $4, 'in_progress', $5, now() + $6::interval, now() + interval '24 hours')
ON CONFLICT (tenant_id, key) DO UPDATE SET
operation = EXCLUDED.operation, fingerprint = EXCLUDED.fingerprint,
state = 'in_progress', recovery_point = 'started',
lock_token = EXCLUDED.lock_token, locked_until = EXCLUDED.locked_until,
response_status = NULL, response_headers = NULL, response_body = NULL,
resource_id = NULL, created_at = now(), completed_at = NULL,
expires_at = EXCLUDED.expires_at
WHERE idempotency_keys.expires_at < now() -- only recycle keys that have expired
RETURNING recovery_point;If a row comes back, you own the key. The DO UPDATE ... WHERE clause recycles an expired row the reaper has not deleted yet, so expiry is enforced by the query rather than by how promptly the cleanup job runs. If no row comes back, someone else holds a live key, and a second read decides the outcome:
type Claim =
| { kind: "owner"; token: string; recoveryPoint: string }
| { kind: "replay"; status: number; headers: Record<string, string>; body: Buffer }
| { kind: "in_progress"; retryAfterSeconds: number }
| { kind: "mismatch" };
export async function claim(db: Pool, k: KeyInput, attempt = 0): Promise<Claim> {
if (attempt > 3) throw new Error("idempotency claim did not converge");
const token = randomUUID();
const ins = await db.query(CLAIM_SQL, [k.tenantId, k.key, k.operation, k.fp, token, LEASE]);
if (ins.rowCount === 1) return { kind: "owner", token, recoveryPoint: ins.rows[0].recovery_point };
const { rows: [row] } = await db.query(
`SELECT operation, fingerprint, state, recovery_point,
response_status, response_headers, response_body,
locked_until > now() AS lease_live,
GREATEST(1, ceil(extract(epoch FROM locked_until - now())))::int AS retry_after
FROM idempotency_keys
WHERE tenant_id = $1 AND key = $2`,
[k.tenantId, k.key]);
if (!row) return claim(db, k, attempt + 1); // reaped in between: try again
if (row.operation !== k.operation || !row.fingerprint.equals(k.fp)) return { kind: "mismatch" };
if (row.state === "completed")
return { kind: "replay", status: row.response_status, headers: row.response_headers, body: row.response_body };
if (row.lease_live) return { kind: "in_progress", retryAfterSeconds: row.retry_after };
// Lease expired: the previous owner crashed or stalled. Take over with a new fencing token.
const take = await db.query(
`UPDATE idempotency_keys
SET lock_token = $3, locked_until = now() + $4::interval
WHERE tenant_id = $1 AND key = $2
AND state = 'in_progress' AND locked_until <= now()
RETURNING recovery_point`,
[k.tenantId, k.key, token, LEASE]);
return take.rowCount === 1
? { kind: "owner", token, recoveryPoint: take.rows[0].recovery_point }
: claim(db, k, attempt + 1); // lost the takeover race
}Map the outcomes to HTTP: owner executes; replay returns the stored response with Idempotent-Replayed: true (Stripe's header name; not defined by the IETF draft); in_progress returns 409 with Retry-After; mismatch returns 422.
Why a lease and a fencing token, not a lock
Under Postgres's default READ COMMITTED, a second concurrent INSERT for the same key blocks until the first transaction commits, then takes the conflict path. That is why the claim must be its own short transaction. If you open a transaction, insert the key, call your payment provider and commit at the end, every duplicate request queues on a row lock for the duration of a third-party HTTP call, holding a connection each. Under a retry storm that exhausts the pool. Commit the claim, then work.
Once the claim is committed, the "lock" is just data: locked_. That raises the classic problem. Owner A stalls in a long GC pause, its lease expires, B takes over and finishes, then A wakes up and writes its own result. The lock_token is a fencing token: every write the owner makes is conditional on still holding it.
-- Run inside the same transaction as the final business writes.
UPDATE idempotency_keys
SET state = 'completed', recovery_point = 'finished',
response_status = $4, response_headers = $5, response_body = $6,
resource_id = $7, completed_at = now(), locked_until = NULL
WHERE tenant_id = $1 AND key = $2 AND lock_token = $3;
-- rowCount = 0 → we lost the lease: ROLLBACK, do not respond as if we succeeded.The fence protects your database. It cannot recall an HTTP call A already made to a payment provider. That is what downstream idempotency keys are for, below.
Choose the lease length from your p99.9 latency for the endpoint plus headroom, and extend it at each recovery point. Thirty seconds suits most synchronous payment calls. Too short and healthy requests get taken over; too long and a crashed request blocks the client's retries for that long.
08Payments: recovery points and downstream idempotency keys
A payment endpoint typically does local work, calls a payment service provider (PSP), then does more local work. The PSP call is a foreign state mutation: you cannot roll it back with your transaction. Brandur's design splits the request into atomic phases, each a local transaction that ends by advancing recovery_. Foreign calls sit between phases.
Illustrative flow for POST /:
recovery_point phase (one DB transaction each, fenced by lock_token)
─────────────── ────────────────────────────────────────────────────
started insert payments row (status 'pending');
set recovery_point = 'payment_created'
payment_created call PSP with a DERIVED idempotency key
(foreign mutation, not rolled back by us);
store psp_charge_id; set recovery_point = 'charged'
charged mark payment 'succeeded';
insert outbox event 'payment.succeeded';
store response; set state = 'completed'A worker that takes over a key reads recovery_ and resumes from there. If it resumes at payment_, it repeats the PSP call. That is safe only because the call carries a deterministic key derived from yours:
// Stripe allows keys up to 255 characters, so hash rather than concatenate.
const pspKey = createHash("sha256")
.update(`${tenantId}:${idempotencyKey}:charge`)
.digest("hex"); // 64 chars
await stripe.paymentIntents.create(
{ amount, currency, customer, confirm: true, metadata: { payment_id: paymentId } },
{ idempotencyKey: pspKey },
);The payment_id in metadata matters too. If the PSP returns a 500, Stripe's guidance is to treat the outcome as indeterminate and to cross-reference later webhooks using an identifier you put in metadata (source). Your webhook handler then reconciles the payment rather than your retry loop guessing.
Your recovery window is bounded by the shortest window downstream. If you call Stripe v1, the derived key only protects you for about 24 hours. A stuck request resumed on day two will create a second charge. Either keep your own key TTL and your takeover horizon inside every downstream's window, or before re-calling the provider, look the object up by your own reference first. With Adyen (7 to 14 days) and Stripe v2 (30 days) the bound is looser, but it is always there.
Which responses to store, and the 5xx question
- Store:
2xx, and deterministic4xxproduced after execution began (a card decline is a final answer for that request). - Do not store: anything rejected before the claim (
400schema errors,401,403,429). The client should fix and retry, possibly with the same key. - Unexpected exception before any foreign mutation: delete the key row (fenced by token) so the retry runs cleanly. Powertools takes the same approach and deletes the record on an unhandled exception.
- Unexpected exception after a foreign mutation: leave the key
in_progresswith its recovery point. The client's next retry, after the lease expires, resumes it. Do not cache a500as the final answer for that key unless you genuinely cannot resume, which is Stripe v1's trade-off, documented as such.
09Idempotency key TTL: how long to keep keys
The draft leaves the window to you but says to publish it. Our rule: TTL ≥ the longest time a legitimate client could still be retrying, plus margin, and ≤ every downstream window you rely on.
Inputs to that:
- SDK retry budgets are short: seconds to minutes.
- Mobile offline queues and batch jobs replay hours later.
- Message redelivery from a dead-letter queue can be days later, if someone re-drives it.
Twenty-four hours suits synchronous APIs with SDK clients. Seven days suits APIs consumed by queues or mobile apps. Stripe moved from 24 hours (v1) to 30 days (v2), which tells you which way the large providers lean.
Storage is rarely the constraint, but do the sum. Worked example, with stated assumptions: 2 million keyed requests a day, an average row of 2 KB including the stored response body. At a 24-hour TTL you hold roughly 2,000,000 × 2 KB ≈ 4 GB of live rows. At 30 days, roughly 120 GB, plus index and bloat. The first fits comfortably next to your OLTP data; the second is worth a conversation about storing only response bodies under a size limit, or compressing them.
Reaping, in Postgres: delete in small batches using the expires_at index (DELETE ... WHERE ctid IN (SELECT ctid ... WHERE expires_), run often. Declarative partitioning by day is tempting because dropping a partition is cheap, but in Postgres a unique constraint on a partitioned table must include the partition key, so (tenant_ would no longer be unique across days. You would lose the guarantee the table exists for. Batch deletes are dull and correct. The mechanics of running these jobs against a busy table are covered in our post on zero-downtime Postgres migrations.
10Where to store idempotency keys: Postgres vs Redis vs DynamoDB
| Store | Atomic claim | Same transaction as business writes | Durability on failover | Expiry | Use when |
|---|---|---|---|---|---|
| Postgres (same DB) | INSERT ... ON CONFLICT |
Yes | Synchronous replication available | Batch reaper | Default for anything touching money |
| Redis / Valkey | SET key val NX PX ttl |
No | Asynchronous replication can lose acknowledged writes on failover (Redis replication docs) | Native TTL | Deduplicating cheap, retry-safe work; rate-limit-adjacent use |
| DynamoDB | PutItem with attribute_ (conditional writes) |
Only if business data is in DynamoDB too (Transact) |
Durable | Native TTL (deletion is eventual) | Serverless stacks; Powertools does this for you |
The Redis row is the one teams get wrong. A key store that can forget a claim during a failover is a key store that will, during your worst afternoon, let a duplicate through. If the operation moves money, keep the key next to the money. The same reasoning applies across regions: in an active-active multi-region deployment, two regions can each claim the same key, so route a tenant's writes to one region.
If you are on Lambda, Powertools for AWS Lambda gives you most of this design off the shelf: INPROGRESS/COMPLETE records, concurrent-request rejection, payload validation and timeout protection. Note its default expires_ is 3,600 (one hour), short for most payment use. Raise it deliberately.
11"Exactly once" is a myth: idempotent processing is what you can build
No system can guarantee a message is delivered exactly once across an unreliable network. The sender cannot distinguish a lost message from a lost acknowledgement, so it must either risk losing the message (at-most-once) or risk sending it twice (at-least-once). Everything sold as "exactly once" is at-least-once delivery plus deduplication at the receiver, inside some boundary.
Kafka is the honest example. Idempotent producers have been on by default since Kafka 3.0 (KIP-679), and transactions give exactly-once semantics for read-process-write within Kafka. The moment your consumer calls an HTTP API or writes to Postgres, you are back to at-least-once and need your own deduplication. Idempotency keys are that deduplication at the HTTP boundary.
12The transactional outbox: side effects that survive retries
Your payment handler should publish payment. so other services send the receipt and update the ledger. Publishing directly to a broker from the handler gives you two bad outcomes. Publish then crash before commit, and you announce a payment that does not exist. Commit then crash before publish, and nobody hears about a real one.
The outbox fixes this by turning the event into a row written in the same transaction as the business change. In the flow above, that is the charged → completed phase:
BEGIN;
UPDATE payments SET status = 'succeeded', psp_charge_id = $psp WHERE id = $payment_id;
INSERT INTO outbox (id, aggregatetype, aggregateid, type, payload)
VALUES (gen_random_uuid(), 'payment', $payment_id, 'payment.succeeded', $payload::jsonb);
UPDATE idempotency_keys SET state = 'completed', ... WHERE ... AND lock_token = $token;
COMMIT;A relay then ships outbox rows to the broker. Either use change data capture, such as the Debezium outbox event router, which expects exactly these column names by default, or poll with SELECT ... FOR UPDATE SKIP LOCKED LIMIT n, publish, then mark the rows sent. Both relays are at-least-once: a crash between publish and mark re-sends. The same outbox-plus-CDC pairing is how data ownership moves in a strangler fig migration. So the outbox moves the duplicate problem to the consumer, where it is solvable with an inbox table:
CREATE TABLE inbox (
consumer text NOT NULL,
message_id uuid NOT NULL, -- the outbox row's id
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, message_id)
);
-- In the consumer, in ONE transaction with its own side effects:
BEGIN;
INSERT INTO inbox (consumer, message_id) VALUES ('ledger', $msg_id)
ON CONFLICT DO NOTHING;
-- rowCount = 0 → already processed: COMMIT and ack.
-- rowCount = 1 → apply the ledger entry, then COMMIT and ack.
COMMIT;The same pattern covers inbound webhooks. Stripe and every other provider will redeliver events. Deduplicate on the provider's event ID before acting.
13Client-side rules for idempotency keys
Server-side correctness is wasted if the client generates a fresh key per attempt. It is the most common integration bug, and it silently disables the whole mechanism.
- One key per user intent, not per HTTP attempt. Generate it when the user presses "Pay", persist it with the pending operation (the checkout row, the offline queue entry), and reuse it on every retry, including after an app restart.
- A new key when the request changes. If the user edits the amount, that is a new intent. Reusing the key gets a
422, correctly. - Use high-entropy keys. UUIDv4 is the common recommendation (Stripe, Adyen). Deriving keys from a business object (a cart ID) also works and protects against double-submits, as Stripe notes, provided the derived key is unique per operation. Never put personal data in a key: it ends up in logs.
- Retry on network errors,
409and5xx; never on422. Use exponential backoff with jitter and honourRetry-After. - Treat a final
5xxas "unknown", not "failed". Reconcile through webhooks or a status lookup before telling the user the payment failed.
AWS SDKs generate and reuse client tokens automatically, so calling code is unaware of retries (source). Aim for the same in any SDK you publish, and in any mutating tool you expose on an MCP server agents can use.
14Where idempotency crosses the other layers of the stack
Idempotency looks like an application concern, but the retries come from everywhere. Service mesh and proxy retry policies (Envoy's retry_, for example) will happily re-send a POST unless someone has scoped them to idempotent routes, which makes it a Cloud & DevOps question. The stored response bodies are personal data, which makes retention and encryption a Security question. The outbox feeds change data capture, which is often also how the warehouse gets its data, so the event schema is a Data question. And a duplicate charge is a customer-support and finance problem long before it is a bug ticket. Tracing a single key across those hops is much easier with the propagation described in Anatomy of a request: one click traced through CDN, WAF, load balancer, app and database.
15The idempotency conformance test matrix
This is the asset we would want on day one: every behaviour above as a test case. Each row is one integration test against a real database, not mocks. If your implementation passes all fourteen, it handles the failure modes we know about. Concurrency rows need genuine parallelism (two connections, a barrier), not sequential calls.
| # | Scenario | Setup | Expected |
|---|---|---|---|
| 1 | First request | New key | Executes once; 2xx; key completed |
| 2 | Sequential retry | Repeat #1 with same key and body | Same status, body and Location; Idempotent-Replayed: true; no new rows |
| 3 | Same key, different body | Repeat #1, change amount |
422; no side effects |
| 4 | Same key, different route | Same key on POST / |
422 |
| 5 | Same key, different tenant | Tenant B reuses tenant A's key | Executes independently for B; A's response never returned |
| 6 | Concurrent duplicates | 20 parallel identical requests | Exactly one execution; others 409 with Retry-After or a replay |
| 7 | Retry while in flight | Hold owner at a barrier; send retry | 409; after release, retry gets replay |
| 8 | Owner crash before foreign call | Kill worker after payment_ |
Retry after lease expiry resumes; one PSP call |
| 9 | Owner crash after foreign call | Kill worker after PSP returns, before charged commits |
Resume re-calls PSP with same derived key; one charge at PSP |
| 10 | Stale owner wakes up | Pause owner past lease; second worker completes; resume first | First worker's completion UPDATE affects 0 rows and rolls back |
| 11 | Pre-execution rejection | Request returns 429 or schema 400 |
Nothing stored; same key succeeds once the cause is fixed |
| 12 | Expired key | Advance clock past expires_at (reaper not run) |
Treated as new; executes |
| 13 | Missing key on required endpoint | No header | 400 with a problem detail naming the header |
| 14 | Quoted and unquoted header | "abc" vs abc |
Treated as the same key |
Pair this with a published contract in your API reference: which endpoints require keys, the key format and maximum length, the scope, the retention window, what is replayed (and that pre-execution errors are not), and the status codes for mismatch and in-flight. The draft asks servers to publish an expiry policy; publish all of it.
16FAQ
Should an idempotency key be required or optional?
Required for anything that moves money or sends something irreversible; return 400 without it, as the IETF draft suggests. Optional elsewhere. Stripe v2 generates a key itself if none is sent; that keeps one code path, but only a key the client holds can protect a retry the client makes.
Should a replayed request return 200 or the original status code?
The original status. If the first attempt returned 201 Created, the replay returns 201 with the same body and Location, plus a header such as Idempotent-Replayed: true so clients and logs can tell the difference.
Can I use the request body hash as the idempotency key?
No. Two genuinely separate purchases of the same item for the same amount have identical bodies. The key identifies the intent; the fingerprint verifies the content. You need both.
What status code should a concurrent duplicate get, 409 or 425?
409 Conflict. That is what the IETF draft, Stripe and Adyen use. Add Retry-After so well-behaved clients back off until the original finishes.
Is the IETF Idempotency-Key header a standard?
No. draft-ietf-httpapi-idempotency-key-header reached -07 in October 2025 and expired in April 2026 without becoming an RFC. It remains a useful, widely recognised reference for header name and status codes.
Do idempotency keys make my API exactly-once?
They make duplicate execution of a keyed request impossible within the retention window, inside your database boundary. Calls to third parties need their own keys, and events need an outbox and consumer-side deduplication. Nothing makes delivery itself exactly once.