How it works
A client sends POST /charges for $40 and its connection times out. The charge may have failed, or succeeded with the response lost. Not retrying might leave the order unpaid. Retrying might bill the customer twice. An idempotency key resolves this: the client generates one unique value per logical operation, such as a UUID for this checkout, and sends the same value on every retry. Stripe’s API accepts one in an Idempotency-Key header.
Where the key lives decides whether this works. Keep it in the same database as the charge record, with a unique constraint on (account_id, key). A separate cache can lose or evict it, allowing a second charge. Insert the key row as in progress and commit; call the payment provider, passing the key so it can deduplicate too; then store the response on the row. A retry hits the unique constraint and gets the saved response, or a 409 while the first attempt is still running. If the server crashes after the provider call, recovery asks the provider what happened or repeats the call with the same key.
Also store a hash of the request, so the same key with a different amount is rejected rather than replayed, and keep keys longer than any client keeps retrying. The cost is a row per request and an in-progress state to recover. Already idempotent operations, such as setting a status to shipped, do not need one. Chat System uses this for retried sends, News Feed for retried posts, and Google Drive for retried upload finalization.
A checkout service keeps idempotency keys in Redis with a 24-hour TTL and writes orders to Postgres. During a Redis failover, the last second of writes is lost, and a client retries a successful order. How do you change the design?
The retry found no key, so it created a second order. Move the authoritative key into Postgres under a unique constraint on account and key, written in the same transaction as the order. Redis can stay as a shortcut for recent keys, but a miss there must fall through to Postgres, where the constraint makes the final decision.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Generate one key per logical operation and reuse it on every retry.
- Store the key durably in the database that holds the effect, under a unique constraint.
- Pass the key to external providers, since your database cannot cover their side.