Every networked system eventually sends the same request twice. A mobile client times out and taps again, a load balancer retries a slow upstream, or a message broker redelivers after a consumer crash. Interviewers ask about idempotency and retries because the answers show whether you can reason about partial failure, which is one of the most common sources of real production incidents: double charges, duplicate shipments, retry storms. This guide covers the ideas behind strong answers: what idempotency actually guarantees, how idempotency keys are stored and claimed atomically, which failures are safe to retry, how to back off without synchronising clients, how consumers survive at-least-once delivery, and how to stop retries from turning a small outage into a large one. Examples are in TypeScript because the concepts are language-agnostic.
Study order
If time is short, go in this order.
- What idempotency guarantees, and what it does not
Every other answer depends on defining idempotency precisely as an effect on state, separate from safety and from identical responses.
- Idempotency keys: client-generated identity for unsafe requests
The most common interview design question: make a non-idempotent create endpoint safe to retry.
- Claiming keys atomically and committing with the business write
Separates mid from senior answers: concurrent duplicates and partial commits are where naive designs break.
- Which failures to retry, and the ambiguous timeout
Knowing that a timeout means unknown, not failed, is the core reasoning interviewers listen for.
- Idempotent consumers under at-least-once delivery
At-least-once delivery is the default in queue-based systems, so this appears in almost every event-driven discussion.
- Exponential backoff with jitter and a bounded attempt count
Expected baseline knowledge; you should be able to write it and justify jitter quickly.
- Retry amplification, retry budgets and circuit breakers
Shows production maturity: understanding how retries cause or deepen outages.
- Natural idempotency: absolute values, upserts and versioned writes
Often the simplest correct design, and it brings in ordering and optimistic concurrency.
- Propagating idempotency to downstream calls
Completes the picture for workflows that call external systems you cannot wrap in your transaction.
What idempotency guarantees, and what it does not
An operation is idempotent when applying it once or many times leaves the system in the same state. PUT /profiles/42 with a full body is idempotent; POST /wallets/42/top-ups usually is not, because each call adds money. Idempotency is about the effect on server state, not about identical responses: a second DELETE may return 404 instead of 204 and still be idempotent.
Keep it separate from safety. A safe method (GET, HEAD) has no intended side effects; an idempotent one may have side effects but they do not accumulate. HTTP defines GET, HEAD, OPTIONS, PUT and DELETE as idempotent, but that is a contract your implementation must honour. A GET handler that increments a counter on every call breaks the contract, and proxies that retry GETs will skew the number.
The practical reason idempotency matters is that retries are the only way to recover from lost responses, and you can only retry freely what is idempotent. So you either make the operation naturally idempotent (set a value instead of adding to it) or attach an identity to the request so duplicates can be recognised.
TypeScript
type Account = { id: string; credits: number; appliedGrants: Set<string> };
// Not idempotent: every retry adds the amount again
function addCredits(acc: Account, amount: number): void {
acc.credits += amount;
}
// Idempotent: the grant id turns repeats into no-ops
function applyGrant(acc: Account, grantId: string, amount: number): void {
if (acc.appliedGrants.has(grantId)) return;
acc.appliedGrants.add(grantId);
acc.credits += amount;
}
const acc: Account = { id: "acc_17", credits: 0, appliedGrants: new Set() };
applyGrant(acc, "grant_2024_06", 50);
applyGrant(acc, "grant_2024_06", 50); // client retry after a timeout
console.log(acc.credits); // 50A support tool for the Quillfern study app grants 50 credits; attaching a grant id makes the retry harmless.
Traps
- Claiming an endpoint is idempotent because it returns the same response. The test is the state after N calls, not the payload.
- Assuming every PUT or DELETE in your codebase is idempotent because the HTTP spec says so. A PUT that appends to a list or triggers an email on each call is not.
- Forgetting side effects outside the main write: audit events, webhooks and notifications can still fire twice even if the row is deduplicated.
Idempotency keys: client-generated identity for unsafe requests
For operations that are inherently non-idempotent, such as creating a payout, the client generates a unique key (typically a UUIDv4) per logical operation and sends it in a header like Idempotency-Key. The server records the key with the outcome. A retry carrying the same key gets the stored response instead of executing again.
A solid implementation stores three things per key: a fingerprint of the request body, a state (in progress or completed), and the final status and body. If the same key arrives with a different payload, reject it with 422 because the client has a bug. If it arrives while the first attempt is still running, return 409 so the client backs off. If it is completed, replay the stored response exactly.
Decide what to do on failure. Deterministic errors such as validation failures are usually stored and replayed, so the client sees a consistent answer. Transient failures where nothing was committed should release the key so a retry can try again. Keys also need a retention period, commonly 24 hours to a few days, long enough to cover realistic client retry windows.
TypeScript
import { createHash, randomUUID } from "node:crypto";
type Result = { status: number; body: unknown };
type Entry =
| { state: "in_progress"; fingerprint: string }
| { state: "done"; fingerprint: string; result: Result };
const keys = new Map<string, Entry>();
function fingerprint(body: { accountId: string; cents: number }): string {
return createHash("sha256").update(`${body.accountId}|${body.cents}`).digest("hex");
}
async function createPayout(key: string, body: { accountId: string; cents: number }): Promise<Result> {
const fp = fingerprint(body);
const existing = keys.get(key);
if (existing) {
if (existing.fingerprint !== fp) return { status: 422, body: { error: "key reused with a different payload" } };
if (existing.state === "in_progress") return { status: 409, body: { error: "original request still running" } };
return existing.result;
}
keys.set(key, { state: "in_progress", fingerprint: fp });
try {
const payout = { id: `po_${randomUUID()}`, ...body };
const result = { status: 201, body: payout };
keys.set(key, { state: "done", fingerprint: fp, result });
return result;
} catch (err) {
keys.delete(key); // nothing committed: allow a clean retry
throw err;
}
}
const key = randomUUID();
createPayout(key, { accountId: "acct_9", cents: 12500 })
.then(() => createPayout(key, { accountId: "acct_9", cents: 12500 }))
.then((r) => console.log(r.status)); // 201, replayedPayout API for a fictional marketplace, Brindle: in-memory to show the state machine; production needs the atomic store in the next concept.
Traps
- Generating the key on the server or per HTTP attempt. It must be created once per logical operation on the client and reused across every retry.
- Fingerprinting with
JSON.stringifyon arbitrary objects. Key order can differ between clients, so build the fingerprint from canonical fields. - Storing transient 5xx outcomes as final. The client then replays a failure forever even though the operation never ran.
- Expiring keys sooner than clients can retry. A mobile app that queues requests offline for hours will create duplicates after a short TTL.
Claiming keys atomically and committing with the business write
The check-then-set in an in-memory map is a race once you have more than one server. Two retries hitting different instances can both see no key and both execute. The claim has to be atomic in a shared store: a unique constraint with INSERT ... ON CONFLICT DO NOTHING in Postgres, a conditional put in DynamoDB, or SET key value NX in Redis.
The strongest pattern puts the key row and the business write in the same database transaction. Either both commit or neither does, so you never end up with a recorded key and no shipment, or a shipment with no key. In Postgres, a second transaction inserting the same key blocks until the first finishes; if the first commits it sees the conflict, if it rolls back it proceeds.
When the side effect lives outside your database, such as a call to a payment provider, a single transaction is impossible. Then you record an in-progress state first, call the provider with a downstream key, and record the result after. A sweeper can later resolve keys stuck in progress by querying the provider.
TypeScript
import { Pool } from "pg";
const pool = new Pool();
export async function recordShipment(key: string, orderId: string, carrier: string) {
const client = await pool.connect();
try {
await client.query("BEGIN");
const claim = await client.query(
"INSERT INTO idempotency_keys (key, created_at) VALUES ($1, now()) ON CONFLICT (key) DO NOTHING",
[key]
);
if (claim.rowCount === 0) {
await client.query("ROLLBACK");
const row = await client.query("SELECT id FROM shipments WHERE idempotency_key = $1", [key]);
return { duplicate: true, shipmentId: row.rows[0]?.id };
}
const res = await client.query(
"INSERT INTO shipments (order_id, carrier, idempotency_key) VALUES ($1, $2, $3) RETURNING id",
[orderId, carrier, key]
);
await client.query("COMMIT");
return { duplicate: false, shipmentId: res.rows[0].id };
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}A warehouse service, Kestrel Fulfilment, claims the key and inserts the shipment in one transaction.
Traps
- Using a cache with eviction as the only dedup store. If the key is evicted under memory pressure, the duplicate executes.
- Writing the key in one transaction and the business row in another. A crash between them leaves state that no retry can repair cleanly.
- Using a Redis
SET NXlock without a TTL or with a TTL shorter than the work. The lock expires mid-request and a retry runs concurrently.
Which failures to retry, and the ambiguous timeout
Not every error deserves a retry. Most 4xx responses mean the request is wrong and will fail again: 400, 401, 403, 404, 422. Retrying them wastes capacity. 429 and 503 usually mean the server rejected the work without doing it, so they are retryable, ideally honouring a Retry-After header.
The hard case is an ambiguous outcome. If the connection was refused, the request never arrived and retrying is safe. If you sent the request and then hit a read timeout, a connection reset, a 502 or a 504, the server may have completed the work and only the response was lost. You can retry those only when the operation is idempotent or carries an idempotency key. Otherwise you have to reconcile: query the resource state before deciding.
In interviews, say this distinction out loud. A good answer separates errors into definitely failed, definitely not executed, and unknown, and attaches a different policy to each.
TypeScript
class HttpError extends Error {
constructor(public status: number, public retryAfterSec?: number) {
super(`HTTP ${status}`);
}
}
type Decision = "retry" | "retry-if-idempotent" | "fail";
function classify(err: unknown): Decision {
if (err instanceof HttpError) {
if (err.status === 429 || err.status === 503) return "retry"; // rejected before work
if ([408, 500, 502, 504].includes(err.status)) return "retry-if-idempotent"; // outcome unknown
return "fail"; // other 4xx: the request itself is wrong
}
const code = (err as { code?: string }).code;
if (code === "ECONNREFUSED") return "retry"; // never reached the server
if (code === "ECONNRESET" || code === "ETIMEDOUT") return "retry-if-idempotent";
return "fail";
}
console.log(classify(new HttpError(504))); // retry-if-idempotent
console.log(classify(new HttpError(422))); // failAn error classifier for an HTTP client used by internal services.
Traps
- Treating a client-side timeout as proof the request failed. It only proves you stopped waiting.
- Retrying 500 on non-idempotent calls by default. A bug that throws after committing will create a duplicate per retry.
- Ignoring
Retry-Afteron 429 and hammering the server on your own schedule, which often extends the throttling.
Exponential backoff with jitter and a bounded attempt count
Retrying immediately in a tight loop turns a brief hiccup into extra load at the worst moment. Exponential backoff spaces attempts out: 100 ms, 200 ms, 400 ms, and so on, capped at a ceiling so a single request does not wait minutes.
Backoff alone is not enough. If 2,000 clients fail at the same instant, pure exponential backoff makes them all retry at the same instants too, producing synchronised spikes. Jitter randomises each delay. Full jitter picks a uniform random delay between zero and the exponential ceiling, which spreads retries across the whole window.
Always bound attempts and total time. Three to five attempts is a common default for interactive paths; background jobs can retry longer but should eventually move work to a dead-letter queue for inspection. Combine the attempt limit with the caller's deadline: there is no point starting an attempt that cannot finish before the user has given up.
TypeScript
type RetryOptions = { maxAttempts: number; baseMs: number; capMs: number };
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function withRetry<T>(
fn: () => Promise<T>,
isRetryable: (err: unknown) => boolean,
opts: RetryOptions = { maxAttempts: 4, baseMs: 100, capMs: 3000 }
): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= opts.maxAttempts || !isRetryable(err)) throw err;
const ceiling = Math.min(opts.capMs, opts.baseMs * 2 ** (attempt - 1));
await sleep(Math.random() * ceiling); // full jitter
}
}
}
let calls = 0;
withRetry(
async () => {
calls++;
if (calls < 3) throw new Error("flaky");
return "ok";
},
() => true
).then((v) => console.log(v, calls)); // ok 3Generic retry helper with capped exponential backoff and full jitter.
Traps
- Retrying without a cap on attempts or total duration, which keeps dead requests alive and holds connections open.
- Adding jitter of a fixed small range (say plus or minus 10 ms) to large delays. It barely desynchronises clients.
- Retrying inside a held database transaction or lock, which extends contention for everyone else.
Retry amplification, retry budgets and circuit breakers
Retries multiply across layers. If a gateway, a service and its database client each make up to 3 attempts, one user request can turn into 27 calls against the database when it is already struggling. This is how a partial slowdown becomes a full outage. The usual rule is to retry at one layer, typically the one closest to the failure or the one that owns the idempotency key, and have the others fail fast.
A retry budget caps retries as a fraction of normal traffic. Each successful request earns a fraction of a token and each retry spends a whole one, so in steady state retries cannot exceed roughly that fraction, say 10 percent. When the dependency is healthy the budget is invisible; when it is failing, retries stop automatically instead of tripling load.
Circuit breakers complement budgets. After a threshold of failures the breaker opens and calls fail immediately for a cool-down period, then a few probe requests test recovery. Pair both with deadline propagation so downstream services stop working on requests the caller has already abandoned.
TypeScript
class RetryBudget {
private tokens: number;
constructor(private readonly max = 50, private readonly ratio = 0.1) {
this.tokens = max;
}
onRequest(): void {
this.tokens = Math.min(this.max, this.tokens + this.ratio);
}
tryRetry(): boolean {
if (this.tokens < 1) return false;
this.tokens -= 1;
return true;
}
}
const budget = new RetryBudget();
let allowed = 0;
for (let i = 0; i < 1000; i++) {
budget.onRequest();
if (budget.tryRetry()) allowed++; // every request fails and wants a retry
}
console.log(allowed); // about 150: the initial 50 tokens plus 10% of 1000Token-based retry budget for calls from a checkout service to an inventory service.
Traps
- Configuring retries independently in the SDK, the service mesh and application code, then being surprised by the multiplied load.
- Letting retries ignore the caller's deadline, so the backend keeps working on requests nobody is waiting for.
- Opening a circuit breaker per instance with tiny thresholds, so normal noise flaps it open and closed.
Idempotent consumers under at-least-once delivery
Most message brokers deliver at least once. A consumer that processes a message and crashes before acknowledging it will see that message again, and producers that retry a publish can create duplicates before it even reaches the queue. Exactly-once delivery across a network is not something you get for free; what you build is exactly-once effect through idempotent processing.
The standard pattern is an inbox or processed-messages table keyed by a stable message id. In one transaction you check the id, apply the effect and record the id. Acknowledge only after that commit. A crash before commit means the message is redelivered and processed cleanly; a crash after commit but before ack means it is redelivered and skipped.
The message id must come from the producer and stay stable across redeliveries and republishes. Broker-assigned delivery ids often change on redelivery, so they cannot be used for deduplication.
TypeScript
type PointsEarned = { eventId: string; memberId: string; points: number };
const processed = new Set<string>();
const balances = new Map<string, number>();
async function onMessage(ev: PointsEarned, ack: () => Promise<void>): Promise<void> {
if (!processed.has(ev.eventId)) {
// In production these two writes share one database transaction
balances.set(ev.memberId, (balances.get(ev.memberId) ?? 0) + ev.points);
processed.add(ev.eventId);
}
await ack(); // ack last: a crash before this triggers redelivery, which the check absorbs
}
const ev = { eventId: "evt_8812", memberId: "m_301", points: 120 };
const ack = async () => {};
onMessage(ev, ack)
.then(() => onMessage(ev, ack)) // redelivered
.then(() => console.log(balances.get("m_301"))); // 120A loyalty programme, Pebblecrest Rewards, consumes points events from a queue without double-crediting.
Traps
- Acknowledging the message before the effect is committed. A crash in between loses the message permanently.
- Deduplicating on the broker's delivery tag or receipt handle, which changes on redelivery.
- Relying on broker-level exactly-once features and assuming they cover side effects in your database or in third-party APIs.
Natural idempotency: absolute values, upserts and versioned writes
The cheapest idempotency is designing operations so repeats are harmless. Send absolute state instead of deltas: set quantity to 40 survives duplicates, add 5 does not. Use upserts keyed on a natural identifier, such as one row per order and line number, so a second insert updates instead of duplicating.
Absolute values introduce a new problem: reordering. If an old update arrives after a new one, a blind set overwrites fresh data with stale data. Attach a monotonically increasing version or sequence number and apply the write only when it is newer than what you hold. Over HTTP the equivalent is optimistic concurrency with ETag and If-Match, returning 412 when the version has moved on.
This gives you both idempotency and ordering safety without a separate dedup table, which is why event-carried state transfer often sends full snapshots with versions rather than increments.
TypeScript
type StockSnapshot = { sku: string; warehouse: string; quantity: number; version: number };
const stock = new Map<string, { quantity: number; version: number }>();
function applySnapshot(ev: StockSnapshot): "applied" | "ignored" {
const key = `${ev.warehouse}:${ev.sku}`;
const current = stock.get(key);
if (current && current.version >= ev.version) return "ignored"; // duplicate or stale
stock.set(key, { quantity: ev.quantity, version: ev.version });
return "applied";
}
console.log(applySnapshot({ sku: "LAMP-07", warehouse: "LDS", quantity: 40, version: 12 })); // applied
console.log(applySnapshot({ sku: "LAMP-07", warehouse: "LDS", quantity: 40, version: 12 })); // ignored
console.log(applySnapshot({ sku: "LAMP-07", warehouse: "LDS", quantity: 55, version: 11 })); // ignored
console.log(stock.get("LDS:LAMP-07")); // { quantity: 40, version: 12 }Stock levels for a homeware retailer's Leeds warehouse, applied as versioned snapshots.
Traps
- Using wall-clock timestamps from different machines as versions. Clock skew lets an older write win.
- Doing the version check and the write as two separate statements without a condition in the write itself, which reopens the race.
- Converting increments to absolute sets without considering concurrent writers, which turns duplicates into lost updates.
Propagating idempotency to downstream calls
Your endpoint is only as idempotent as its weakest dependency. If a retried request reaches your service, you dedupe it correctly, but you had already called a payment provider before crashing, the provider charge may have gone through. On the retry you must call the provider in a way that it recognises as the same operation.
Derive downstream keys deterministically from the incoming key plus a step name, for example a hash of the parent key and charge. Every retry of the parent produces the same child key, so the provider deduplicates on its side. Random keys generated per attempt defeat this.
For multi-step workflows, persist progress per step so a retry resumes where it stopped rather than redoing completed steps. When a dependency offers no idempotency support, fall back to reconciliation: look up whether the effect already exists, for instance by searching for a charge carrying your order reference in its metadata, before issuing a new one.
TypeScript
import { createHash } from "node:crypto";
interface PaymentProvider {
charge(req: { amountCents: number; reference: string; idempotencyKey: string }): Promise<{ chargeId: string }>;
}
function childKey(parentKey: string, step: string): string {
return createHash("sha256").update(`${parentKey}:${step}`).digest("hex");
}
async function checkout(parentKey: string, orderId: string, amountCents: number, provider: PaymentProvider) {
const { chargeId } = await provider.charge({
amountCents,
reference: orderId,
idempotencyKey: childKey(parentKey, "charge"),
});
return chargeId;
}
const seen = new Map<string, string>();
const fakeProvider: PaymentProvider = {
async charge({ idempotencyKey }) {
if (!seen.has(idempotencyKey)) seen.set(idempotencyKey, `ch_${seen.size + 1}`);
return { chargeId: seen.get(idempotencyKey)! };
},
};
checkout("req_ab12", "ord_5521", 4200, fakeProvider)
.then(() => checkout("req_ab12", "ord_5521", 4200, fakeProvider))
.then((id) => console.log(id, seen.size)); // ch_1 1A checkout service for a ticketing site passes a deterministic key to its payment provider.
Traps
- Generating a fresh UUID for the downstream call on each attempt, which makes every retry look like a new charge to the provider.
- Reusing the parent key verbatim for several different downstream calls to the same provider, which makes the second call replay the first one's response.
- Assuming a provider supports idempotency keys without checking its retention window, which may be shorter than your own.
Common questions
Short answers to the usual doubts.
Is exactly-once delivery possible?
Not across an unreliable network in the general case, because a sender cannot distinguish a lost message from a lost acknowledgement. What systems offer is exactly-once processing within a boundary, built from at-least-once delivery plus deduplication or transactional commits. Say that clearly, then explain how you get an exactly-once effect with idempotent consumers.
Should the client or the server generate the idempotency key?
The client, once per logical operation, before the first attempt. Only the client knows that two HTTP requests represent the same user intent. A server-generated key cannot link a retry to the original request because the retry arrives without it.
How long should idempotency keys be kept?
Long enough to cover the longest realistic retry window of your clients, including offline queues and background job retries. A day is a common baseline for synchronous APIs; asynchronous pipelines may need longer. Tie the TTL to measured client behaviour and document it in the API contract.
Is POST ever idempotent?
Not by HTTP definition, but you can make a specific POST endpoint behave idempotently by requiring an idempotency key or by using a natural key, such as one subscription per user and plan. The method name describes the default contract; your implementation decides the actual behaviour.
Where should retries live in a microservice chain?
Ideally at a single layer, usually the edge client or the service that owns the idempotency key, with inner layers failing fast. Retrying at every hop multiplies load geometrically. Protect the chain with a retry budget, deadlines passed downstream, and circuit breakers around fragile dependencies.
What do I return when a duplicate arrives while the original is still running?
Return a conflict status such as 409, optionally with Retry-After, so the client waits and retries for the stored result. Blocking the duplicate until the original finishes is possible but ties up connections. Executing it in parallel is the one option that is never acceptable.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Idempotency and retriesTake the test
- No double spend in a betting walletSolve the exercise
Keep reading