Idempotency keys in payment systems: how Stripe and Uber prevent double charging
Why automatic network retries cause catastrophic duplicate payments, and how distributed locks, unique UUID headers, and Redis response caching enforce exactly-once execution.
Imagine a user booking a ride on Uber or paying for an item on Shopify. They tap the “Pay $50” button on their mobile phone.
At that exact millisecond, their phone switches from Wi-Fi to cellular data. The payment gateway successfully charges their credit card and commits the transaction, but the returning HTTP 200 OK response packet is dropped over the air.
Seeing a timeout error, the mobile client application triggers an automatic network retry, or the impatient customer taps the “Pay” button a second time.
Without architectural protection, the server processes the second request as a new transaction, charging the customer’s card $100 instead of $50.
1. HTTP Methods and Idempotency
An operation is idempotent if making the same request multiple times produces the exact same side effects and end state on the server.
HTTP IDEMPOTENCY MATRIX:
┌─────────┬──────────────┬─────────────────────────────────────────────────┐
│ Method │ Idempotent? │ Behavior on 10 Retries │
├─────────┼──────────────┼─────────────────────────────────────────────────┤
│ GET │ YES │ Safe read; server state unchanged │
│ PUT │ YES │ Overwrites resource with exact payload 10 times │
│ DELETE │ YES │ Deletes resource; subsequent calls return 404/204│
│ POST │ NO │ Creates 10 new database records / 10 charges! │
└─────────┴──────────────┴─────────────────────────────────────────────────┘
Because POST endpoints are non-idempotent by default, critical payment and order APIs must enforce idempotency at the protocol level.
2. The Idempotency Key Architecture
The industry-standard solution (pioneered by Stripe, IETF RFC draft draft-ietf-httpapi-idempotency-key-header) uses the Idempotency-Key HTTP request header:
POST /v1/charges HTTP/1.1
Host: api.stripe.com
Authorization: Bearer sk_live_...
Idempotency-Key: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
Content-Type: application/json
{
"amount": 5000,
"currency": "usd",
"source": "tok_visa"
}
┌───────────────────────────────┐
│ Client generates UUID Key │
│ Header: Idempotency-Key: <ID> │
└───────────────┬───────────────┘
│
▼
┌───────────────────────────────┐
│ API Gateway / Auth Layer │
└───────────────┬───────────────┘
│
▼
┌───────────────────────────────────┐
│ Redis / Distributed Key Check │
└─────────────────┬─────────────────┘
│
┌────────────────────────┼────────────────────────┐
│ │ │
[Key NOT Found] [Key: "PROCESSING"] [Key: "COMPLETED"]
│ │ │
▼ ▼ ▼
1. Acquire Lock (SETNX) Return HTTP 409 Conflict Replay Cached 200 OK
2. Execute Payment Charge or hold connection (Skip backend execution!)
3. Save Response in Redis (Prevents race condition)
4. Return HTTP 200 to client
3. Implementing Distributed Idempotency Locks
To handle race conditions where 5 identical retry requests arrive within 10 milliseconds of each other, the server must use an atomic distributed lock in Redis:
import { Redis } from "ioredis";
const redis = new Redis();
async function handleChargeRequest(req, res) {
const idempotencyKey = req.headers["idempotency-key"];
if (!idempotencyKey) {
return res.status(400).json({ error: "Missing Idempotency-Key header" });
}
const cacheKey = `idempotency:${idempotencyKey}`;
// Step 1: Check if this idempotency key already finished
const existingRecord = await redis.get(cacheKey);
if (existingRecord) {
const { status, body } = JSON.parse(existingRecord);
return res.status(status).json(body); // Instant cache replay!
}
// Step 2: Acquire distributed lock to prevent parallel double-execution
// SET with NX (Only if Not Exists) and 60s expiration
const lockAcquired = await redis.set(`lock:${cacheKey}`, "LOCKED", "EX", 60, "NX");
if (!lockAcquired) {
// Another concurrent thread is currently charging this exact key!
return res.status(409).json({ error: "Request is currently being processed. Please wait." });
}
try {
// Step 3: Execute the real financial transaction
const chargeResult = await processPaymentGateway(req.body);
// Step 4: Cache the final result with a 24-hour TTL
await redis.set(
cacheKey,
JSON.stringify({ status: 200, body: chargeResult }),
"EX",
86400 // 24 hours
);
return res.status(200).json(chargeResult);
} finally {
// Release the temporary execution lock
await redis.del(`lock:${cacheKey}`);
}
}
4. Key Takeaways for Production
- Client-Generated Keys: The client application (iOS/Android/Web) must generate a single UUID per user intention (e.g. checkout submission) and persist it across retries.
- Payload Validation: Store a hash of the request body with the key. If a client sends the same idempotency key with different amounts or parameters, reject the request with
422 Unprocessable Entity. - Response Caching Window: Retain idempotency records in Redis or PostgreSQL for at least 24 to 48 hours to cover prolonged network outages and manual retries.
Test Your Understanding
Quick architectural scenario challenge based on this breakdown.
A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.
Q1.How should a downstream dependency failure be handled to protect upstream service availability?
Comments –
Sign in to share your thoughts
Nothing yet. Be the first.