Designing Idempotency Keys in Practice — the IETF draft, PostgreSQL locking, and retry policy
How to stop one timeout from becoming a double charge: Idempotency-Key designed against the IETF draft draft-ietf-httpapi-idempotency-key-header-09 (2026-11-21) — its syntax, fingerprints, and error codes (400, 409, 422). A PostgreSQL table and the ON CONFLICT claim that settles concurrent requests in one statement, Spring Boot code, when to put the key in the same transaction versus committing it separately, what to store for 4xx and 5xx, lease expiry and takeover, the trap of putting Redis in front, retention as Stripe and Adyen do it, and the client bug that breaks everything — a new UUID on every retry.
- Draft
- -09 2026.11.21
- Concurrent retry
- 409 Conflict
- Key reuse
- 422 Unprocessable
- The line
- Unique index is the lock
One timeout, two possible facts
Take an API that creates an order through POST /orders. The client sends the request and waits 30 seconds with no response. Everything the client knows is one word: unknown.
- The server may never have received it — so it should be sent again.
- The server may have created the order and committed, and only the response was lost — so sending it again creates a second order.
This ambiguity appears whenever the network hiccups. Not retrying loses orders; retrying duplicates them. Both options are bad because POST is not idempotent by definition. RFC 9110 defines OPTIONS, HEAD, GET, PUT and DELETE as idempotent, and POST and PATCH as not (RFC 9110).
The fix is for the server to recognize “this is that earlier request”. The client generates a key once per user intent and sends it in a header; the server remembers the request and its result under that key. The IETF HTTPAPI working group is writing this down, and the newest revision is draft-ietf-httpapi-idempotency-key-header-09, published 21 November 2026.
What the draft settles, and what it leaves to you
The draft is a 14-page WG document (Standards Track target, expires 25 May 2027). Five things in the text matter for production.
| Item | What the draft says |
|---|---|
| Syntax | Idempotency-Key is an Item Structured Header Field (RFC 9651); its value MUST be a String |
| Uniqueness | The key MUST be unique and MUST NOT be reused with a different payload. UUIDs (RFC 9562) are recommended |
| Fingerprint | A server MAY store a fingerprint of the payload with the key to detect a key reused for a different request |
| Expiry | The resource SHOULD define and publish an expiration policy |
| Errors | Missing key 400, same key with a different payload 422, retry while the original is still running 409 |
Two consequences matter in practice.
First, the value is a String, so quotes are the canonical form. In structured field syntax a string is double-quoted:
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"
The draft’s own examples look like this. Existing APIs such as Stripe and Adyen have always accepted the bare token, though, so accept both on the way in, and store the value with the quotes stripped. If you are writing the client, follow the draft and quote it.
Second, the draft does not define a header that says “this was a replay”. Returning the same status code and body as the original is all it asks; anything beyond that is your call. I add Idempotent-Replayed: true to replayed responses, because it makes the difference between “I am seeing the first response” and “I am seeing the cached one” visible in logs.
The whole round trip looks like this.
sequenceDiagram
autonumber
participant C as Client
participant A as API server
participant D as PostgreSQL
participant P as Payment provider
C->>A: POST /orders + Idempotency-Key
A->>D: claim the key (INSERT ... ON CONFLICT DO NOTHING)
D-->>A: 1 row = this request owns the key
A->>P: authorize
P-->>A: approved
A->>D: state=completed, store the response
A-->>C: 201 Created
Note over C,A: response lost (client timeout)
C->>A: retry with the same key
A->>D: look up the same key
D-->>A: completed + stored response
A-->>C: 201 Created (replay, one charge)
The 409 in the draft is for a retry that arrives between lines 3 and 6 in that diagram. While the original request is still waiting on the payment provider, the server has to say “one request with this key is already in flight”.
One PostgreSQL table does the job
The most common mistake in an idempotency store is check, then insert.
-- Don't do this
SELECT ... FROM idempotency_key WHERE key = ?; -- no rows
INSERT INTO idempotency_key ...; -- two requests arrive here together
Two requests that look at the same instant both see “no rows” and both insert. Application code cannot close that window. A unique constraint is the only reliable arbiter.
CREATE TABLE idempotency_key (
scope text NOT NULL, -- tenant + API credential
key text NOT NULL, -- what the client sent (quotes stripped)
fingerprint bytea NOT NULL, -- SHA-256 of method + path + canonical body
state text NOT NULL DEFAULT 'in_progress'
CHECK (state IN ('in_progress', 'completed')),
locked_at timestamptz NOT NULL DEFAULT now(), -- lease start
response_status int,
response_content_type text,
response_body bytea,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (scope, key)
);
-- for the expiry job
CREATE INDEX idempotency_key_expires_at ON idempotency_key (created_at);
Four details in that schema are load-bearing.
PRIMARY KEY (scope, key): a unique index on the key alone lets tenant A guess tenant B’s key and read someone else’s response. A composite key is exactly what the draft’s Security Considerations recommend. Put the tenant ID and the API credential inscope.fingerprintasbytea: storing the hash as a hex string doubles its size. SHA-256 is 32 bytes.locked_atas a watchdog: if the worker holding the key dies, the row sits inin_progressforever. Give it a lease, and let another request take over once the lease is stale.- Store the response body too: with only the status code, a client that retries gets
201and noid. Store theContent-Typealongside it.
Claiming a key is one statement.
INSERT INTO idempotency_key (scope, key, fingerprint)
VALUES (:scope, :key, :fp)
ON CONFLICT (scope, key) DO NOTHING;
If one row comes back, this request owns the key. If zero, someone got there first and you have to read the existing row. PostgreSQL’s behaviour matters here: when an insert with the same key is still uncommitted, the second INSERT waits rather than guessing. That keeps “still running” and “already done” from blurring together. The wait holds a connection, though, so keep the claim in a short transaction and do the real work outside it.
The decision tree has four leaves.
flowchart TD
S["POST / PATCH + Idempotency-Key"] --> V{"header valid?"}
V -- "no" --> E400["400 + application/problem+json"]
V -- "yes" --> I["INSERT ... ON CONFLICT DO NOTHING"]
I --> R{"1 row inserted?"}
R -- "yes" --> RUN["run the work"]
R -- "no" --> SEL["lock and read the existing row (FOR UPDATE)"]
SEL --> F{"fingerprint matches?"}
F -- "no" --> E422["422 key already used"]
F -- "yes" --> ST{"state"}
ST -- "completed" --> REP["replay the stored status and body"]
ST -- "in_progress, lease valid" --> E409["409 + Retry-After"]
ST -- "in_progress, lease expired" --> RUN
The order of that tree is not arbitrary. Check the fingerprint before the state. Reverse them and a client that reused a key for a different request gets someone else’s response. The draft says the same thing: on a mismatch, do not return the result of the original request.
Spring Boot implementation
In Spring MVC the least invasive place is a OncePerRequestFilter. Once @RequestBody has deserialized the body, the original bytes are gone, so wrap the request in the filter and compute the fingerprint there.
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class IdempotencyFilter extends OncePerRequestFilter {
private static final Set<String> METHODS = Set.of("POST", "PATCH");
private final IdempotencyStore store;
public IdempotencyFilter(IdempotencyStore store) {
this.store = store;
}
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String header = req.getHeader("Idempotency-Key");
if (header == null || !METHODS.contains(req.getMethod())) {
chain.doFilter(req, res);
return;
}
String key = IdempotencyKeys.normalize(header); // strip quotes, check length and charset
if (key == null) {
writeProblem(res, 400, "Idempotency-Key is malformed");
return;
}
var request = new ContentCachingRequestWrapper(req, 1_048_576);
byte[] body = request.getInputStream().readAllBytes(); // cached, so the controller can read it again
byte[] fp = IdempotencyKeys.fingerprint(req.getMethod(), req.getRequestURI(), body);
String scope = IdempotencyKeys.scopeOf(req); // tenant + credential
switch (store.claim(scope, key, fp)) {
case IdempotencyStore.Replay r -> {
res.setStatus(r.status());
if (r.contentType() != null) res.setContentType(r.contentType());
res.setHeader("Idempotent-Replayed", "true");
res.getOutputStream().write(r.body());
}
case IdempotencyStore.InProgress ignored ->
writeProblem(res, 409, "A request is outstanding for this Idempotency-Key");
case IdempotencyStore.Mismatch ignored ->
writeProblem(res, 422, "Idempotency-Key is already used");
case IdempotencyStore.Proceed ignored -> {
var response = new ContentCachingResponseWrapper(res);
chain.doFilter(request, response); // controller and service run here
byte[] out = response.getContentAsByteArray(); // copy before it goes out
int status = response.getStatus();
if (status < 500) {
store.complete(scope, key, status, response.getContentType(), out);
} else {
store.release(scope, key); // only when there is certainly no side effect
}
response.copyBodyToResponse(); // actually write to the client
}
}
}
}
Note the cache limit passed to ContentCachingRequestWrapper. Past that limit the cached body is truncated, and the fingerprint no longer matches the real payload. If your API accepts large uploads, check Content-Length in front of the filter and reject with 413, or compute the fingerprint from fields instead of raw bytes.
The store is two short transactional methods.
@Component
public class IdempotencyStore {
public sealed interface Claim permits Proceed, Replay, InProgress, Mismatch {}
public record Proceed() implements Claim {}
public record Replay(int status, String contentType, byte[] body) implements Claim {}
public record InProgress() implements Claim {}
public record Mismatch() implements Claim {}
private static final Duration LEASE = Duration.ofSeconds(30);
private final JdbcClient jdbc;
private final TransactionTemplate tx;
public Claim claim(String scope, String key, byte[] fp) {
int inserted = jdbc.sql("""
INSERT INTO idempotency_key (scope, key, fingerprint)
VALUES (:scope, :key, :fp)
ON CONFLICT (scope, key) DO NOTHING
""")
.param("scope", scope).param("key", key).param("fp", fp)
.update();
if (inserted == 1) return new Proceed();
return tx.execute(t -> {
var row = jdbc.sql("""
SELECT fingerprint, state, locked_at,
response_status, response_content_type, response_body
FROM idempotency_key
WHERE scope = :scope AND key = :key
FOR UPDATE
""")
.param("scope", scope).param("key", key)
.query(KeyRow.class).optional().orElse(null);
if (row == null) return new Proceed(); // raced with the cleanup job
if (!MessageDigest.isEqual(row.fingerprint(), fp)) return new Mismatch();
if ("completed".equals(row.state()))
return new Replay(row.responseStatus(), row.responseContentType(), row.responseBody());
if (row.lockedAt().isAfter(Instant.now().minus(LEASE))) return new InProgress();
jdbc.sql("UPDATE idempotency_key SET locked_at = now() WHERE scope = :scope AND key = :key")
.param("scope", scope).param("key", key).update();
return new Proceed(); // take over a dead request's key
});
}
}
That row == null branch really does happen, rarely: the expiry job deleted the row between your INSERT and your SELECT. Retry from the INSERT (three attempts is plenty). Without the retry you get a request that can neither find a key nor be processed.
Same transaction, or commit separately?
This is where designs diverge most. The answer depends on how far the side effects reach outside the database.
| Side effect | Recommendation | Why |
|---|---|---|
| Database writes only (orders, posts, points) | One transaction: claim → work → store response → commit | A rollback removes the key row too, so a retry re-executes immediately. No window of doubt exists |
| External call (payment, shipping, SMS) | Commit the claim → call out → commit the response | You cannot roll back an external call. If the worker dies, the lease expires and someone takes over |
With the first shape you drop the filter’s claim and wrap all three steps in a TransactionTemplate inside the service.
public OrderResponse create(Long tenantId, String key, CreateOrderRequest req) {
byte[] fp = IdempotencyKeys.fingerprint("POST", "/orders", req);
return tx.execute(t -> {
var claim = store.claimInTx(tenantId, key, fp); // INSERT in this same transaction
if (claim instanceof IdempotencyStore.Replay r) return r.asOrderResponse();
if (claim instanceof IdempotencyStore.InProgress) throw new IdempotencyConflictException();
if (claim instanceof IdempotencyStore.Mismatch) throw new IdempotencyMismatchException();
OrderResponse created = orderService.place(tenantId, req); // the actual work
store.completeInTx(tenantId, key, 201, created); // response stored with it
return created;
});
}
The advantage is that there is no state where the order exists but the key does not, because both land in the same commit. With an external payment in the middle, that is impossible.
When an external call is involved, treat the key as a small workflow. This is the shape Brandur Leach described for Stripe. Keep a recovery_point column (started → payment_authorized → completed) so a request that takes over knows whether to start over or resume after the authorization. Takeover needs care.
An expired lease means the worker was slow, not that it is dead. A stalled worker can wake up and authorize the payment, and if the new owner authorizes it too, the customer is charged twice. Always send your own idempotency key to the payment provider as well (most of them accept
Idempotency-Key). Then even if your key is processed twice, the charge happens once.
The lifecycle fits in one state diagram.
stateDiagram-v2
state "in progress" as IP
state "completed" as DONE
[*] --> IP: first use of the key
IP --> DONE: response stored
IP --> IP: takeover after lease expiry
DONE --> [*]: deleted after retention
Should you store 5xx and 4xx?
Once you decide to store responses, it is tempting to store all of them. A careless policy means clients replay a permanently failing response forever.
| Result | Store | On retry |
|---|---|---|
| 2xx | yes | replay the stored status and body verbatim |
| 4xx — request validation failed (400, 422) | no | the same key is validated again |
| 4xx — business rejection (out of stock) | your call | storing gives the same answer; I would store it |
| 429, 503 | no | the server never processed the request, so retrying is fine |
| 5xx | no (or wait for the lease) | re-execute only after confirming there was no side effect |
Stripe’s v1 API chooses differently: once endpoint execution has begun, it stores even a 500 and returns that 500 to retries with the same key. Requests that never started executing — validation failures, concurrent conflicts — are not stored. Either way the underlying rule is the same: store based on whether execution started.
Do not store 409 or 422. They are facts about the moment, not results. A 409 disappears in seconds, and a 422 says the client misused the key.
Putting Redis in front
If lookups get heavy, Redis in front is tempting. It works, but Redis must not be the source of truth.
# the familiar shape
SET idem:{tenant}:{key} "in_progress" NX PX 30000
That line is atomic and blocks concurrent requests well. The problems start after it.
- If the TTL is shorter than the processing time, the second request gets through and runs again. When processing time varies, no TTL is long enough forever.
- If Redis restarts or fails over, keys disappear. Depending on AOF/RDB settings that can be seconds to tens of seconds of writes, and a retry in that window duplicates the work.
- Storing response bodies is awkward. Once replay bodies live in Redis, its eviction policy becomes your API contract.
So production systems use two tiers. Redis is the fast first filter (keeping a retry storm away from the database), and the PostgreSQL unique constraint makes the final call. When NX fails in Redis, return 409 straight away, but when the database row says completed, replay the response. If Redis is wiped entirely, the database is still the backstop.
If you only need to deduplicate inside one instance — preventing a batch job from running twice, say — Redis alone is enough. Even then, size the TTL like “max processing time × 3” and measure the processing time.
How real APIs do it
| Stripe API v1 | Stripe API v2 | Adyen | IETF draft-09 | |
|---|---|---|---|---|
| Header | Idempotency-Key |
Idempotency-Key |
idempotency-key |
Idempotency-Key (String) |
| Retention | 24 hours | 30 days | 7–14 days | published by the server |
| Methods | POST (DELETE has no effect) |
POST, DELETE |
POST |
POST, PATCH |
| Retry, same key | replay the first response, including 500 | resume failed work, return an updated response | return the first response | a response consistent with the intent |
| Retry while in flight | — | — | 409/422, error code 704 |
409 |
| Key reuse, different body | error | — | — | 422 |
| Key length | 255 chars | 255 chars | 64 chars | server-defined |
There is a way to read this table. The retention window is the retry window. 24 hours fits a payment API; 30 days reflects v2 clients that may retry far more slowly. Adyen keeps 7–14 days and enforces key uniqueness per company account, which is the draft’s scope idea applied for real.
Adyen’s documentation contains one very practical sentence: when two requests with the same key arrive together, one is processed and the other gets a transient error, and that response carries a transient-error: true header meaning “you may retry later with the same key”. An API that just throws 409 and says nothing about when to come back makes the client guess. Retry-After, or an explicit signal like Adyen’s, is better.
Where clients break it
No server design survives a client that generates a new UUID on every retry. This is more common than it sounds: UUID.randomUUID() inside the retry loop, or a mobile app that dies after sending and creates a new key on relaunch.
Three rules for the client.
- One key per user intent. Generate it when the user presses “Pay”, and keep using it until a successful response arrives.
- Persist it before sending. If the app dies, it has to reuse the same key. Keep
(intent, key)inlocalStorageor SQLite and delete it on success. - Retry with exponential backoff and jitter. A retry storm keeps a broken server down longer.
Among 4xx, 409 means “retry later” and 422 means do not retry — generate a new key instead. 400 means the key was missing, which is a client bug.
Remaining traps
Fingerprint canonicalization. If two identical requests produce different fingerprints, a legitimate retry gets rejected with 422. The usual causes: JSON object key order, omitted defaults (currency omitted vs "USD" spelled out), and timestamps the client adds on every attempt. Two approaches.
- Hash the raw bytes: simple, and the body is preserved exactly. The cost is that a different key order becomes a different request.
- Hash a canonical form: serialize the DTO with a fixed field order, apply defaults, then hash. Put per-attempt fields such as timestamps on an exclusion list.
For a small service, start with the raw hash and move to canonicalization once 422s show up in practice.
What goes into the fingerprint. The draft only says “the payload”. In practice hash method + path + body. Without the path, the same key can be used against /orders and /refunds, and then one kind of request replays the other’s response. The same reasoning puts the tenant in scope.
Never put personal data in the key. An email or phone number as a key ends up in logs and monitoring forever. The draft recommends UUIDs.
Do not send it on GET or DELETE. They are already idempotent, and storing them just wastes space.
An idempotency key is not exactly-once. It prevents duplicate execution within the client’s retry window. Internal async consumers — a Kafka consumer, a batch job — processing the same event twice is a different problem, solved with event-ID deduplication or the outbox pattern. Idempotency keys solve one narrow problem, “retried HTTP requests”, extremely well.
Gateway retries must reuse the key. If a load balancer or service mesh retries automatically on 5xx with a fresh key, duplicates appear in front of your application. Check that every retrying layer preserves the original headers.
Expiry and cleanup
Keys accumulate forever. At 100 payment requests per second that is 8.6 million rows a day and 260 million a month. Two strategies.
- Batched delete: loop
DELETE FROM idempotency_key WHERE created_at < now() - interval '24 hours' LIMIT 10000;. Thecreated_atindex is required, andLIMITkeeps each lock short. - Partitioning: partition daily on
created_atandDROPold partitions. No vacuum debt from mass deletes, which is much easier to operate.
Either way, publish the retention period in the API docs. The draft asks for it (RECOMMENDED), and clients need to know how long they may retry with the same key.
Checklist
- Is the unique constraint
(scope, key), with tenant and credential inscope? - Do you claim with
INSERT ... ON CONFLICTrather than select-then-insert? - Do you check the fingerprint before the state?
- Does
in_progresscarry a lease, and is there a path that takes over an expired key? - Do you store the response body, not just the status? And the
Content-Type? - Do you skip storing 5xx, with a policy consistently keyed on “did execution start”?
- Does the 409 carry
Retry-Afteror another signal that retrying is allowed? - Do you send a separate idempotency key to the payment provider?
- Does the client keep the key across retries, and across app restarts?
- Is there an expiry policy, and is it documented?
An idempotency key is not exotic. One table, one unique constraint, and one question — “did execution start?” — cover most of it. But drop any one of the three and you get silent double charges, and by then it is too late.
Comments