The practical answer

For most APIs, retain idempotency keys for at least as long as clients may retry a request and still need a definitive answer. A common starting point is 24 to 72 hours, but there is no universal expiry that fits every product.

The right period depends on three things:

  1. How long your client and its infrastructure may keep retrying after a timeout or network failure.
  2. How long an ambiguous request can remain useful to the business.
  3. How much storage and operational complexity you can reasonably maintain.

For payment, order-creation, wallet, credit, or other high-value operations, retain keys longer. If a client may retry for several days, a key that expires after one hour cannot protect the second attempt. Conversely, keeping every key indefinitely may turn a small database table into an unnecessary operational burden.

A useful rule is:

Set the retention window longer than your longest realistic retry window, then add a safety margin.

Do not treat a short expiry as a way to simplify the system. It can move the duplicate-work problem from the database into the customer experience.

What an idempotency key actually protects

A client sends a unique key with a request that can create side effects, such as POST /orders or POST /payments. If the response is lost, the client does not know whether the server completed the operation. Retrying the same request with the same key lets the server recognize the second attempt and return the original result rather than creating another order or charging again.

The Idempotency-Key HTTP request header is designed for this pattern. The IETF Internet-Draft describes it as a way to make non-idempotent methods such as POST and PATCH fault-tolerant.

Idempotency is not a property of the HTTP method alone. GET, PUT, and DELETE are conventionally idempotent, while POST and PATCH generally are not. In practice, the key matters most when the operation creates or changes something that the business cannot safely repeat.

For a founder, the question is simpler:

Could an ambiguous retry cause duplicated work, double revenue, a second notification, or another customer-visible problem?

If yes, make the operation idempotent even if the HTTP layer already provides some natural idempotency.

Choose retention from the retry horizon, not a fashionable default

Start by mapping the retry behavior of each important client.

Ask:

  • How long does the client retry after an ambiguous response?
  • Does the client retry automatically in the background, or only when a person presses a button?
  • Are retries paused during outages and resumed later?
  • Does an upstream proxy, queue, or SDK add its own retries?
  • Can a business workflow legitimately replay an event after a day or a week?

If the answer is that retries can continue for seven days, a 24-hour retention period is not sufficient. If all retries occur within ten minutes, retaining keys for 24 hours may already provide a generous safety margin.

For most small teams, use this conservative starting policy:

Operation type Practical starting point Why
Low-risk, quickly repeatable API calls 24 hours Covers common timeout and client retry behavior while limiting storage growth.
Orders, subscriptions, or other billable operations 7 days Preserves protection across delayed retries and customer-initiated recovery.
Payments, credits, wallet transfers, or other high-impact financial operations At least the maximum replay window; often longer The cost of a duplicate is much higher than the cost of retaining a key.
Background jobs triggered by external events Until the event or job has a clearly defined replay horizon The relevant boundary is when the upstream system can no longer redeliver the event.

These are engineering starting points, not universal standards. The IETF draft explicitly treats key validity and expiry as implementation concerns rather than prescribing one duration.

A calculation you can use

Estimate the required retention like this:

retention period
  = longest client retry window
  + queue and outage delay
  + safety margin

For example:

6-hour client retry window
+ 12-hour outage or queue delay
+ 6-hour safety margin
= 24-hour minimum

Then adjust upward for operations whose consequences are expensive, irreversible, or visible to customers.

Do not blindly use the same TTL for every endpoint. An endpoint that creates a draft document and an endpoint that transfers money do not have the same risk profile.

Scope the key to one client and one logical operation

A key should identify one intended operation, not merely a particular HTTP request attempt.

A robust scope is:

(tenant or authenticated client, operation, idempotency key)

For example:

(acct_123, create_payment, 9f8a...)

This prevents two clients from colliding when they independently generate the same key. It also prevents the same key from being reused for a different operation.

Include the account or tenant in the lookup even when the key itself is globally unique. A globally unique UUID reduces accidental collisions, but it does not justify trusting a key from the wrong account. Authentication and authorization must still be checked before returning a stored response.

Do not scope a key only to the URL if different versions, tenants, or operation types could interpret that URL differently. The server needs enough context to know that the retry refers to the same logical action.

Detect accidental reuse with a request fingerprint

A key should not become a way to replay an old response to a materially different request. For example, this pair should not be treated as the same operation:

