Idempotency keys, retries and exponential backoff
Networks fail, so clients retry. Idempotency makes a retry safe (no double charges), and backoff with jitter makes retries polite (no stampede on a recovering server).
In one sentence
An operation is idempotent if doing it twice has the same effect as doing it once. With an idempotency key, the server recognizes a retry and returns the original result instead of charging, booking or sending again.
The problem: a lost answer
The app sends "charge €60". The server charges the card, but the response is lost (tunnel, timeout, app killed). From the phone, a lost request and a lost response look identical. If it retries, the customer may pay twice. If it doesn't, the order may be lost.
Idempotency keys
- The client generates a unique key per intent (a UUID when the user taps Pay) and sends it in a header:
Idempotency-Key: a1f3…. - Every retry of that intent reuses the same key.
- The server stores
key → result(in the database, ideally in the same transaction as the charge, or in Redis with an expiry such as 24 h). - If the key was already processed, it returns the stored result. If it's being processed right now, it answers 409 or waits.
Stripe's API works this way. Some operations are idempotent by nature: PUT /users/42 {name} or "set status to shipped" can run twice safely. "Add €10" or "insert a row" can't, unless you add a key or a unique constraint.
Retrying politely: exponential backoff and jitter
If a server goes down and 100,000 clients retry every second, they'll knock it over again the moment it comes back (a thundering herd). Instead, wait longer after each failure, and add randomness so clients don't retry in sync.
async function withRetry<T>(fn: () => Promise<T>, max = 5) {
for (let attempt = 0; ; attempt++) {
try { return await fn(); }
catch (err) {
if (attempt >= max || !isRetryable(err)) throw err;
const cap = Math.min(30_000, 200 * 2 ** attempt); // 200ms, 400ms, 800ms…
await sleep(Math.random() * cap); // "full jitter"
}
}
}- Retry only retryable errors: timeouts, 429, 502, 503. Never a 400 or 401.
- Respect
Retry-Afterwhen the server sends it. - Cap the attempts and the total time. Retries at every layer multiply: 3 layers × 3 retries = 27 calls.
- A circuit breaker stops calling a dependency that keeps failing, and tries again later.
It's everywhere in distributed systems
Queues and logs deliver at least once, webhooks are resent, and mobile apps retry on bad networks. The safe default is to assume every message may arrive twice and make the handler idempotent: store processed message IDs, use unique constraints (UNIQUE(order_id)), or write with upserts.
Key takeaways
- 01A client can't tell a lost request from a lost response, so retries are unavoidable.
- 02An idempotency key per intent lets the server return the original result instead of repeating the action.
- 03Retry only retryable errors, with exponential backoff, jitter and a limit.
- 04Assume at-least-once delivery everywhere and make consumers idempotent.
Check your understanding
1 of 3
What does idempotent mean?
Related concepts
SQS vs SNS
SQS stores messages until one consumer pulls and processes each of them; SNS pushes each message to every subscriber immediately and doesn't store it.
8 min read →Kafka vs queues
A queue (SQS, RabbitMQ) deletes each message once one consumer handles it. A log (Kafka, Kinesis) keeps events in order for days; every consumer group tracks its own offset, so many services read the same stream and can replay it.
7 min read →Rate limiting
A rate limiter caps how many requests a client can make in a period ("100 per minute") and answers the rest with 429 Too Many Requests, so one client can't take the system down for everyone.
6 min read →