A duplicate charge, order, or background job rarely begins with an obvious bug. It begins when a client cannot tell whether a timed-out request succeeded, so it retries. If the API treats that retry as a new operation, the customer may pay twice—or your agent may submit the same work twice.
The direct answer is simple: treat an idempotency key as the identity of one intended operation, not as a globally unique receipt. Scope it by tenant or client and by the operation being performed. When a key is reused, compare a canonical request fingerprint with the stored request. If they match, replay the original outcome; if they differ, reject the conflict instead of guessing. For concurrent requests with the same key, allow only one execution and make the others wait for or receive the result of that execution.
This matters to a small software company because reliable retry behavior prevents customer support work, refunds, duplicate usage charges, and unreliable agent workflows. It is often cheaper to build a small, durable idempotency store than to explain duplicate side effects after launch.
What an idempotency key actually identifies
The key identifies a logical operation such as “create this customer order.” It should be generated once before the first attempt and reused only when the client is uncertain whether that same operation completed.
A new key means a new logical operation. Changing the amount, destination, or other business-relevant data also means the operation is no longer the same. In that case, generate a new key.
Do not derive the key only from the request body. Two requests with identical payloads may intentionally represent two separate actions. Conversely, a retry can differ in harmless transport details—such as the order of JSON properties—while still representing the same operation. The server therefore needs both a stable key and a normalized request fingerprint.
The IETF Idempotency-Key header work describes this general pattern for fault-tolerant non-idempotent methods such as POST and PATCH. It remains a standards-track Internet-Draft rather than an RFC, so publish the exact behavior of your own API rather than implying that every server must behave identically.
A scoping model that prevents cross-client collisions
The most damaging collision is often not a random UUID collision. It is a logical collision caused by storing keys without enough context.
Use a compound scope similar to:
tenant_id + client_id + operation + idempotency_key
Where each part has a clear purpose:
tenant_idprevents one customer from colliding with another customer.client_iddistinguishes integrations or users if they share a tenant.operationdistinguishes route or operation families, such as creating an order versus issuing a refund.idempotency_keyidentifies the intended attempt within that scope.
Depending on your API, the operation component could be a stable route name, a canonical endpoint identifier, or an explicit internal action type. Avoid using a raw path if minor URL variations would create different scopes. For example, /orders and /orders/ should not become separate operation namespaces merely because of formatting.
One useful rule is: if two requests use the same key but could reasonably belong to different tenants, clients, or business actions, they must not share an idempotency record.
Do not log a key without enough context to investigate collisions. A log entry containing only the key may be useless if UUIDs are common across many clients. Log a one-way tenant or client identifier alongside a redacted key representation, operation name, request fingerprint, and outcome. Avoid recording secrets or sensitive payload contents in idempotency records or logs.
Detect accidental reuse with a request fingerprint
For each incoming request, calculate a fingerprint over the fields that define the intended operation. A practical implementation can use a cryptographic hash of a canonical representation of the request:
fingerprint = SHA-256(canonical_request_representation)
The canonical representation should normalize formatting without discarding business meaning. Depending on the endpoint, that may include:
- The authenticated tenant or client identity
- The operation or route identifier
- The HTTP method
- The relevant path parameters
- A canonicalized request body
- Any headers that alter the operation’s meaning
Do not fingerprint every incidental header. Authorization, tracing headers, timestamps, and proxy headers can differ between the original request and its retry without representing a different operation. Normalize or exclude them deliberately.
JSON objects with the same fields in different orders should ordinarily produce the same fingerprint. Numbers, arrays, absent fields, null values, and default values need explicit rules. For example, decide whether {"amount": 10} and {"amount": 10.00} are equivalent in your domain. Do not leave these decisions to whichever JSON library happens to serialize the body first.
Store the fingerprint beside the idempotency record. When the key already exists:
- Compare the stored fingerprint with the new fingerprint.
- If they match, treat the request as a retry.
- If they differ, return an idempotency conflict.
- Never execute the second operation merely because the key was “new enough” or because the original request failed.
Choose a conflict response deliberately
A conflict response tells the client that a key has been reused for a different request. This is a client contract problem, so return a stable status and structured error code rather than relying on prose in the response body.
A reasonable contract is:
HTTP/1.1 409 Conflict
Content-Type: application/json
{
"error": {
"code": "idempotency_key_conflict",
"message": "This idempotency key was already used for a different request.",
"request_id": "req_..."
}
}
The exact status code is an API design choice. The important distinction is between a conflicting payload and a valid retry. A client should never respond to a conflict by blindly generating another key and submitting the changed request unless its workflow intentionally allows that.
Also distinguish malformed input from a key collision. A missing or invalid key may receive a 400 Bad Request. A payload that fails business validation may receive 422 Unprocessable Content in APIs that use that convention. A reused key with a different fingerprint is a conflict, commonly 409 Conflict. These cases should not be collapsed into one generic error.
Avoid echoing the complete original request or sensitive payload in the conflict response. Include enough information for a developer to identify the mistake, such as a request identifier and the name of the conflicting operation.
Handle concurrent requests with one winner
Concurrency creates a race that a simple “check, then insert” sequence cannot solve safely:
Request A: key not found -> starts work
Request B: key not found -> starts work
Both requests observed the same empty state before either recorded the key. To prevent duplicate execution, the idempotency record must be created atomically before the side effect begins.
A small-team implementation can use one of these patterns:
- Insert a unique idempotency record before executing the operation. Only the request that successfully inserts it may proceed.
- Use a database transaction that claims the key, then performs the operation and stores the result.
- Use a distributed lock keyed by the compound scope, with a short timeout and durable state that survives a worker crash.
The unique-insert approach is usually the easiest to reason about when the primary database is already available. The essential operation is conceptually:
INSERT record(scope, key, fingerprint, status=in_progress)
If insertion fails because the scope and key already exist, do not start the work. Load the existing record instead.
Then handle the two valid states:
in_progress: the original execution has not produced a final result. Return a defined “still processing” response, such as409 Conflictwith a distinct error code, or wait briefly and re-read the record. Do not return the same response as a completed operation.completed: replay the stored status code and response body.
The distinction matters. A retry of a completed request should normally receive the original result. A concurrent request that arrives while the first execution is still running should not be told that the operation failed if it may still succeed.
You can also allow the second request to wait and then return the completed result. That can improve client ergonomics, but it consumes a worker or connection and creates timeout risks. For a small API, returning a documented “request in progress” response is often simpler and operationally safer.
Store enough result to replay it
An idempotency implementation that only marks a key as “seen” is incomplete. A later retry needs a stable answer.
A useful record contains:
scope
key
fingerprint
status
created_at
expires_at
response_status
response_headers
response_body
resource_id, when available
Store the final status and response representation used for the original request. Replaying the same status and body is easier for clients to reason about than synthesizing a new response that merely says “already processed.” The replayed body may become stale if the resource changed later, but that is preferable to pretending the operation ran again.
If a response contains a signed URL, a one-time token, or other expiring value, decide whether it is safe to store and replay. If not, store the durable operation result and define a separate retrieval path. Do not promise byte-for-byte replay for material you intentionally omit.
Decide which failures become final stored results. A deterministic validation error can often be stored and replayed because retrying the same invalid request will not produce a different result. A transient server failure may need to be marked retryable, depending on whether the side effect truly completed. This distinction is operational, not merely syntactic: a generic “cache every 500” policy can make a transient failure permanent for the entire key lifetime.
Set a safe retention period
An idempotency key should live long enough to cover the client’s retry window, but not forever. Retention must be based on the longest plausible uncertainty period, not a convenient cleanup schedule.
Consider these inputs:
- Client retry and timeout policies
- How long jobs remain in queues or execute asynchronously
- Mobile or offline clients that may reconnect much later
- Billing, payment, and refund reconciliation processes
- Customer support and incident investigation needs
- Privacy and data-minimization obligations
- Expected request volume and storage cost
Then publish the validity window. A key retained for one hour cannot safely protect a request that may be retried after three hours. A key retained for a week creates more records and may retain request metadata longer than necessary.
There is no universal retention period in the dossier or in the draft specification. Treat any exact number in your API documentation as a product decision supported by your retry and business workflows—not as an industry rule.
Do not promise safe retries after the retention window. State plainly that a new key may be required, and explain what that means for the operation. For a low-risk operation, that may be acceptable. For a payment or other consequential action, provide a lookup endpoint or reconciliation mechanism so the client can check the prior outcome before creating a new operation.
A safe expiry process also needs to handle in-progress records. Do not delete a key merely because its age crossed the retention threshold while its operation is still running. Expire completed records according to policy, but keep active records until the execution reaches a terminal state or an operator resolves it.
A minimal architecture for a small team
You do not need a dedicated idempotency platform to start safely. If your API already has a primary relational database, begin there:
- Create a table with a unique constraint over the full scope.
- Insert the claim record atomically before starting side effects.
- Store a canonical request fingerprint.
- Execute the operation within the appropriate business transaction or workflow boundary.
- Update the record with the final status and response.
- Schedule deletion of expired completed records.
- Add metrics for new requests, replayed results, in-progress conflicts, payload conflicts, and expired-key misses.
A simplified schema might look like this:
CREATE TABLE api_idempotency_records (
scope TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
request_fingerprint TEXT NOT NULL,
status TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
response_status INTEGER,
response_body BYTEA,
PRIMARY KEY (scope, idempotency_key)
);
The important part is the composite primary key and the atomic insert. If your application has several API instances, all of them must use the same durable store; an in-memory map on one server cannot protect the whole service.
Asynchronous operations need one additional decision: when should the idempotency record become complete? If the API returns 202 Accepted, the side effect may not yet be finished. You can either:
- Keep the record in progress until the worker finishes, allowing clients to poll or retry and receive the final result; or
- Mark the HTTP request complete but expose a separate operation-status resource.
Do not mark work complete merely because the API accepted it if the worker may fail and later retry. That creates another layer where duplicates can enter.
Test the failure cases, not only the happy path
Your test matrix should focus on the moments when a customer or agent is most likely to create duplicates:
| Scenario | Expected behavior |
|---|---|
| Same key and identical payload, sequentially | Original response is replayed; side effect occurs once |
| Same key and different payload | Conflict response; no second side effect |
| Two identical requests arrive concurrently | Exactly one operation executes |
| Two conflicting requests arrive concurrently | One wins; the other receives a conflict |
| Original operation fails before the side effect | Retry policy is explicit and does not accidentally replay permanent failure |
| Original operation succeeds but the response is lost | Retry returns the stored result |
| Key has expired | Behavior is documented; client receives a clear expiry indication or lookup path |
| Worker restarts during execution | The in-progress record is recovered or safely resolved |
Include a test that sends the same logical JSON with different property order. If your canonicalization is wrong, a harmless retry may appear as a conflict.
For agent-driven products, add an end-to-end case where an agent loses its connection after submitting work and retries from its persisted checkpoint. The key must survive that restart. If your agent framework generates a fresh key on every transport retry, the API cannot distinguish a retry from a second logical action.
A pre-launch checklist
Before enabling idempotency keys on a consequential endpoint, confirm that:
- The key represents one logical operation, not one HTTP attempt.
- The client persists the key across retries and process restarts.
- The server scopes records by tenant or client and operation.
- The server creates the record atomically before executing side effects.
- The request fingerprint distinguishes meaningful payload changes from formatting noise.
- A conflicting payload receives a documented conflict code.
- Concurrent requests cannot both execute the side effect.
- Completed responses can be replayed with the original status and body.
- Retention covers the documented retry window but has a cleanup mechanism.
- In-progress records are not deleted prematurely.
- Logs and metrics can reveal collisions without exposing sensitive payloads.
- The client has a strategy for requests retried after key expiry.
Frequently asked questions
Should every endpoint use idempotency keys?
Not necessarily. They are most valuable for operations that create consequential side effects and may be retried: charges, orders, refunds, invitations, account creation, job submission, and agent actions. Read-only endpoints usually do not need them, although an unusual GET with side effects should not rely on GET being harmless.
Can two clients use the same random key?
Yes, if your scope separates them. UUID-style random keys make accidental overlap unlikely, but scoping is still the security and correctness boundary. Tenant isolation must not depend on clients choosing sufficiently random values.
Should the server return the original error response?
Only if that error is a deterministic result of the same request and your contract says it is replayable. A transient infrastructure error may warrant a different retry outcome. Define this explicitly rather than caching every response indiscriminately.
Is an in-memory cache enough?
Only for a single-process demonstration. It loses records on restart and cannot coordinate instances. It also makes the retention guarantee depend on deployment shape. Use durable shared storage for production workloads where duplicate side effects matter.
What if a key is reused after expiry?
Your policy must say what happens. A fresh operation may be allowed, or the API may require reconciliation through a lookup mechanism. The dangerous behavior is silently treating an old key as brand new without explaining whether the earlier operation might still have succeeded.
The smallest reliable design is not a large distributed system. It is a durable compound scope, an atomic claim, a normalized fingerprint, a stored final response, and a published expiry policy. Add those five pieces first; then expand observability and recovery as request volume justifies them.
Sources
- IETF draft: The Idempotency-Key HTTP Header Field, revision 07
- IETF Datatracker: draft-ietf-httpapi-idempotency-key-header
- HTTP Idempotency Keys for API Developers: Handle 400, 409, 422
- Idempotency in Practice: Why Your Retry Just Charged the Customer Twice
- Why Retries Break Your Java APIs and How Idempotency Fixes It