Idempotency-Key: abc123
POST /payments
{"amount": 1000, "currency": "USD"}
Idempotency-Key: abc123
POST /payments
{"amount": 2500, "currency": "USD"}

Store a fingerprint of the request alongside the key. A canonical representation can be based on:

  • HTTP method
  • API version or route
  • Relevant request fields
  • Tenant or account scope

Canonicalize the request before hashing it. Normalize object key order, apply documented defaults, and decide how arrays should be represented. Do not hash raw JSON bytes if harmless serialization differences would make an identical retry look different.

When the same key arrives with a different fingerprint, reject the request with a conflict response rather than replaying the earlier result. A 409 Conflict is usually clearer than silently ignoring the new payload.

Handle concurrent retries with an atomic claim

The duplicate-request race is simple:

  1. Request A checks whether key abc123 exists.
  2. Request A finds nothing and starts creating an order.
  3. Request B arrives with the same key, also finds nothing.
  4. Both requests create an order.

A “check, then insert” implementation is not safe unless the claim is atomic. The server needs a database uniqueness constraint or equivalent coordination mechanism.

A practical state model has three parts:

key + client + operation
    request fingerprint
    status: processing | completed | failed
    response status and body
    created_at / expires_at

At the start of processing, attempt to insert the key with a unique constraint. If the insert succeeds, this request owns the operation. If it fails because the key already exists, inspect the existing record:

  • processing: return a suitable response indicating that the original operation is still in progress, or wait briefly and check again.
  • completed: replay the stored response.
  • failed: apply a policy based on the failure type. Do not blindly rerun a failure that may have produced partial side effects.

The crucial property is that only one request may claim a given key. Application-level “check if absent” code without a unique constraint leaves a race window.

Avoid holding a database transaction open

It may be tempting to keep a transaction open while calling a payment provider or starting a long-running job. That couples database availability to external latency and can make lock behavior fragile.

A more robust pattern is:

  1. Atomically create the processing record.
  2. Perform the side effect using a downstream idempotency key whenever possible.
  3. Atomically store the final status and response.

Your API cannot make an external provider call perfectly safe by itself. If your API sends a request to another service, propagate the same logical operation identifier when the downstream service supports idempotency. Otherwise, design reconciliation and duplicate detection for that boundary too.

For expensive asynchronous work, return a stable operation identifier and let the client poll for the result. The idempotency key should identify the work request; it does not need to make the entire worker execution synchronous.

Make expiration explicit and safe

An expired key means the server can no longer prove that a repeated request is the same operation. That is useful for storage hygiene, but it is dangerous when clients still retry.

When a key is missing because it expired:

  • Do not quietly process the request as if no key had ever been supplied.
  • Do not return the original response if you can no longer retrieve it safely.
  • Prefer an explicit error that tells the client the key is no longer retained.

A 409 Conflict or 410 Gone may be appropriate, depending on whether the operation itself is considered expired. The key distinction is that the server is not claiming the request is new when it may actually be an old retry.

This creates a practical trade-off:

  • Long retention reduces duplicate-work risk but increases stored records and the cost of maintaining them.
  • Short retention keeps the store small but increases the chance that a legitimate retry is rejected or, worse, processed again.

For a founder, the safe default is to favor the side of customer-visible correctness unless storage cost or privacy requirements clearly justify otherwise.

Handle failed operations deliberately

“Not found yet” and “the operation failed” are different states.

If a request fails before producing side effects, you may be able to release the key and allow a retry. If it fails after partial processing, automatic reuse may be unsafe. Return the same failure response for subsequent attempts until a human or an explicit recovery mechanism resolves the state.

A useful policy is:

Failure point Possible response policy
Validation failure before side effects Return a deterministic error; reuse or release the key only after clearly documenting the behavior.
Temporary dependency failure with no known side effect Return a retryable error and preserve the in-progress or failed record according to your recovery policy.
Partial or ambiguous external side effect Do not automatically rerun; reconcile using the downstream operation identifier.
Successful completion Store and replay the response.

Do not invent a “retry everything on 5xx” rule. Some 5xx responses represent an operation whose outcome is unknown. Retrying that work safely depends on whether the downstream effect can be identified.

Operational checklist

