Why APIs Use Idempotency Keys (Prevent Double Payments)
🎯 The Question
"If a customer clicks 'Pay $100' and their network disconnects before receiving a response, retrying the request could double-charge their credit card. How do APIs use Idempotency Keys to solve this?"
⚡ 30-Second Elevator Pitch
In distributed systems, network timeouts are ambiguous: you don't know if the request failed before reaching the server, or if the server charged the card and only the response was lost.
An operation is Idempotent if executing it multiple times produces the exact same result as executing it once ().
GET,PUT,DELETEare naturally idempotent by HTTP standards.POSTis non-idempotent (each call creates a new record).
How Idempotency Keys Work:
- Client generates a unique UUID (
Idempotency-Key: abc-123) and sends it in the header. - Server checks Redis/Database:
- If key does not exist: Process charge, store key + cached response, return success.
- If key already exists: Skip processing and return the cached response immediately.
🧠 Under-the-Hood: Idempotent Payment Flow
🔬 Handling In-Flight Concurrent Race Conditions
What if two identical retry requests arrive simultaneously within 10 milliseconds?
- Use Atomic Locking (
SET key IN_PROGRESS NX EX 120) in Redis. - The first request acquires the lock and begins charging the card.
- The concurrent second request sees the
IN_PROGRESSstate and returnsHTTP 409 Conflictor polls until the first request completes.
📌 Comparison Matrix: HTTP Methods & Idempotency
| HTTP Method | Naturally Idempotent? | Safe (Read-Only)? | Side-Effect Behavior |
|---|---|---|---|
GET | ✅ Yes | ✅ Yes | Zero mutations |
PUT | ✅ Yes | ❌ No | Overwrites existing resource with exact payload |
DELETE | ✅ Yes | ❌ No | Deleting resource 10 times results in resource gone |
POST | ❌ No | ❌ No | Each execution creates a new entity (Requires Idempotency Key) |
💡 What Interviewers Ask Next (Follow-Up Traps)
-
"What TTL (Time-To-Live) should you set on Idempotency Keys in Redis?"
- Answer: Stripe and standard payment gateways maintain idempotency records for 24 to 72 hours. Retrying an operation after 72 hours is treated as an intentional new transaction.
-
"What happens if the client sends the same Idempotency Key with DIFFERENT payload parameters?"
- Answer: The server must hash the request body alongside the key. If the key matches an existing record but the payload body differs, the server rejects the request with
HTTP 422 Unprocessable Entity(Idempotency Key Mismatch error).
- Answer: The server must hash the request body alongside the key. If the key matches an existing record but the payload body differs, the server rejects the request with
Interview Answer: Idempotency keys prevent duplicate side-effects (like double charges) caused by network retries. The server records unique client-provided UUIDs in an atomic store (Redis), executing the transaction once and returning cached responses for any identical duplicate requests.