HAMZA KAREEM / CONCEPTS hamzawi.dev

Lesson 31 min read

Idempotency Keys

System designAPI design / system design

What it is

An idempotency key is a unique client-generated token (often a UUID) sent with a write request so the server can safely retry it. If the same key arrives twice, the server returns the original result instead of performing the action again.

Why it matters

Networks are unreliable: a request can succeed on the server but the response gets lost, so the client retries. Without idempotency, that retry creates a duplicate charge, order, or email. Stripe, PayPal, and most payment APIs require this exact mechanism.

Example

Client sends:

POST /charges
Idempotency-Key: 7b3f-9a21-...
{ "amount": 5000 }

Server logic:

key = request.header('Idempotency-Key')
if (cache.has(key)) return cache.get(key)   // replay stored response
result = chargeCard(amount)
cache.set(key, result, ttl=24h)
return result

The retry with the SAME key returns the first charge, never a second one.

Common mistakes

  • Generating the key on the server (it must come from the client, before the first attempt, and stay constant across retries).
  • Caching only on success — you must also store/lock in-flight requests, or two concurrent retries both charge.
  • No TTL or scoping the key per-user, leading to unbounded storage or cross-user collisions.

Your exercise

Sketch the server pseudocode for handling TWO identical requests with the same idempotency key arriving at the SAME time (a race). What do you store, and how do you make the second one wait for or replay the first?