Lesson 195 of 296
Idempotency and idempotency keys
What you will learn
- Why retries are dangerous for POST requests
- Idempotency keys: how they work
- Implementing them with a store and locking
- Idempotent consumers for messages and webhooks
- Edge cases interviewers ask about
On this page
The problem
A customer taps "Pay £50". The request reaches the server, the payment is taken, but the response is lost (the phone switched from Wi-Fi to mobile data). The app does not know if it worked, so it retries. Without protection, the customer is charged twice.
Networks are unreliable, and clients, load balancers and job queues all retry. So any operation that can be retried must be made safe to repeat.
Idempotency keys
The client generates a unique key for each logical operation (usually a UUID) and sends it in a header. A retry of the same operation reuses the same key.
POST /api/payments
Idempotency-Key: 3f2b8c1e-5d4a-4e7b-9b1a-0c2d3e4f5a6bThe server:
- Looks up the key.
- Not seen before: records the key as "in progress", processes the request, then stores the response (status and body) with the key.
- Seen and completed: returns the stored response without doing the work again.
- Seen but still in progress (a retry arrived while the first attempt is running): returns 409 Conflict (or waits), so the work does not run twice in parallel.
- Same key, different request body: returns an error (422), because the client is misusing the key.
Keys are stored for a limited time (Stripe keeps them for 24 hours) and scoped per user or account, so one customer's key cannot collide with another's. Stripe's API is the famous example.
An implementation
An Express middleware with a store interface (in production the store is Redis or a database table with a unique constraint on the key):
import type { Request, Response, NextFunction } from "express";
import { createHash } from "node:crypto";
type StoredResponse = { status: number; body: unknown };
type Entry = { requestHash: string; state: "in_progress" } | { requestHash: string; state: "done"; response: StoredResponse };
export interface IdempotencyStore {
claim(key: string, requestHash: string): Promise<Entry | null>;
complete(key: string, requestHash: string, response: StoredResponse): Promise<void>;
release(key: string): Promise<void>;
}
export class MemoryIdempotencyStore implements IdempotencyStore {
private entries = new Map<string, Entry>();
async claim(key: string, requestHash: string): Promise<Entry | null> {
const existing = this.entries.get(key);
if (existing) return existing;
this.entries.set(key, { requestHash, state: "in_progress" });
return null;
}
async complete(key: string, requestHash: string, response: StoredResponse): Promise<void> {
this.entries.set(key, { requestHash, state: "done", response });
}
async release(key: string): Promise<void> {
this.entries.delete(key);
}
}
export function idempotency(store: IdempotencyStore) {
return async (req: Request, res: Response, next: NextFunction) => {
const rawKey = req.header("Idempotency-Key");
if (!rawKey) {
res.status(400).json({ error: "Idempotency-Key header is required" });
return;
}
const userId = res.locals.userId ?? "anonymous";
const key = `${userId}:${rawKey}`;
const requestHash = createHash("sha256").update(`${req.method} ${req.path} ${JSON.stringify(req.body ?? null)}`).digest("hex");
const existing = await store.claim(key, requestHash);
if (existing) {
if (existing.requestHash !== requestHash) {
res.status(422).json({ error: "Idempotency-Key was already used with a different request" });
return;
}
if (existing.state === "in_progress") {
res.status(409).json({ error: "A request with this Idempotency-Key is still being processed" });
return;
}
res.setHeader("Idempotent-Replayed", "true");
res.status(existing.response.status).json(existing.response.body);
return;
}
const originalJson = res.json.bind(res);
res.json = (body: unknown) => {
if (res.statusCode >= 500) void store.release(key);
else void store.complete(key, requestHash, { status: res.statusCode, body });
return originalJson(body);
};
next();
};
}Points to explain:
claimmust be atomic ("insert if not exists"). In Redis:SET key value NX EX 86400. In SQL:INSERT ... ON CONFLICT DO NOTHINGon a unique key. Otherwise two simultaneous retries could both "claim" the key (a race condition).- On a 5xx error the key is released, so the client can retry. A 4xx response (like a validation error) is stored, because repeating the same bad request should give the same answer.
- The hash detects a reused key with a different body.
Idempotent consumers
The same idea applies to messages and webhooks. Queues usually deliver at least once (Lesson 204), and providers like Stripe may send the same webhook twice. So consumers record the IDs of processed messages (for example a processed_events table with a unique constraint) and skip duplicates. Or they make the operation naturally idempotent: "set order 5 status to paid" can run twice safely; "add £10 to the balance" cannot.
Making operations naturally idempotent
| Not idempotent | Idempotent alternative |
|---|---|
balance = balance + 10 | Record a transaction with a unique ID; the balance is the sum |
| "Create user" with POST | PUT /users/{clientGeneratedId} or a unique constraint on email |
| "Send email" | Store email_sent_at; send only if empty |
How to say it in an interview
"Clients and infrastructure retry after timeouts, so non-idempotent operations like payments can run twice. With idempotency keys, the client sends a unique key per logical operation, and the server atomically claims the key, processes once, stores the response and replays it for retries. A concurrent retry gets 409, a reused key with a different body gets 422, and keys expire after a period like 24 hours and are scoped per user. I release the key on server errors so the client can retry. For queues and webhooks I build idempotent consumers that record processed message IDs, and I prefer naturally idempotent operations."
Key words
| Word | Meaning |
|---|---|
| Retry | Sending the same request again after a failure or timeout |
| Idempotency key | A unique ID for one logical operation, reused on retries |
| Atomic | Happens completely or not at all, with no race in between |
| At-least-once delivery | Messages may arrive more than once, never zero times |
| Idempotent consumer | A message handler that safely ignores duplicates |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.