Design the consumer side of a payment queue so that no customer is charged twice and no payment is lost.
Sketch your own answer first, then compare it with the one below.
A strong answer
Use at-least-once delivery so nothing is lost, and make the charge idempotent so repeats do nothing. Attach a payment identifier to the message at the producer, before the first send, so it is the same on every retry.
In the consumer, charge through an API that accepts the identifier as an idempotency key. If you also keep your own record, write the key and the state change in one database transaction. Ack only after both are done.
Cover the gaps. A crash after the charge and before the record needs the gateway to remember the key, or a way to look up the charge by key on retry. Keys must outlive the longest redelivery. Add a dead-letter queue and reconciliation against the gateway's records, because no design removes the need to check.
Sources
- J. H. Saltzer, D. P. Reed, D. D. Clark (1984). End-to-end arguments in system design.
- Tyler Akidau and others (2013). MillWheel: fault-tolerant stream processing at internet scale.
- Neha Narkhede (2017). Exactly-once Semantics are Possible: Here's How Apache Kafka Does it.