Idempotency: safe to retry
Make payments and orders safe when the same request arrives twice.
Retries are certain
Networks drop replies. The client retries, a queue redelivers, a user double-clicks. If each attempt charges again, customers pay twice.
Idempotency keys
The client sends a unique key with the request. The server stores the key with the result the first time. A repeat with the same key returns the stored result instead of acting again.
charge(key, amount):
if seen(key): return resultFor(key) // a retry: no second charge
result = gateway.charge(amount)
save(key, result) // in the same transaction as the charge record
return result
Store it atomically
Saving the key and recording the charge must happen together. If the server crashes between them, a retry could charge again.
Key takeaways
- Assume every request may arrive twice.
- An idempotency key turns a retry into a lookup.
- Save the key and the effect in one transaction.
Try it in the simulator: Survive a database failure without losing payments
Put this concept into practice on Design Payment System:
- Build Client → Load balancer → API servers → PostgreSQL, with payment calls going through Kafka and Workers, and run it.
- Add the fault "Database primary failure" and run again. With no replica, writes fail until the database comes back.
- Give PostgreSQL a read replica and run the fault again. Then set its replication to synchronous and run once more.
What to watch: With an asynchronous replica the database fails over, but payments the old primary had confirmed are lost and some reads are stale, so the run still fails. With synchronous replication nothing confirmed is lost and the run passes. For money, a confirmed write must not disappear.
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- A payment request times out and the app retries with the same idempotency key. What should the server do?
- Why save the idempotency key in the same transaction as the charge?