What you'll learn: By the end of this lesson you will be able to explain why a timeout makes a
POSTunsafe to retry, describe theIdempotency-Keyheader as the IETF draft defines it, design the server side (atomic claim of the key, stored response, replay, conflict and mismatch answers), say which responses to store and for how long, and read the captured output of a Spring filter that handles a lost reply, a changed body and a concurrent duplicate.
At a bank counter you hand over a transfer slip with a reference number. The teller stamps it and processes it. If the queue is long and you go away and come back with the same slip, the teller sees the stamp and points at the earlier result instead of moving the money again. If you come back with a slip with the same number but a different amount, the teller stops and asks what is going on. The reference number is the idempotency key; the stamp is the stored response.
API design covers resource and method choices. Idempotent and commutative operations gives the general design, and timeouts, retries, backoff and jitter says when a client should retry at all. This lesson is the HTTP mechanism for making a write retryable and the traps in the server side. The browser's half is client retries and backoff.
Verified with the IETF Internet-Draft draft-ietf-httpapi-idempotency-key-header-09, RFC 9110, the Stripe API reference, Spring Boot 4.1.2 and Java 25, on 2026-12-01.
The core idea
A client that cannot tell whether a POST happened must be able to send it again without it happening twice. It does so by attaching a unique key to the logical operation and sending the same key on every attempt; the server runs the operation once, stores the response under the key, and answers every repeat from the store.
Three illustrations run through the lesson: the minimal example is the Spring filter in "Build it"; the realistic example is ShopStream's order placement on a weak mobile network; the failure example is a duplicate that arrives while the first request is still running.
Why a timeout is not an answer
RFC 9110 defines a method as idempotent if the intended effect of several identical requests is the same as that of one, and says PUT, DELETE and the safe methods are. POST is not on the list. It adds that a client should not automatically retry a non-idempotent request unless it knows the request is effectively idempotent or can detect that the original was never applied.
A timeout gives the client neither piece of knowledge. The server may have done the work and the reply may have been lost.
Figure 1. The retry that duplicates. How to read this: the work happened once, but the client cannot see it. The key lets the server recognise the second request as a repeat of the first.
The header, as the draft describes it
The Idempotency-Key header is described in an IETF Internet-Draft of the HTTPAPI working group. At the time of writing it is version 09, a work in progress and not an RFC; the draft itself says that Internet-Drafts should be cited only as work in progress. What it says:
- The key is "a unique value generated by the client which the resource uses to recognize subsequent retries", and the header is a Structured Field string, such as
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324". - The key must be unique and must not be reused with a different request payload. A UUID or similar random identifier is recommended.
- A missing key on an operation that requires one: the server should reply 400. The key reused with a different payload: 422. A retry while the original is still processing: 409.
- A server may store a fingerprint of the request with the key, and fail a request whose fingerprint differs. It should publish its key expiration policy.
- Security: validate the key format before using it in a cache lookup, and include client-specific attributes in the lookup so low-entropy keys cannot fetch another client's result.
The draft does not require a header to mark a replay; the lab's Idempotent-Replayed: true is its own addition. A real server also documents which operations honour the key, because a client cannot assume any server does.
The server side
The filter runs before the controller. It needs four things.
- An atomic claim. The first request with a key must win and all others must see that. Checking the store and then writing to it is a race: two requests both see nothing and both run. The store's
beginmust be one atomic step. - A fingerprint. Compare method, path and body with what the key first came with. The same key with a different body is a client bug and must not return the first result.
- A scope. Key by caller and key, never the key alone, so one client cannot read another's response.
- A stored response, written when the operation finishes, so a repeat can be answered without running anything.
Figure 2. The states of one key. How to read this: a repeat in InProgress gets 409, a repeat in Completed gets the stored response, and a different body in either state gets 422.
Figure 3. Everything that repeats stops at the filter. How to read this: only a request that wins the claim reaches the controller and the payment; the rest are answered from the store or refused.
What to store, and for how long
Store the response of any request that actually ran to a conclusion, success or a client error. A server error is a harder choice. Stripe's API v1 saves the status code and body of the first request after execution begins and returns the saved response on retries "including 500 errors"; it saves nothing when validation fails or a concurrent request conflicts, and says keys can be removed after at least 24 hours. The lab chooses the other policy for 5xx, releasing the key so a retry runs again, because its 5xx responses mean the work did not complete. Both are defensible; what matters is that the policy is written down and that the operation is safe to run again after a 5xx. Retention is a trade-off: long enough to cover a client's retry window, short enough that the store does not grow without bound.
What the key does not protect
The key protects the HTTP request. It does not make everything the handler does safe.
- A crash between the effect and the stored response. If the payment is taken and the process dies before the response is stored, the retry runs the payment again. The lasting fix is to record the key in the same database transaction as the effect (a unique constraint), see Spring
@Transactional, or to pass a key on to the downstream call. - An in-memory store. It is lost on restart and not shared between instances. A real deployment needs a shared store with an atomic insert.
- A key stuck in progress. If the first request dies without releasing the key, repeats get 409 forever unless an in-progress entry has a lease.
- Message consumers. The same idea applies to a consumer that sees a message twice; see delivery guarantees.
Build it: an Idempotency-Key filter in Spring
This is the minimal example. Goal: make POST /orders retry-safe and see each outcome. Not a real service: the controller and the filter run behind MockMvc (no network), the store is an in-memory ConcurrentHashMap (InMemoryIdempotencyStore), the payment provider is a counter, and the client identity comes from an X-Client-Id header standing in for authentication.
Setup. From the repository (Docker is not needed):
cd examples/spring-labs
./gradlew :labs:idempotency-keys:test
It runs 11 tests, one of which compares the report below with the golden file examples/spring-labs/golden/idempotency-keys.txt. The code is in examples/spring-labs/labs/idempotency-keys/. The atomic claim is one compute call on the map, and the filter turns its four outcomes into responses:
entries.compute(scopedKey, (key, existing) -> {
Instant now = clock.instant();
if (existing == null || (existing.response() != null && !existing.createdAt().plus(ttl).isAfter(now))) {
outcome.set(new Started());
return new Entry(fingerprint, null, now);
}
if (!existing.fingerprint().equals(fingerprint)) {
outcome.set(new Mismatch());
} else if (existing.response() == null) {
outcome.set(new InProgress());
} else {
outcome.set(new Replay(existing.response()));
}
return existing;
});
switch (store.begin(scopedKey, fingerprint)) {
case IdempotencyStore.Started started -> execute(scopedKey, cached, response, chain);
case IdempotencyStore.Replay replay -> replay(replay.response(), response);
case IdempotencyStore.InProgress inProgress ->
problem(response, 409, "A request with this Idempotency-Key is still being processed");
case IdempotencyStore.Mismatch mismatch ->
problem(response, 422, "This Idempotency-Key was already used with a different request");
}
The key is parsed as a quoted string of up to 64 letters, digits, - and _, which is a small subset of a Structured Field string; the body is read once (CachedBodyRequest) so it can be fingerprinted with SHA-256.
Scenarios 1 and 2: the lost reply, without and with the filter. Without it the retry creates a second order and takes a second payment. With it the retry returns the first response, marked as replayed.
Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, 2026-12-01):
== 1. Without the filter: the client times out and retries, and the order is created twice
attempt 1 (reply lost on the way back): 201 {"orderId":"ord-1"}
attempt 2 (the retry): 201 {"orderId":"ord-2"}
orders created: 2, payments captured: 2
== 2. With the filter: the retry gets the first response back and nothing runs twice
attempt 1 (reply lost on the way back): 201 {"orderId":"ord-1"}
attempt 2 (the retry): 201 {"orderId":"ord-1"} [Idempotent-Replayed: true]
orders created: 1, payments captured: 1
Scenario 3: a changed body. The same key with a different quantity is refused with 422 and nothing runs; the original body still replays.
Expected output, captured from a real run (the same run):
== 3. The same key with a different body is refused, not replayed
first request (qty 2): 201 {"orderId":"ord-1"}
same key, qty 20: 422 {"status":422,"title":"This Idempotency-Key was already used with a different request"}
same key, same body: 201 {"orderId":"ord-1"} [Idempotent-Replayed: true]
orders created: 1, payments captured: 1
Scenarios 4 and 5: duplicates at the same time. In scenario 4 a latch holds the first request inside the payment call; the duplicate gets 409; after the first finishes, a retry replays. In scenario 5 eight threads send the same request at once. Which of them see 409 and which see a replay depends on timing, so the report prints only what cannot vary: one order, one payment, and every reply 201 or 409.
Expected output, captured from a real run (the same run):
== 4. A duplicate that arrives while the first request is still running
first request is inside the payment call
duplicate while it runs: 409 {"status":409,"title":"A request with this Idempotency-Key is still being processed"}
first request finishes: 201 {"orderId":"ord-1"}
retry after it finished: 201 {"orderId":"ord-1"} [Idempotent-Replayed: true]
orders created: 1, payments captured: 1
== 5. Eight clients send the same request at the same moment
replies: 8
every reply is 201 or 409: true
the distinct 201 bodies: [{"orderId":"ord-1"}]
orders created: 1, payments captured: 1
Scenarios 6 and 7: bad keys and server errors. When the lab requires a key, a missing or malformed one gets 400 and nothing runs. A 503 from the payment provider is not stored: the retry runs, succeeds, and the next retry replays.
Expected output, captured from a real run (the same run):
== 6. A key the server requires, and a key that is not well formed
no Idempotency-Key header: 400 {"status":400,"title":"Idempotency-Key header is required"}
key without the quotes: 400 {"status":400,"title":"Idempotency-Key must be a quoted string of 1 to 64 letters, digits, - or _"}
key with a space inside: 400 {"status":400,"title":"Idempotency-Key must be a quoted string of 1 to 64 letters, digits, - or _"}
a well-formed key: 201 {"orderId":"ord-1"}
orders created: 1, payments captured: 1
== 7. A server error is not stored, so the retry runs
attempt 1 (payment provider down): 503 {"status":503,"title":"payment provider unavailable"}
attempt 2 (the retry): 201 {"orderId":"ord-1"}
attempt 3 (another retry): 201 {"orderId":"ord-1"} [Idempotent-Replayed: true]
payment attempts: 2
orders created: 1, payments captured: 1
Scenarios 8 and 9: scope and retention. Two clients can pick the same key without seeing each other's orders. A stored key replays at 23 hours and is forgotten at 25, so the same request creates a second order; the 24 hours is an illustrative choice of the lab, not a recommendation.
Expected output, captured from a real run (the same run):
== 8. Keys are scoped to the caller: two clients may pick the same key
client alice, key k-8: 201 {"orderId":"ord-1"}
client bob, key k-8: 201 {"orderId":"ord-2"}
client alice retries: 201 {"orderId":"ord-1"} [Idempotent-Replayed: true]
orders created: 2, payments captured: 2
== 9. A stored key is kept for a limited time (24 hours here, an illustrative choice)
t+0h: 201 {"orderId":"ord-1"}
t+23h: 201 {"orderId":"ord-1"} [Idempotent-Replayed: true]
t+25h: 201 {"orderId":"ord-2"}
orders created: 2, payments captured: 2
Break it. In IdempotencyFilter, make the Replay case call chain.doFilter(...) instead of replay(...): the replay test fails because two orders exist. Restore it and re-run.
Left out: a shared or durable store, a lease for in-progress keys, Problem Details bodies, PATCH-specific cases, fingerprints of normalised JSON, and any real database or payment provider.
Trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| Key plus stored response | Retries are safe and cheap | A store, an expiry policy, a race to get right | Your operation is already naturally idempotent (PUT) |
| Store 5xx responses | The client always sees the first outcome | A transient error can be replayed for the whole retention window | The error was a temporary fault you want retried |
| Release the key on 5xx | A retry can succeed | The operation must be safe to run twice after a failure | The handler can fail after a side effect |
| Fingerprint the body | Catches a reused key with changed input | Hashing cost; reordered JSON counts as different | Clients reserialise bodies between retries |
| Short retention | Small store | A late retry runs again | Clients retry for longer than the window |
In practice: placing an order on a weak mobile network
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company, and every number is illustrative.
This is a realistic scenario, not a case history.
The situation
The ShopStream mobile app places an order with POST /orders. On a weak connection the app often times out after the server has created the order, and its retry code sends the request again. Support sees customers with two identical orders and two payments.
Starting architecture
Figure 4. The order path. How to read this: the app's retry reaches the API a second time; the database and the payment adapter must each see the operation once.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
| A. Stop the app retrying | No duplicates from retries | Users lose orders on a bad network |
| B. Deduplicate by cart contents | No client change | Two real identical orders are merged |
| C. A key per checkout attempt, stored by the API | The retry returns the first result | A store and a race to get right |
The decision
Option C. The app generates a random key when the user taps "Place order" and reuses it for every retry of that tap, and a new key for a new tap. The API claims the key with a unique insert in the same database transaction as the order, stores the response, replays it on a repeat, answers 409 while the first is running and 422 for a changed body. The retention window is set longer than the app's longest retry window (illustrative: a day).
Rollout and verification
A rollout would first run the lab's scenarios against the real API with a test client: a repeat, a changed body and two simultaneous requests, checking the order count each time. In production the checks are counts: replays per hour, 409s per hour, 422s per hour (each a client bug), and duplicate orders per customer, which should fall to zero.
The 2 a.m. failure
The page says orders are stuck: customers get 409 on every retry. A deploy killed an API pod while it was handling checkouts, and their keys stayed in progress with no one to finish them. The checks are the age of in-progress keys and the pods that restarted. The mitigation is to delete the stuck keys by hand. The lasting fix is a lease: an in-progress key older than the longest legitimate request is treated as abandoned, and the order insert and the key share one transaction so a crash leaves neither half behind.
Architect's notes
- Make the client generate the key once per user intent, and reuse it for every retry of that intent.
- Claim atomically. Check-then-insert is a race.
- Scope by caller and fingerprint the body.
- Write down what is stored (including 5xx) and for how long.
- Put the key in the same transaction as the effect wherever you can.
Common mistakes
- A new key for every retry. That defeats the purpose.
- Checking the store, then writing it. Two simultaneous requests both run.
- Replaying a response to a different body. Compare a fingerprint.
- Keys not scoped to the caller. One client may read another's response.
- No expiry. The store grows for ever; and an in-progress key with no lease blocks forever.
- Assuming the key protects downstream calls. It protects only the request it guards.
Key takeaways
- A timeout does not say whether a
POSThappened, so a retry needs a key. - The
Idempotency-Keyheader is an IETF draft (version 09 at the time of writing), not an RFC. - The server claims the key atomically, runs once, stores the response, and replays it.
- Repeat while running: 409. Same key, different payload: 422. Required key missing: 400.
- Decide whether to store 5xx, and how long to keep keys.
- A key guards the request; use a transaction or a downstream key to guard the effect.
Practice exercises
Exercise 1 (20 min). For POST /transfers, PUT /profile and DELETE /orders/7, say which need a key and why.
Exercise 2 (45 min). Run the lab. Make the 5xx policy "store it" and say which scenario changes and how.
Exercise 3 (1 hour). Replace the map in InMemoryIdempotencyStore with an H2 table with a unique key column, keeping the same four outcomes, and run the same scenarios.
Related reading
- Idempotent and commutative operations: the general design and the key contract.
- Timeouts, retries, backoff and jitter: when and how often to retry.
- Client retries and backoff: the browser's side, with the key generated once per action.
- Delivery guarantees: the same problem for message consumers.
The other side of this topic is the client: it creates the key when the user acts, keeps it across every attempt of that action, and stops retrying when the user cancels.
Official documentation
- IETF HTTPAPI working group, The Idempotency-Key HTTP Header Field (Internet-Draft, version 09, work in progress).
- IETF, RFC 9110: HTTP Semantics, section 9.2.2 Idempotent Methods.
- Stripe, Idempotent requests.
- Spring Framework, Filters in Spring MVC.