Imagine a client sends a payment request to your API. The server processes the payment, but the connection drops before the client receives the response. Unsure whether the payment succeeded, the client retries the request. Without proper protection, the customer could be charged twice.
This problem is not limited to payments. Network timeouts, application crashes, load balancer resets, and message redelivery can all cause the same operation to be submitted more than once.
Idempotency keys make retries safer by allowing an API to recognize repeated requests belonging to the same logical operation. Instead of performing the operation again, the server can return the result of the original request.
This guide explains how idempotency keys work, how to store them, how to handle concurrent requests, and how to design a reliable implementation using database constraints and recovery mechanisms.
What Is Idempotency?
An operation is idempotent when repeating it produces the same intended effect on the server as performing it once.
For example, setting a user's account status to active repeatedly produces the same final state. Creating a new order repeatedly, however, may create multiple orders.
HTTP defines methods such as GET, PUT, and DELETE as idempotent according to their intended server-side effects. POST is generally not idempotent by default, which makes it particularly important to handle retries carefully when it creates resources or triggers external actions.
An idempotency key is a unique identifier that a client attaches to a request, commonly through an Idempotency-Key header. The server uses it to identify retries of the same logical operation.
Remark: Idempotency is about the effect of an operation, not necessarily identical response bodies. A server might return different request IDs or timestamps while ensuring that the underlying operation is not performed twice.
How Idempotency Keys Work
The client generates a unique key before making the first request and reuses that key whenever it retries the same operation. A UUID with sufficient randomness is a common choice.
The server checks the key and follows one of three paths:
| Situation | Expected behavior |
|---|---|
| New key | Register the operation and process the request |
| Existing completed key | Return the stored result without repeating the operation |
| Existing key still processing | Return a conflict response or follow the API's documented waiting and retry behavior |
The key must be scoped correctly. A key from one customer must never cause another customer's request to receive the first customer's result.
For example, uniqueness might be enforced per account and operation, rather than across all requests made by every customer.
Remark: Generate the key on the client before the first attempt and retain it with the pending operation. Generating a fresh key for every retry defeats the purpose of idempotency.
What Should an Idempotency Record Store?
A reliable implementation needs more than the key itself. An idempotency record typically includes:
- Scope and key: Identify the customer, API client, or operation and its idempotency key.
- Request fingerprint: Identify the parameters associated with the original operation.
- Status: Indicate whether the operation is processing, completed, or in a defined failure state.
- Stored response: Preserve the response status and body when the API's replay policy requires it.
- Recovery metadata: Track timestamps, ownership or lease information, and expiry.
The request fingerprint is particularly important. It helps detect a client reusing the same key for a different operation.
For JSON requests, fingerprinting can use a normalized representation of the relevant fields so that insignificant differences, such as JSON property ordering, do not create false mismatches. Include the parameters that define the operation, not merely whichever fields happen to be convenient.
Remark: Avoid storing sensitive request data unnecessarily. A fingerprint can be calculated from the relevant request fields and stored instead of retaining the entire raw payload.
How Long Should Keys Be Stored?
The retention period depends on the API contract and how long clients may retry. Some payment APIs use a retention period of approximately 24 hours, but this is not a universal rule.
A cleanup process can remove expired records, provided the expiration policy is documented and appropriate for the operation.
Remark: Once a key expires and its record is deleted, submitting that key again may create a new operation. For high-value operations, consider additional business-level safeguards, such as unique payment references, reconciliation, or constraints on duplicate orders.
Handling Concurrent Duplicate Requests
One of the hardest cases occurs when two requests with the same key arrive almost simultaneously.
A simple check-then-act approach is unsafe. Both requests might check the database before either records the key, allowing both to perform the operation.
The solution is to let the database enforce uniqueness.
In PostgreSQL, a unique constraint or composite primary key over the appropriate scope and idempotency key ensures that only one request can claim that key. The application can use an insert with ON CONFLICT DO NOTHING and inspect whether it successfully created the record, rather than relying on a uniqueness error and attempting another query in the same failed transaction.
The winning request registers the operation as processing. A duplicate request checks the existing record:
- If the fingerprint differs, reject the request.
- If the operation is completed, return the stored response.
- If the original operation is still processing, return HTTP 409 Conflict or use another clearly documented concurrency policy.
This prevents concurrent requests from independently claiming the same idempotency key.
Remark: Keep database transactions short. Do not hold a database transaction open across a slow external API call simply to keep the idempotency record locked.
Recovering From Crashed Requests
Consider what happens when a server registers an idempotency key and then crashes before completing the operation. The record might remain in the processing state indefinitely, causing every retry to be rejected or delayed.
A recovery mechanism can identify processing records whose leases or lock timestamps have expired and allow another worker to investigate or resume the operation.
However, an expired lock does not prove that the original operation failed. The server might have completed an external side effect before crashing, even though it never saved the final response.
A safe recovery strategy should therefore account for:
- Whether the operation actually completed.
- Whether the previous worker is still running or can resume.
- Whether the old worker can overwrite the result produced by a replacement worker.
- Whether repeating the external operation is safe.
Use conditional ownership checks or fencing tokens where necessary to prevent a stale worker from finalizing an operation it no longer owns. For external services, pass through the same idempotency key when supported, and reconcile uncertain outcomes before repeating an irreversible action.
For operations entirely within one database, a database transaction can often commit the business change and the completed idempotency result atomically.
Remark: Idempotency reduces duplicate effects, but it does not automatically provide exactly-once execution across multiple independent systems. Reliable external workflows may also require downstream idempotency, reconciliation, and transactional messaging patterns.
What If the Same Key Is Used With a Different Payload?
Suppose a client sends a payment request for 500 using a particular key, then reuses that key for a payment of 900.
The server should not silently return the first payment's response as though the second request succeeded. It should also not process the changed payload under the same key, because that breaks the key's meaning.
The server should compare the incoming request fingerprint with the stored fingerprint and reject a mismatch.
A common convention, also recommended by the current IETF Idempotency-Key Internet-Draft, is to return HTTP 422 Unprocessable Content for a key reused with different request parameters. HTTP 409 Conflict can be used for a request that conflicts with another request still in progress.
The distinction makes the response easier for clients to interpret:
| Status code | Meaning |
|---|---|
| 409 Conflict | The original request is still processing |
| 422 Unprocessable Content | The key was reused with different parameters |
These conventions should be documented consistently in your API.
Remark: Normalize the fields used for fingerprinting before comparing them. Otherwise, equivalent requests with different JSON property ordering could be incorrectly rejected.
Which Responses Should Be Stored and Replayed?
The response-caching policy is an important design decision. There is no universal rule that every error should be cached or that every server error should be retried.
For example, Stripe's API v1 stores the first result after endpoint execution begins, including HTTP 500 responses. Validation failures before execution and certain concurrent conflicts are not stored in the same way. Other APIs can define different behavior.
A well-designed API should specify:
- Which successful outcomes are stored.
- Whether terminal business errors are replayed.
- How server errors and uncertain execution outcomes are handled.
- What happens when the same key is submitted again after a failure.
- When an expired or abandoned processing record can be recovered.
A timeout does not necessarily mean that the operation failed. If a payment provider processed a charge but the application lost the response, blindly retrying without downstream idempotency or reconciliation may cause a duplicate.
The key principle is to preserve enough information to determine whether the original operation completed, rather than treating every failure response as proof that no side effect occurred.
Remark: Document your retry policy explicitly. Clients need to know whether to resend the same key, wait for a result, correct the request, or create a new key for a genuinely new operation.
Implementing Idempotency With a Database Constraint
PostgreSQL provides a strong foundation for an idempotency system.
Create an idempotency table containing the scoped key, request fingerprint, processing status, stored response fields, timestamps, and recovery metadata. Enforce uniqueness on the combination of scope and key.
A request handler can then follow this general sequence:
- Read the idempotency key and calculate the request fingerprint.
- Attempt to claim the key atomically.
- If the key already exists, compare fingerprints and inspect the existing status.
- Return the stored response for a completed operation, reject a payload mismatch, or handle an operation still in progress.
- If the key is new, perform the operation and persist its final outcome using the appropriate transaction and recovery strategy.
When the business operation and idempotency record use the same database, commit them together whenever possible. When the operation involves an external service, use the provider's idempotency feature if available and design for uncertain outcomes.
Remark: PostgreSQL's unique constraint is the foundation for preventing two requests from claiming the same scoped key. Application-level checks alone are not sufficient under concurrency.
Common Idempotency Mistakes
Generating a new key on every retry. The server cannot reliably recognize a retry if the client changes the key each time.
Using a business identifier without defining its meaning. An order ID may be a suitable key if only one operation is allowed per order. It may be inappropriate when multiple distinct payment attempts are legitimate. Define whether the key represents one operation, one attempt, or one user intent.
Treating idempotency as a replacement for transactions. Idempotency prevents repeated requests with the same key from duplicating an operation under the defined policy. It does not automatically make a multi-step workflow atomic.
Ignoring external services. A database record cannot by itself prevent a payment provider, email service, or shipping API from processing a repeated external request. Use downstream idempotency and reconciliation where supported.
Ignoring expiration and recovery. Removing a key too early can allow an old retry to create a new operation. Taking over an abandoned processing record without checking the previous operation can also repeat a side effect.
Remark: Treat idempotency as a complete API contract covering keys, concurrency, error handling, retention, and recovery, rather than as a header added to a request.
Conclusion
Idempotency keys make API retries safer by allowing the server to recognize repeated requests belonging to the same logical operation. A robust implementation combines client-generated keys, request fingerprinting, database-enforced uniqueness, a documented response policy, and safe recovery from interrupted operations.
The most important details are easy to overlook: the same key must not be reused for different parameters, concurrent requests must be coordinated atomically, and an interrupted request may already have caused an external side effect.
Start with a unique constraint and a well-defined request fingerprint, then add response replay, expiry, and recovery rules appropriate to your application.
You do not need to process payments to benefit from this pattern. Any API that creates resources or triggers side effects can become more reliable when retries are designed deliberately.
Frequently Asked Questions
What is an idempotency key?
An idempotency key is a unique identifier supplied by a client to help a server recognize retries of the same operation. When the server has already completed that operation, it can return the saved result instead of performing the action again.
Why do POST requests need idempotency keys?
POST requests commonly create resources or trigger side effects. If a client retries after a timeout, the first request may already have succeeded. An idempotency key helps the server distinguish that retry from a new operation.
How long should an idempotency key be stored?
The retention period depends on the API's retry window and business requirements. Some APIs use approximately 24 hours, but longer periods may be necessary for workflows involving delayed retries or reconciliation. The API should document when a key expires and what happens if it is reused afterward.
What should happen if the same key is sent with a different request body?
The server should compare the request fingerprint and reject the changed request rather than returning a misleading result or processing a different operation under the same key. HTTP 422 is a common choice for this mismatch.
Should idempotency keys be unique globally or per account?
Uniqueness should follow a documented scope, such as an account, merchant, API client, and operation. A scoped key prevents unrelated clients from receiving each other's results and avoids unnecessary collisions.
Do idempotency keys guarantee exactly-once execution?
No. They help prevent duplicate effects within the defined scope and retention period, but crashes, expiration, external services, and recovery races can still create uncertainty. Reliable systems combine idempotency with transactions, downstream deduplication, and reconciliation when necessary.



