πŸ’¬
βœ‰οΈ
πŸ“Έ
▢️

Loading…

Design a payment system: ledgers, webhooks, and idempotency

PaymentGuided Mode

Step 6 β€” Idempotency Layer: Fixing Duplicate Charges

Request Flow

1

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.

2

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.

3

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