Design a payment system: ledgers, webhooks, and idempotency
Payment
Guided ModeStep 6 β Idempotency Layer: Fixing Duplicate Charges
Request Flow
Client sends an idempotency key
The client generates a UUID (e.g., UUID v4) per charge attempt and includes it as the Idempotency-Key header. The Idempotency store (a Redis cache) records a mapping: key β response, with a 24-hour TTL.
Cache hit: replay the stored response
On a retry, the Idempotency cache finds the key and immediately returns the stored response β no request reaches the Payment Service. Duplicate charges become structurally impossible.
Cache miss: process and store atomically
For new keys, the Idempotency cache uses a distributed lock (Redis SET NX) to claim the key before forwarding. When the response comes back, it stores it atomically. A second concurrent request with the same key blocks until the lock is released.
Why We Need This
Idempotency keys must be generated by the client, not the server β the server cannot distinguish a fresh request from a retry. The 65% hitRate here represents retried requests being safely deduplicated before touching the payment pipeline.
Key Insight
Idempotency is not a feature β it's a contract. The client owns key generation; the server owns key storage and replay. Both sides must honour the contract or the guarantee breaks.
Step 6 of 7
