How does an idempotency key make a consumer safe against redelivery? What is the catch?
Sketch your own answer first, then compare it with the one below.
A strong answer
Each message carries an identifier that is the same on every attempt. The consumer stores the identifiers it has applied. Before acting it checks the store. If the key is present, it skips the effect and acks.
The catch is atomicity. The key must be written in the same transaction as the effect. If the effect happens and the crash comes before the key is stored, the retry repeats the effect. If the key is stored first and the effect fails, the effect is lost.
Keys also expire, so the window must outlast the longest possible redelivery. And an effect outside your database, such as an email, stays safe only if the other system honours the key.
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.
- Martin Kleppmann (2017). Designing Data-Intensive Applications.