Video in progress

Is it right to use Kafka as the main "source of truth" for event sourcing?

Kafka is good as an event log, but it has limits as an event store: you can't quickly read one aggregate's events by ID, and there's no optimistic check (expected version) on write. Usually the event store is a separate DB, and Kafka is used to distribute the events.

📖 Answer

Event sourcing has two core operations:

  1. Rebuilding an aggregate's state: "give me all the events of account-123".
  2. A conditional write: "if the last version is 17, write 18, otherwise it's a conflict".

Kafka does neither of them well. A partition holds millions of other keys mixed together, so reading one key means scanning the whole partition. And there's no conditional write at all: two instances can write two different version 18s at the same time.

The usual approaches:

  • Kafka Streams with a state store: the state is in local RocksDB, the changelog in a compacted topic. This works because one instance owns one partition and writes go through it. But ad-hoc queries, migrations and debugging are harder.
  • A DB event store + Kafka: events are stored in PostgreSQL with a (aggregate_id, version) unique constraint and published to Kafka through an outbox or CDC. Consistency lives in the DB, distribution in Kafka. For most teams this is what I recommend.
  • A dedicated event store (EventStoreDB, Axon Server), if the team is ready for it.

Then there's the question of keeping data forever. In Kafka it's possible with retention.ms=-1 and tiered storage, but it collides with the GDPR "right to be forgotten": deleting one user from an immutable log is hard. Crypto-shredding (encrypting with a separate key per user and deleting the key) is one solution.

In short, Kafka is great for distributing and replaying events, but before you call it the "single source of truth", you need a clear answer to where the business invariants are checked.