← All lessons
How idempotency works
One key, one charge
App
Payments API
Key store
checkout.js
const key = crypto.randomUUID();// the same key on every retryawait withRetry(() => fetch("/payments", { method: "POST", headers: { "Idempotency-Key": key }, body: JSON.stringify({ amount: 2000 }),}));server.js
app.post("/payments", async (req, res) => { const key = req.get("Idempotency-Key"); const seen = await keys.get(key); if (seen) { res.set("Idempotent-Replayed", "true"); return res.status(seen.status).json(seen.body); } await keys.insert(key, { state: "processing" }); const charge = await card.charge(req.body.amount); await keys.done(key, { status: 201, body: charge }); res.status(201).json(charge);});Send it yourself reuse a key, race it, change the body
Response
Key store
Charges
Real APIs keep keys for about 24 hours. A retry after that counts as a new payment
idempotency.js
async function handle(key, body) { if (!key) return charge(body); const rec = await keys.get(key); if (rec && rec.hash !== hash(body)) return { status: 422 }; // key reused with another body if (rec?.state === "processing") return { status: 409 }; // first one hasn't finished if (rec) return { ...rec.response, replayed: true }; // insert fails if the key exists, so two racers can't both get here await keys.insert(key, { hash: hash(body), state: "processing" }); const response = await charge(body); await keys.update(key, { state: "done", response }); return response;}Same request, sent again which ones are safe to repeat
Cart after each send
The answer changed to 404, but the cart didn't. Idempotent is about the state, not the reply
cart.http
// sets a value: repeat it all you likePUT /cart/items/42 { "qty": 2 } // adds each time it arrivesPOST /cart/items/42/add { "qty": 1 } // gone is gone, the second one says 404DELETE /cart/items/42 // the key turns an add into a one-time addPOST /cart/items/42/add { "qty": 1 }Idempotency-Key: 5f0c2a9e-…Topics
Next: How cache-aside works
Open lesson