Make retries safe
A retried request or redelivered message creates a duplicate order, charge or notification.
Say it like this
Every retry path in this system can deliver the same request twice, so the client sends an idempotency key and the server stores the result under it, which turns a duplicate into a cheap replay instead of a second charge.
Basic solution
Have the caller send an idempotency key; store it with the result and return the stored result on repeats.
Claim the key, act, store the result
The first request claims the key atomically and does the work. A retry with the same key fails the claim and gets the stored response.
How it works
- The client generates a unique key for the logical operation (a UUID, or a hash of the intent such as order-shipped:order123) and sends it with the request, in an Idempotency-Key header or a message field. A retry of the same operation sends the same key.
- The server tries to claim the key atomically, in one step that cannot interleave with another request: SET key NX with a TTL in Redis (NX means "only if it does not exist"), or INSERT into a table with a unique constraint on the key.
- If the claim fails, the key is already known, so this request is a repeat. The server returns the response stored under the key, or 409 Conflict if the first attempt is still in progress and there is no result yet.
- If the claim succeeds, this is the first time: the server performs the operation and stores the result against the key, in the same transaction as the side effect where possible, so a crash cannot leave the effect without the record.
- Keys expire after the longest plausible retry window, usually 24 hours, so storage stays bounded.
Where to put the dedup record
- In the same database and transaction as the write: the strongest option, because the effect and the record commit together and there is no window between them.
- In Redis: the fastest option, but a crash between the side effect and writing the record leaves a window in which a retry would repeat the effect, so order it as claim the key, act, then record the result.
Worked example
Notification system
- Producers retry on any timeout. Without keys, a 1% retry rate on 250M notifications/day is 2.5M duplicate messages a day.
- Key: producer-supplied, scoped per producer, such as orders:order-shipped:9f3a. Stored in Redis with SET NX EX 86400.
- Memory: 250M keys × ~80 B ≈ 20 GB over 24 h; a small cluster, or keep it in the notification table with a unique index on (producer, key) and lose the extra store.
- Second dedup point: the SMS worker sets sent:delivery_id before calling Twilio, so a worker that crashes after the provider call does not resend on redelivery.
- Window left: a crash between the Twilio call and the SET. With a 50 ms call and a few crashes a day, that is a handful of duplicates a day instead of millions.
Variants and when each wins
Client-generated key stored with the result
- The client sends a key and the server stores the full response under it, returning the identical response on replay. It wins for any API that charges or creates something, which is why it is the standard; it costs storage per key.
Natural idempotency
- Design the operation so repeating it is harmless: set balance = 100 instead of add 10, PUT instead of POST, upsert by a natural key. It wins whenever the model allows it, because there is no extra storage and no key to manage; not every operation can be shaped this way.
Unique constraint on the business key
- A unique index on (user_id, external_order_id) makes the database reject a second insert of the same order. It wins when the operation already has a natural unique identity and runs in one transaction; the client must handle the conflict response.
Provider-side idempotency
- Payment and messaging providers accept an idempotency key of their own. It wins as a second layer: pass your key through so a retry to the provider is also safe, closing the window your own record cannot cover.
Prefer natural idempotency where the model allows it; otherwise a client key stored transactionally with the result.
Failure modes
Key reused for a different request
- A client sends a new order with a key it used before and gets the old order back as if it had succeeded. It happens because the key was derived from something that is not unique to the intent, such as a user id plus a date. Store a hash of the request body with the key, and reject a reuse whose body does not match with 422.
Crash between side effect and record
- A handful of rare duplicate sends. It happens because the dedup record is written after the external call, so a worker that crashed in between left the effect done but unrecorded, and the retry did it again. Claim the key before the call so a retry sees the claim; accept the small remaining window, or pass an idempotency key to the provider too.
Keys never expire
- Redis memory grows for weeks until eviction starts dropping live keys, and then duplicates appear. It happens because the keys were written without a TTL. Set a TTL equal to the retry window and alert on Redis memory.
Concurrent duplicates
- Two identical requests a millisecond apart both succeed. It happens because the code checked whether the key existed and then set it in two steps, and both requests passed the check before either set. Use an atomic claim (SET NX, or a unique constraint) and never GET followed by SET.
Scope collision across tenants
- One customer's request is rejected as a duplicate of another customer's. It happens because keys are not namespaced, so two callers who both chose key "order-1" collide. Prefix every key with the caller's identity before storing it.
Interviewer follow-ups
Answer out loud before you open each one.
What should the server return on a duplicate?
The same status and body as the first response, so the client cannot tell it was a replay. If the first attempt is still running, return 409 Conflict with a hint to retry, because returning success before the work finished would be a lie.
How long do you keep the keys?
Longer than any retry can arrive: client retries are seconds, queue redelivery minutes, a replayed batch maybe a day. Twenty-four hours covers almost everything; for payments many keep them for weeks in the database rather than Redis.
Does this give you exactly-once?
It gives at-least-once delivery with effectively-once effect, which is what people usually mean. The side effect may still execute twice in the crash window; what you guarantee is that the observable outcome is as if it ran once.
Can the server generate the key instead of the client?
Only if the server sees the request once; a retried HTTP call arrives as a fresh request with no link to the first. The key has to be created by whoever retries. Message brokers solve this for you by attaching a message id you can use.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Notification API | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon ElastiCache | Redis | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon Aurora | Notification DB | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |
| Amazon SQS | Intake queue | Pub/Sub, Cloud Tasks | Service Bus queues, Queue Storage | RabbitMQ, ActiveMQ |