Before shipping idempotency support, verify the following:

  • The key is generated once per logical operation and reused across retries.
  • The client does not generate a new key merely because a retry timer fires.
  • The lookup scope includes tenant or client identity and operation context.
  • A unique database constraint prevents two workers from claiming the same key.
  • The request fingerprint detects accidental reuse with different parameters.
  • A completed response can be replayed with the same status and important headers.
  • Concurrent requests are handled deterministically.
  • Failed and partially completed operations have an explicit recovery policy.
  • The retention period covers the longest realistic retry and replay window.
  • Expiration produces an explicit error rather than silently accepting an old retry.
  • Metrics distinguish new requests, duplicate retries, concurrent retries, fingerprint conflicts, and expired keys.

That last item matters for operations. A dashboard that only counts total requests will not show whether idempotency is working or whether clients are generating an unusual number of retries.

How to reduce the storage burden

Longer retention does not require keeping every large response body forever. Store only what is needed to reconstruct the outcome.

Depending on the operation, your record might need:

  • The key and request fingerprint
  • The resource identifier created by the operation
  • The final HTTP status
  • A normalized response payload
  • Selected response headers, such as Location
  • Creation, completion, and expiry timestamps

For large payloads, store the created resource identifier and rebuild the response from the database when possible. That saves space, although it introduces another failure mode: the resource may later change, so a replay may not exactly match the original response. Decide which matters more for your API contract.

You can also partition or archive old records, provided the system still returns a clear expired-key response rather than treating a missing record as a new operation.

What should the client do after a successful response?

Once the client receives a successful response, it should stop retrying that logical operation. If a later business workflow needs to perform the same action again, it should intentionally create a new key.

This distinction prevents accidental key reuse. “Retry the failed request” and “submit a new order” are different intentions and should not share a key.

A client-side retry policy should normally:

  1. Reuse the original key.
  2. Retry only when the outcome is ambiguous or the server explicitly indicates a retryable failure.
  3. Respect Retry-After when the server supplies it.
  4. Stop after the declared retry horizon.
  5. Surface a durable operation status for long-running requests instead of repeatedly recreating work.

The server still needs protection even if clients are imperfect. Keys, retry libraries, and infrastructure can all produce accidental duplicates.

Why the answer is not one universal number

The draft Idempotency-Key header specification gives implementations flexibility over key validity and expiry. That is appropriate because the safe period depends on the API’s risk and the ecosystem around it.

A 24-hour window can be sensible for a small API whose clients retry briefly. It can be reckless for a payment API whose queue may replay an event five days later. Conversely, a multi-year retention policy can be justified for financial records while being wasteful for a temporary draft-generation endpoint.

The decision should be explicit in your API documentation. Tell clients:

  • Which endpoints accept idempotency keys.
  • How long keys are retained.
  • Whether the same key may be used with different request parameters.
  • What response to expect for concurrent and expired keys.
  • Which failures are safe to retry.

If clients cannot make a correct retry decision, the server has not fully specified the contract.

Frequently asked questions

Should every API endpoint support idempotency keys?

No. Add them where a repeated request can cause duplicated or conflicting business effects, or where your clients have a realistic need to retry. Read-only operations usually do not need the same protection.

Can I reuse a key across different endpoints?

Prefer not to. Scope keys to one operation so accidental reuse becomes a fingerprint conflict rather than an ambiguous replay.

Is a UUID enough to prevent duplicates?

It helps make collisions unlikely, but it does not solve concurrency, request mismatch, expiration, or storage. The server still needs atomic key claiming and a defined retention policy.

What should happen when two identical requests arrive simultaneously?

Only one should claim the key. The other should observe the in-progress or completed record and avoid performing the side effect again. The exact response depends on your API contract; a stable conflict response and a replayable success response are both viable designs.

Should I delete a key immediately after success?

Usually not. Deletion immediately after success leaves a gap in which a delayed retry can duplicate the operation. Keep enough history to cover the client’s replay horizon.

Where should idempotency records live?

Use durable storage with atomic uniqueness enforcement and transactional updates. A process-local cache may help performance, but it should not be the only authority if losing the record can cause duplicate work.

Bottom line

Start with the longest realistic retry period, add a safety margin, and extend retention for expensive or financially meaningful operations. Scope each key to one client and one logical operation, atomically claim it, fingerprint the request, and distinguish processing, completed, failed, and expired states.

The central principle is not “keep every key forever.” It is:

Keep enough evidence to distinguish a retry from a new request for as long as a retry could plausibly arrive.

That is enough to prevent most duplicate work without building a complex idempotency platform before the API has earned one.

Sources