- Published on
Idempotency in Distributed Systems: Designing APIs That Survive Retries
- Authors

- Name
- André Mello
Intro
If you have ever seen a customer charged twice, an order created in duplicate or the same email sent three times, you have met the consequences of a non-idempotent operation in a system that retries.
In a distributed system, retries are not an edge case. Networks drop packets, load balancers time out, clients give up and try again, and message brokers redeliver. The question is not whether a request will be executed more than once, but what happens when it is.
A common scenario in the market looks like this: a mid-sized e-commerce platform processing around 50,000 card payments a day. Its checkout calls the payment service with a 10-second timeout, while the card processor occasionally takes 12 to 15 seconds to respond during peak events like Black Friday. If just 0.1% of requests hit that timeout and the frontend retries automatically, that is 50 duplicate charge attempts per day — each one a support ticket, a chargeback risk and a customer who may not come back. Nobody notices in testing, because in testing the network never fails.
What Idempotency Means
An operation is idempotent when executing it once or many times produces the same result on the server. HTTP already gives us some guarantees:
| Method | Idempotent by spec? | Notes |
|---|---|---|
GET | Yes | Must not change state |
PUT | Yes | Replaces the resource with the same payload |
DELETE | Yes | Deleting twice leaves the resource deleted |
POST | No | Usually creates something new on each call |
PATCH | Not necessarily | Depends on the patch semantics (+1 vs =5) |
The problem is that the most business-critical operations — creating a payment, placing an order, issuing a document — are almost always POST. That is exactly where we need to design idempotency ourselves.
Why "Just Don't Retry" Doesn't Work
Consider a client calling a payment API:
- The client sends
POST /payments. - The server processes the payment and commits it to the database.
- The response is lost because of a timeout between the load balancer and the client.
From the client's point of view, the request failed. From the server's point of view, it succeeded. The client has no way of telling the difference, so the only safe options are to retry or to give up. Giving up means the user thinks the payment failed when it didn't. Retrying without idempotency means paying twice.
Idempotency Keys
The most common and robust solution is the idempotency key: a unique value generated by the client for each logical operation and sent with every attempt of that operation.
POST /payments HTTP/1.1
Idempotency-Key: 6f1c2b8e-3a4d-4f7e-9b1a-2c5d8e9f0a1b
Content-Type: application/json
{ "amount": 150.00, "currency": "BRL", "customerId": "c-123" }
The server stores the key together with the result of the first execution. Any later request with the same key returns the stored result instead of executing the operation again.
A minimal implementation
The most reliable way to enforce uniqueness is to let the database do it:
CREATE TABLE idempotency_keys (
idempotency_key VARCHAR(64) PRIMARY KEY,
request_hash VARCHAR(64) NOT NULL,
status VARCHAR(16) NOT NULL, -- IN_PROGRESS, COMPLETED
response_code INT,
response_body JSONB,
created_at TIMESTAMP NOT NULL DEFAULT now()
);
And in a Spring service:
@Transactional
public PaymentResponse createPayment(String key, PaymentRequest request) {
String hash = DigestUtils.sha256Hex(objectMapper.writeValueAsString(request));
Optional<IdempotencyRecord> existing = repository.findById(key);
if (existing.isPresent()) {
IdempotencyRecord record = existing.get();
if (!record.requestHash().equals(hash)) {
throw new IdempotencyKeyReusedException(key); // 422
}
if (record.isInProgress()) {
throw new RequestInProgressException(key); // 409
}
return record.storedResponse();
}
// The primary key guarantees only one concurrent request wins this insert
repository.insertInProgress(key, hash);
PaymentResponse response = paymentProcessor.process(request);
repository.markCompleted(key, response);
return response;
}
A few details matter more than they seem:
- Hash the request. If a client reuses a key with a different payload, that is a bug on their side. Return an error instead of silently returning the old response.
- Handle concurrent duplicates. Two retries can arrive at the same time. The unique constraint makes one of them fail the insert; that one should answer
409 Conflictand let the client retry later. - Set an expiration. Keys don't need to live forever. 24 hours to a few days is typical; clean them up with a scheduled job.
Natural Idempotency
Sometimes you don't need a separate key because the domain already has one:
- An invoice number that must be unique per issuer.
- An external transaction ID received from a partner.
- A
(customer_id, billing_month)pair for a monthly charge.
In these cases a unique constraint on the business identifier gives you idempotency for free. Prefer this whenever the domain allows it — it is simpler and it protects you even from bugs in your own code.
Idempotent Consumers
The same reasoning applies to message consumers. Kafka, SQS and RabbitMQ all provide at-least-once delivery in their most common configurations, which means your consumer will see duplicates.
A simple pattern is to record processed message IDs in the same transaction as the side effect:
INSERT INTO processed_messages (message_id) VALUES (:id)
ON CONFLICT (message_id) DO NOTHING;
If the insert affects zero rows, the message was already processed and can be acknowledged and skipped.
Common Pitfalls
- Calling external services before recording the key. If you call the payment gateway and crash before saving anything, the retry will call the gateway again. Record the intent first, and pass your own idempotency key to the downstream provider when it supports one.
- Generating the key on the server. The key must come from the client and be the same across retries. A key generated per request on the server protects nothing.
- Treating idempotency as a cache. It is a correctness mechanism. It must be durable and consistent, which usually means your primary database, not a best-effort cache.
In the scenario above, the most likely culprit is the first pitfall: the service calls the card processor before persisting anything, so a timeout between the two steps leaves no trace that the attempt ever happened. The fix is to persist the intent first and forward the same idempotency key downstream — many payment providers, such as Stripe and Adyen, accept one for exactly this reason.
Conclusion
Retries are a fact of life in distributed systems, and they are only safe when the operations being retried are idempotent. Idempotency keys, unique constraints on business identifiers and idempotent consumers are simple tools, but they turn "the network failed" from a data integrity incident into a non-event.
When designing your next POST endpoint, ask a simple question: what happens if this request arrives twice? If the answer is anything other than "nothing new", there is work to do.