Video in progress
If an old event reaches a consumer after a newer one (a retry, a replay, or from another topic), what do you do so it doesn't overwrite the new data with the old?
I add the aggregate version to the event, and the consumer applies only a version greater than the one it has stored. That way a late or repeated event is ignored, and the state doesn't go backward.
📖 Answer
Keeping order with the partition key is good, but it doesn't always suffice: a message resent from the DLT, an event from another topic, replaying a topic, the period after the partition count was increased. Then CustomerUpdated{address: old} arrives after CustomerUpdated{address: new}, and the copy in the consumer goes stale.
The solution is a monotonic version of the aggregate in every event:
{"customerId": 42, "version": 17, "address": "Toshkent, Chilonzor"}
On the producer side the version is the aggregate's @Version column or the sequence number in the event store. The consumer then does a conditional update:
UPDATE customer_copy
SET address = :address, version = :version
WHERE customer_id = :id AND version < :version;
If 0 rows change, the event is stale and is ignored. If it might also be a new customer, in PostgreSQL do it in a single statement with INSERT ... ON CONFLICT (customer_id) DO UPDATE ... WHERE customer_copy.version < EXCLUDED.version.
Subtle points:
- A timestamp can't replace a version: different servers' clocks differ, and two changes can happen in the same millisecond.
- If an event carries only a delta (
PhoneChanged) rather than the full state, you need to detect a skipped version. If 17 arrives after 15, 16 is missing: you have to re-request it or wait. Full-state events are much simpler in this respect. - A delete event should have a version too, and the record should stay as a "tombstone"; otherwise a late
Updatedbrings a deleted customer back to life.
Bonus: this makes the consumer idempotent too. If the same event arrives twice, the second one fails the version < 17 condition.
Sign up to mark studied questions and save your progress.