How can you use Kafka to enable event sourcing in a microservices architecture?
Instruction: Discuss the principles of event sourcing and how Kafka can be utilized to implement it in a microservices ecosystem.
Updated
Official answer
Event sourcing stores accepted domain changes as the authoritative event sequence from which state can be rebuilt. Publishing notifications after updating an ordinary database is event-driven integration; it is not automatically event sourcing.
For an order aggregate, events such as OrderCreated and ItemAdded can rebuild its current state. Define who validates commands, enforces aggregate versions and serializes conflicting changes. A Kafka key can preserve partition order, but it does not by itself provide an expected-version append check or prevent two services from accepting conflicting commands.
Kafka can distribute an event history and feed independent projections. Decide whether Kafka or another event store is authoritative and use an explicit publication protocol; avoid an uncoordinated database-plus-Kafka dual write. Preserve event IDs, aggregate sequence and schema versions, and make projection updates replay-safe.
Retention and compaction are critical. Compaction keeps a keyed latest-state history according to its policy, not every domain event; finite retention can erase events needed for a rebuild. Preserve complete required history or validated snapshots plus all later events, with appropriate archive and restore procedures.
Rebuild projections into an isolated target and reconcile them before cutover. Replay must not resend payments or emails. Manage schema interpretation and recorded external facts so historical replay remains meaningful. Consumers can be temporarily behind one another; events do not create instantaneous cross-service consistency.
Evaluate rebuild time, projection lag, conflict handling and operational cost against simpler persistence. Use event sourcing when authoritative history and reconstruction justify those obligations.
Event sourcing definition and replay, Kafka compaction semantics, retention configuration