Consumers update a customer's address from events. A redelivered old event overwrote a newer address. How do you prevent that?
Sketch your own answer first, then compare it with the one below.
A strong answer
Redelivery can hand a consumer an old event after a newer one was applied. Being idempotent is not enough here, because applying the old event is a legitimate first time for that event. What is missing is an ordering check.
Attach a monotonic version to each entity's events: a sequence number from the producer, or the entity's version column. The consumer applies an update only if the event's version is higher than the stored one. In SQL that is a conditional write, such as updating where the stored version is lower, so the check and the write are one atomic step.
Where events cannot carry a version, a timestamp from the source of truth can serve, with the usual care about clock skew. Keying messages by customer id keeps one customer's events in one partition, which makes the stream mostly ordered and shrinks the window where a late duplicate can appear.
Last, store the version even when you skip an event. Otherwise a very old duplicate could arrive after the record has been cleared.
Sources
- Martin Kleppmann (2017). Designing Data-Intensive Applications.
- J. H. Saltzer, D. P. Reed, D. D. Clark (1984). End-to-end arguments in system design.