Idempotency middleware
Middleware that makes POST /payments safe to retry. Clients send an Idempotency-Key header, and the same key must never produce a second charge — including when two retries arrive in the same millisecond.
What must a stored idempotency key be scoped by?
- The key alone — clients generate UUIDs
- The key plus the authenticated caller and the endpoint
- The key plus a timestamp
- The key plus the server instance that handled it
A globally scoped key lets one tenant key collide with another and replay a response belonging to someone else — a data leak wearing a cache hit as a disguise. Scoping to caller and endpoint also catches one client reusing a key across two different operations, and none of it depends on trusting clients to generate good UUIDs.
Assign each responsibility.
- Intercept the request and decide replay or proceed
- IdempotencyMiddleware
- Persist key to outcome, atomically
- IdempotencyStore
- Hash the request body to detect a key reused with different content
- RequestFingerprint
- Hold the status code and body to be replayed later
- ResponseRecord
- Expire records once the key is old enough to be safe
- IdempotencyStore
Keeping this as middleware means no handler has to remember it, which is the only version that stays correct across a hundred endpoints. The fingerprint exists because a key alone cannot distinguish "the client retried" from "the client reused a key for a different payment" — and those two need opposite responses.
Two retries of the same request arrive simultaneously and no record exists yet. What stops both charging?
- Check for a record, then insert one if absent
- Insert an in-progress record atomically; the loser waits or gets a 409
- A lock held in application memory
- Rejecting one of them at the load balancer
Check-then-insert leaves a window where both requests find nothing and both proceed — Tier 2 double-booking bug, now at HTTP scale. The insert has to be the check: a unique constraint on the key means exactly one request creates the record and the other fails loudly, at which point it can wait for the outcome or tell the client the request is already in flight.
A key that already charged 500 arrives again, with a body asking for 900. What should the middleware return?
- The stored 500 response
- A 409, because the key was reused with different content
- A new 900 charge
- A 400 asking the client for a fresh key
Replaying the old response tells the client its 900 request succeeded when nothing of the sort happened — worse than any error you could return. A fingerprint mismatch means the client has a bug, and the honest answer is to refuse and say why. Silently doing something other than what was asked is the exact failure mode idempotency exists to prevent.