An idempotency key is a client-generated unique identifier attached to a mutating HTTP request (POST, PUT, PATCH) so that the server can detect retries and return the same response without re-executing the operation. This pattern is critical for payment APIs, order creation, and any non-idempotent operation that may be retried due to network failure.
How idempotency keys work
Client Server
| |
|-- POST /orders |
| Idempotency-Key: <uuid-v7-1> --> |-- check store: miss
| |-- execute operation
| |-- store response keyed by uuid-v7-1
|<-- 201 Created ------------------- |
| |
[network failure — client retries] |
| |
|-- POST /orders |
| Idempotency-Key: <uuid-v7-1> --> |-- check store: HIT
|<-- 201 Created (cached) ---------- | (no re-execution)
UUID v7 as idempotency key
import { v7 as uuidv7 } from 'uuid';
// Client: generate UUID v7 before the first attempt
const idempotencyKey = uuidv7();
async function createOrder(order: OrderRequest, key = idempotencyKey) {
const response = await fetch('/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': key, // UUID v7
},
body: JSON.stringify(order),
});
return response.json();
}
// Retry with the same key — server deduplicates
await createOrder(order, idempotencyKey); // first attempt
await createOrder(order, idempotencyKey); // retry — same result
Server-side: TTL from UUID v7 timestamp
// Extract key age from UUID v7 — no created_at column needed
function getKeyAgeMs(uuidV7Key: string): number {
const hex = uuidV7Key.replace(/-/g, '').slice(0, 12);
const createdMs = parseInt(hex, 16);
return Date.now() - createdMs;
}
// Middleware: validate and deduplicate
async function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {
const key = req.headers['idempotency-key'] as string;
if (!key) return next();
// Reject stale keys (older than 24 hours)
const ageMs = getKeyAgeMs(key);
if (ageMs > 86_400_000) {
return res.status(422).json({ error: 'Idempotency key expired' });
}
// Check store
const cached = await redis.get(`idempotency:${key}`);
if (cached) {
return res.status(200).json(JSON.parse(cached)); // replay cached response
}
// Execute and cache
res.on('finish', async () => {
if (res.statusCode < 500) {
const ttlMs = 86_400_000 - ageMs; // remaining TTL
await redis.set(
`idempotency:${key}`,
JSON.stringify(res.locals.responseBody),
'PX', ttlMs,
);
}
});
next();
}
Idempotency key patterns
| Pattern | Description |
|---|---|
| Client-generated UUID v7 | Client generates before first attempt; retries reuse same key |
| Server-generated token | Server issues a token; client must fetch before POST |
| Request hash | Hash of request body; fragile if body changes |
UUID v7 client-generated keys are the most common and robust pattern. See UUID as Idempotency Keys for implementation details.
Cloudflare Workers KV — TTL from UUID v7
// TTL derived from UUID v7 timestamp — no separate expiry metadata
const createdMs = parseInt(idempotencyKey.replace(/-/g, '').slice(0, 12), 16);
const ageMs = Date.now() - createdMs;
const ttl = Math.max(86400 - Math.floor(ageMs / 1000), 3600);
await env.IDEMPOTENCY.put(idempotencyKey, JSON.stringify(result), {
expirationTtl: ttl, // seconds
});
See ServerlessConf 2026 for the edge idempotency pattern.
Further reading
- UUID as Idempotency Keys — Full Implementation Guide
- ServerlessConf 2026 — UUID v7 at the Edge
- UUID v7 in Serverless — Lambda, Functions, Edge
- Write Skew — Concurrency Anomaly
Frequently asked questions
Why is UUID v7 preferred over UUID v4 for idempotency keys?
UUID v4 is entirely random — idempotency records keyed by UUID v4 require a separate created_at column or TTL hint to expire old records. UUID v7 embeds a 48-bit Unix millisecond timestamp: the server can extract creation time directly from the key with parseInt(key.replace(/-/g, '').slice(0, 12), 16) and compute the TTL without any additional metadata. This simplifies idempotency stores in Redis, DynamoDB, and Cloudflare KV. See UUID as Idempotency Keys.
How long should an idempotency key be valid?
Stripe recommends 24 hours. The exact window depends on your retry policy: keys must remain valid for at least the maximum retry interval plus network timeout. UUID v7's timestamp lets you compute the key's age on the server: Date.now() - createdMs where createdMs is extracted from the UUID v7 key. Reject keys older than your window: if (ageMs > 86_400_000) return 422. See UUID as Idempotency Keys.
What HTTP header should I use for idempotency keys?
Use Idempotency-Key (the Stripe/IETF convention) for financial and mutating operations. Some APIs use X-Idempotency-Key. The IETF draft for HTTP idempotency keys specifies the canonical header name as Idempotency-Key. The server stores the key, checks for duplicates, and returns the cached response if the key is already known. See UUID as Idempotency Keys.