Idempotency Keys for Reliable HTTP APIs: Semantics, Storage, and Failure Recovery
Design key scope, request fingerprints and response replay.
How idempotency keys make retried HTTP requests safe: what the key names, how the server claims it atomically, when to replay or reject, and how to recover when the outcome is unknown.
At a glance
- A client sends a unique key per logical operation; the server treats every request with that key as the same operation.
- Claim the key atomically before the side effect, with a unique constraint on (tenant, operation, key). Check-then-insert races.
- Store a fingerprint of the request: the same key with a different body is misuse and must be rejected, not replayed.
- After success, replay the original outcome (same status, same order ID) instead of running the operation again.
- A timeout, a lost response or an expired worker lease does not prove the first attempt had no effect. Reconcile before re-executing.
PUT,DELETEand safe methods are idempotent by definition;POSTis not, which is why it needs a key.
What the server does with a key
| Incoming request | Key known? | Same fingerprint? | Response |
|---|---|---|---|
| First use | no | - | claim the key atomically, then run the operation |
| Retry after success | yes | yes | replay the original response |
| Retry while the first is still running | yes | yes | 409, or 202 "in progress", or wait (the API's contract decides) |
| Same key, different request | yes | no | reject as misuse, for example 422 or 409 |
| Key past its retention window | - | - | treat as new, or reject if duplicates are not acceptable |
| Key store unavailable | - | - | fail closed for operations with side effects |
Claim, replay and reject
using System.Collections.Concurrent;
var api = new OrderApi();
Console.WriteLine($"first: {api.Create("tenant-A", "key-K", "2 x book")}");
Console.WriteLine($"retry: {api.Create("tenant-A", "key-K", "2 x book")}");
Console.WriteLine($"other body: {api.Create("tenant-A", "key-K", "5 x book")}");
Console.WriteLine($"tenant-B: {api.Create("tenant-B", "key-K", "2 x book")}"); // keys are scoped per tenant
Console.WriteLine($"orders created for tenant-A, key-K: {api.Executions("tenant-A", "key-K")}");
await Task.WhenAll(Task.Run(() => api.Create("tenant-A", "key-L", "1 x pen")),
Task.Run(() => api.Create("tenant-A", "key-L", "1 x pen")));
Console.WriteLine($"orders created for key-L by two concurrent requests: {api.Executions("tenant-A", "key-L")}");
sealed class OrderApi // in memory for the example; a real store is durable, with a unique constraint
{
readonly ConcurrentDictionary<(string Tenant, string Key), (string Fingerprint, Lazy<string> Response)> claims = new();
readonly ConcurrentDictionary<(string, string), int> executions = new();
int lastOrderId;
public string Create(string tenant, string key, string body)
{
var claim = claims.GetOrAdd((tenant, key), _ => (body, new Lazy<string>(() =>
{
executions.AddOrUpdate((tenant, key), 1, (_, n) => n + 1); // the side effect: create the order
return $"201 order {Interlocked.Increment(ref lastOrderId)}";
})));
return claim.Fingerprint == body ? claim.Response.Value : "422 key reused with a different request";
}
public int Executions(string tenant, string key) => executions.GetValueOrDefault((tenant, key));
}first: 201 order 1 retry: 201 order 1 other body: 422 key reused with a different request tenant-B: 201 order 2 orders created for tenant-A, key-K: 1 orders created for key-L by two concurrent requests: 1
- The retry gets the stored first response back, word for word, and the order is created once.
GetOrAddcan run its factory twice under a race, but only one stored entry wins, and itsLazy<string>runs the side effect once.- The fingerprint here is the raw body. A real rule compares what changes business meaning (the stored payload, chosen fields, or a hash of a canonical form, with formatting and defaults normalized), and records a version for the rule itself.
- An in-memory dictionary works for one process only. Across replicas, the claim must live in a shared, durable store.
The dangerous case: the outcome is unknown
- Worker A claims key K in the key store, then commits order 731 in the database.
- A crashes before it records the result next to K. The store still says "pending".
- The client retries with K. Worker B sees "pending" and the lease has expired.
- Running the order again would create a second one. B must first look for the order through a durable operation ID linked to K, then replay order 731, or keep the request marked as outcome-unknown.
If the key record and the order live in one database, commit both in one transaction. A call to another service over HTTP cannot be rolled back that way: give it its own stable operation ID that it deduplicates, and reconcile.
What to store
| Field | Why |
|---|---|
| tenant, operation, key (unique together) | the atomic claim, scoped so one tenant's key never matches another's |
| fingerprint and its version | detect a reused key with a different request |
| state: pending, succeeded, failed-before-effect, outcome-unknown | a single "failed" flag cannot say whether a retry is safe |
| the business ID (order, charge) | replay the same outcome; reconcile after a crash |
| response status and body (or a pointer) | replay what the first call returned |
| created and expiry times | the retention window |
Authenticate and authorize before replaying: knowing a key must not reveal another caller's receipt.
Retention and regions
- Keep records at least as long as clients realistically retry: often hours to days for payments, shorter for low-stakes actions.
- After expiry a late retry looks new. If that is unacceptable, keep a unique business operation ID beyond the key's lifetime.
- Across regions, per-region key stores allow duplicates when a client fails over. Irreversible actions need a single writer, a globally consistent store, or a downstream effect that deduplicates by a stable operation ID.
Common mistakes
- Check, then insert: two requests both see no key. Let a unique constraint decide.
- Storing only the key: a buggy client that reuses a key for another order gets the wrong receipt. Store the fingerprint.
- Retrying a 500 without knowing whether the work committed: find out first.
- A new key after a timeout: it defeats the key's protection and risks a second order, unless a business-level unique ID still catches it. Retry with the same key.
- Keys or business IDs as metric labels: unbounded label sets. Count outcomes instead.
In an interview
What problem does an idempotency key solve? A request can succeed while its response is lost. The key lets the client retry safely: the server recognizes the repeat and returns the first result instead of acting twice.
Why a unique constraint rather than a check in code? Two concurrent requests can both pass a check before either inserts. A unique constraint lets the database pick exactly one winner.
What do you return when the same key comes with a different body? An error such as 422 or 409, never the earlier result: the client is misusing the key.
What if the first request is still running when the retry arrives? Follow the contract: 409, a 202 with a status link, or wait for the first to finish. Never run it a second time.
Which HTTP methods are idempotent already? The safe methods (GET, HEAD, OPTIONS, TRACE) plus PUT and DELETE, by RFC 9110. POST and PATCH are not, so they are the usual targets for idempotency keys.
Is there a standard header? Idempotency-Key is defined by an IETF Internet-Draft in the HTTP APIs working group; it is not yet an RFC.
Check yourself
Two identical create-order requests with the same key arrive at the same moment. What guarantees only one order?
Show answer
Correct answer: B
Only an atomic operation lets exactly one request win; the other sees the key taken.
Option A: Both requests can pass the check before either inserts.
Option C: Timeouts do not stop two requests from running.
Option D: Logging records the duplicate; it does not prevent it.
A retry uses an existing key but asks for 5 books instead of 2. What should the server do?
Show answer
Correct answer: C
The stored fingerprint differs, so this is not a retry of the same operation.
Option A: Replaying hides a client bug and returns the wrong outcome.
Option B: The key now names a different operation.
Option D: A retry must never change the original operation.
The order committed, but the worker crashed before recording the result. The lease expired and the client retries. What is safe?
Show answer
Correct answer: B
An expired lease says who may work now, not whether the earlier work happened.
Option A: That creates a second order.
Option C: A new key defeats the key's protection and risks a second order.
Option D: Deleting the record loses the link to the committed order.
Sources
- RFC 9110, idempotent methods: which HTTP methods are idempotent.
- The Idempotency-Key HTTP header field: the IETF draft for the header.
- Retry pattern: a lost response, and why non-idempotent retries are risky.
- Idempotent Consumer pattern: handling the same message more than once.
- ConcurrentDictionary:
GetOrAddruns its factory outside the lock.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·