Designing HTTP APIs · mid
Idempotency keys: charge exactly once
An idempotency key is a unique id the client sends with a non-idempotent request (like POST /payments) so the server can store the first result and return that same result for any retry, instead of doing the work twice.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Why: networks fail after the server did the work but before the client got the reply. The client must retry, and without a key a retry charges twice.
- Flow: client creates a UUID per user action and sends Idempotency-Key: <uuid>. Server: if the key is new, store it as 'in progress' with a fingerprint (hash) of the request, do the work, store the response. If the key exists and finished, return the stored response. If it is still in progress, wait or answer 409.
- Same key with a different body is a client bug: reject it (Stripe returns an error; 422 or 409 are common).
- Store keys with a TTL (Stripe keeps them at least 24 hours), scoped per user or account. A unique constraint in the database (or Redis SET NX) makes the 'first one wins' check atomic.
- If the work failed with a retryable error, delete the key so the retry runs again; if it failed for a final reason, store that error response.
- The same idea protects webhooks and queue consumers (dedupe by event id) and double-clicks on 'Pay' (disable the button and send the same key).
- An IETF draft standardises the Idempotency-Key header; Stripe, Razorpay-style payment APIs and Adyen use the pattern.
The red pen
Common traps: mistake → fix
Mistake: Disabling the button is enough
Fix: retries, double taps on slow networks and app restarts still send duplicates; the server must dedupe.
Mistake: Check 'does this payment exist?' then insert
Fix: two concurrent requests both pass the check; use an atomic insert or lock.
Mistake: Generate the key on the server
Fix: the client must generate it, so the retry carries the same key.
Easy to hard
Questions interviewers ask, easy to hard
- A user double-clicks 'Pay'. How do you make sure they are charged once?
- What is an idempotency key and who generates it?
- Two requests with the same key arrive at the same moment. What happens?
- Same key, different amount. What do you return?
- How long do you keep keys, and where?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.