Imagine a client sends a request but never receives the response. The server may have completed the operation; only the response was lost in transit. If the client retries, a payment, order, reservation, or resource creation operation may happen twice. This uncertainty is one of the most important reliability problems in APIs that produce side effects.
The main tool for addressing it is idempotency. When the same logical operation is submitted more than once with the same request identity, the observable effect should be equivalent to processing it once. This article explains how to design an idempotency-key contract, protect it against concurrent requests, persist results safely, and test failure paths.
What idempotent behavior actually means
In HTTP semantics, an idempotent operation is one where sending the same request one or more times has the same intended effect on the server as sending it once. This does not mean that every implementation detail is identical. A server may log each attempt separately. The important property is that a second request does not create another order or charge an account again.
GET, PUT, and DELETE are defined as idempotent HTTP methods, provided the application respects their intended semantics. POST is not idempotent by default. Resource creation and other side-effecting commands therefore need an application-level mechanism when clients must be able to retry safely.
Define the idempotency-key contract first
The client generates a random, high-entropy identifier for one logical operation. It can be sent in the Idempotency-Key request header:
POST /v1/orders HTTP/1.1
Idempotency-Key: 7f3d8f1e-2a20-4a50-9f48-0dd9d0a8e3b1
Content-Type: application/json
{"customer_id":"c_42","items":[{"sku":"book-7","quantity":1}]}When the server sees the same key again, it should return the result of the original logical operation rather than start a second one. The scope must be explicit: is the key unique per tenant, per authenticated customer, per endpoint, or globally? The contract should also define how long keys are retained and what happens after expiration.
A practical contract usually includes these rules:
- The key must be non-empty and subject to a reasonable length limit.
- The key must be associated with the authenticated customer or tenant.
- Reusing a key with a different request payload must be rejected.
- The status code and response body needed for replay should be stored.
- The retention period should exceed the client’s expected retry window.
Reject the same key with different intent
A dangerous implementation only checks whether a key has been seen before. Suppose a client first submits a request for ten units and later accidentally reuses the key for one unit. The second request must not silently receive or overwrite the first result. It is a key-reuse error.
To detect this condition, store a fingerprint of the original request. The fingerprint can be computed from a canonicalized request body together with the endpoint, tenant, authenticated principal, and other fields that affect behavior. When the key is reused, compare the new fingerprint with the stored one. A mismatch should produce a clear client error, commonly a conflict response or a documented validation error.
Canonicalization matters. If JSON member order has no semantic meaning, two equivalent payloads with different field order should produce the same fingerprint. At the same time, the API must define how it handles decimal formatting, timestamps, omitted defaults, Unicode normalization, and fields that are ignored by business logic. Hashing raw request bytes is often too strict or too dependent on serialization details.
Make the database enforce uniqueness
This sequence is not safe on its own:
- Look for the idempotency record.
- If it does not exist, execute the operation.
- Insert the result into the idempotency table.
Two concurrent requests can both observe “not found” and then both perform the side effect. The uniqueness rule must therefore be enforced by the database, and the insertion or reservation step must be atomic.
An idempotency record commonly contains:
| Field | Purpose |
|---|---|
scope | Tenant, customer, or client boundary |
key | The client-generated operation identifier |
request_hash | Fingerprint of the first request |
status | processing, succeeded, or failed |
response_code and response_body | Replayable result |
created_at and expires_at | Retention and cleanup control |
In PostgreSQL, a unique constraint such as UNIQUE (scope, key) protects against concurrent insertion races. Application code should handle a uniqueness conflict as part of the normal idempotency path. Prefer an atomic insert, an upsert with carefully defined semantics, or a transaction and locking strategy over a separate check-then-insert sequence.
Represent the operation as a state machine
Explicit states make ambiguous failures easier to reason about:
- processing: The key has been reserved and work is in progress.
- succeeded: The operation completed and its result was durably stored.
- failed: Processing started and ended with a permanent failure.
- expired: The retention window has ended and cleanup is allowed.
When a request arrives for a key in processing, there are two common choices. For short transactions, the server can wait briefly for the original operation to finish. For long-running work, return 202 Accepted with a status resource and let the client poll. The repeated request must not start a second job.
The ordering of the business change and the idempotency record is critical. If the main database update succeeds but the idempotency record is lost, a retry may repeat the side effect. If the record is written first but the business transaction rolls back, the system may incorrectly replay a success. When possible, persist the idempotency reservation, the business change, and the final result within one database transaction.
When an external provider is involved, such as a payment service, use that provider’s own idempotency mechanism as well. If the two systems cannot share a transaction, design reconciliation and status-check workflows for uncertain outcomes.
Choose a clear response and error policy
A result may be worth replaying even when it represents a failure. For example, validation may pass, processing may begin, and the server may return a transient error after the external side effect occurs. Returning a consistent stored result for the same key helps the client avoid creating a second operation.
On the other hand, a request rejected before execution begins does not always need a durable idempotency record. The client can fix the invalid input and submit a new request. The distinction must be part of the API contract: “not started” errors can be retried after correction, while an operation that began should have a stable outcome or a queryable status.
Use a machine-readable error format with stable problem types and avoid returning stack traces, database statements, internal hostnames, or secrets. Error responses should help the client decide whether to correct the request, wait, query status, or retry with the same key.
Retention, privacy, and security
Keeping idempotency records forever creates storage and privacy costs. Choose the retention period according to the business operation. A payment flow may need a longer window than a short-lived reservation. If a key can be reused as a new operation after expiration, document that behavior explicitly because it changes the meaning of delayed retries.
An idempotency key is not an authorization credential. The server must bind it to the correct tenant, user, and permission context. A key from one customer must not reveal a response belonging to another customer. If stored response bodies contain personal or financial data, apply access controls, encryption, retention limits, and appropriate redaction in logs.
Test the failure paths, not only the happy path
- Send the same key and identical payload repeatedly.
- Reuse the same key with a different payload.
- Deliver two identical requests concurrently.
- Complete the operation but drop the response before the client receives it.
- Crash the server while the record is in
processing. - Force a database transaction rollback.
- Run cleanup and retry around the expiration boundary.
- Attempt to use a key from a different tenant or authorization context.
Idempotency is therefore more than adding a header to an HTTP request. A production-quality design combines an explicit API contract, canonical request fingerprints, database-enforced uniqueness, a state machine, safe result replay, bounded retention, and targeted failure testing. Once these pieces are in place, timeouts and controlled retries stop being duplicate-side-effect risks and become a reliable mechanism for recovering from normal distributed-system failures.
0 Comments