Why your idempotency implementation is probably broken under concurrent load
Most backend developers know what idempotency is. Fewer get it right under concurrent load. Here's why, and what actually needs to happen. The problem Network requests fail and get retried. Your pa...

Source: DEV Community
Most backend developers know what idempotency is. Fewer get it right under concurrent load. Here's why, and what actually needs to happen. The problem Network requests fail and get retried. Your payment client times out and fires again. A webhook gets delivered twice. Your order creation endpoint runs twice and charges the customer twice. The naive fix looks like this: app.post('/orders', async (req, res) => { const key = req.headers['idempotency-key'] if (!key) return next() const existing = await store.get(key) if (existing) return res.json(existing.response) const result = await createOrder(req.body) await store.set(key, result) res.json(result) }) This looks correct. It isn't. The race condition Under concurrent load, two retries with the same key arrive simultaneously: Thread A: store.get(key) → null (key doesn't exist yet) Thread B: store.get(key) → null (key doesn't exist yet) Thread A: createOrder() (runs) Thread B: createOrder() (also runs — double charge) Thread A: store.s