Event Sourcing and CQRS with Kafka
Event sourcing stores the history of what happened to an entity as a sequence of events, instead of only its current state. CQRS (Command Query Responsibility Segregation) separates the model that handles changes from the models that answer queries. Together with Kafka they make it possible to build systems where every change is recorded, and new read models can be added at any time by replaying events.
This tutorial explains both patterns, what Kafka is good at in such an architecture and where it is not a complete event store, how to keep writes consistent, how to build and rebuild read models with Spring Boot and Kafka Streams, and how to deal with eventual consistency.
1. What Is Event Sourcing?
A traditional system stores the current state: the accounts table says the balance is 70. An event-sourced system stores the facts that led there:
v1 AccountOpened owner=Asha
v2 MoneyDeposited amount=100
v3 MoneyWithdrawn amount=50
v4 MoneyDeposited amount=20
-> current balance = 100 - 50 + 20 = 70
Events are immutable and only ever appended. The current state is derived by replaying an entity’s events, usually with a snapshot to avoid replaying thousands of them. Nothing is lost: you can answer “what was the balance last Tuesday?”, audit every change, and find out why a value is what it is.
2. What Is CQRS?
CQRS splits an application into two sides:
- The command side receives requests to change something (“withdraw 50”), checks business rules against the current state, and records the result.
- The query side serves reads from one or more read models (projections) shaped for specific queries: a balance view, a monthly statement, a search index.
The two patterns are independent: CQRS can be used with an ordinary database, and event sourcing can be used with a single model. They are often combined, because events are the natural way to keep read models up to date.
3. Where Kafka Fits, and Where It Does Not
| Need | Kafka’s strength or gap |
|---|---|
| Durable, ordered, replayable log of events | Strength. A topic keyed by entity ID keeps each entity’s events in order, retained as long as you configure |
| Distributing events to many consumers | Strength. Any number of projections, services and analytics jobs can read independently |
| Building and rebuilding read models | Strength. Consumers and Kafka Streams can replay from the beginning |
| “Append only if the entity is still at version N” (optimistic concurrency) | Gap. A producer cannot make a write conditional on the current last event of a key |
| Load all events of one entity quickly | Gap. There is no index by key; you would scan a whole partition |
| Keep history forever | Possible with retention.ms=-1 or tiered storage, but not with log compaction, which deletes old events |
So there are two sound ways to use Kafka for event sourcing. Either keep the events in a database that enforces per-entity versions and publish them to Kafka through an outbox or CDC, or make Kafka the source of truth and guarantee a single writer per entity, for example a Kafka Streams application that owns each entity’s partition and validates commands against its state store. This tutorial uses the first approach, which is easier to get right.
4. A Practical Architecture
5. The Write Side: Appending Events Safely
The command side must never record two conflicting changes for the same entity, such as two withdrawals that each assume a balance of 100. A unique constraint on (account_id, version) gives optimistic concurrency: if two requests race, only one insert of version 5 succeeds.
CREATE TABLE account_events (
account_id VARCHAR(40) NOT NULL,
version BIGINT NOT NULL,
event_type VARCHAR(60) NOT NULL,
payload JSONB NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, version)
);
@Service
public class AccountCommandService {
private final AccountEventStore store; // reads and appends rows of account_events
public AccountCommandService(AccountEventStore store) { this.store = store; }
@Transactional
public long withdraw(String accountId, BigDecimal amount) {
List<AccountEvent> history = store.load(accountId); // ordered by version
Account account = Account.replay(history); // rebuild current state
if (account.balance().compareTo(amount) < 0) {
throw new InsufficientFundsException(accountId); // business rule on current state
}
long next = account.version() + 1;
store.append(accountId, next, new MoneyWithdrawn(amount)); // fails on (account_id, version) conflict
return next; // returned to the caller (see section 9)
}
}
If another request appended version next first, the insert fails with a duplicate-key error; the caller retries the command against the new state, where the balance check may now fail correctly. The new row is then published to the account-events topic by CDC or an outbox relay, keyed by accountId, so each account’s events stay ordered in one partition.
6. The Read Side: Building Projections
A projection consumes the events and maintains a read model. Because delivery is at least once, it must be idempotent; the event version makes that easy:
@Component
public class BalanceProjection {
private final JdbcClient jdbc;
public BalanceProjection(JdbcClient jdbc) { this.jdbc = jdbc; }
@KafkaListener(topics = "account-events", groupId = "balance-view-v1")
@Transactional
public void on(AccountEventMessage e) {
BigDecimal delta = switch (e.type()) {
case "MoneyDeposited" -> e.amount();
case "MoneyWithdrawn" -> e.amount().negate();
default -> BigDecimal.ZERO;
};
// apply each version once: older or repeated events change nothing
jdbc.sql("""
INSERT INTO balance_view (account_id, balance, version) VALUES (:id, :delta, :v)
ON CONFLICT (account_id) DO UPDATE
SET balance = balance_view.balance + :delta, version = :v
WHERE balance_view.version < :v
""")
.param("id", e.accountId()).param("delta", delta).param("v", e.version())
.update();
}
}
The WHERE balance_view.version < :v clause ignores events that were already applied, so a redelivered event cannot change the balance twice. It relies on the per-account order that keying by account ID provides. Different projections use different consumer groups and can live in different databases, each optimised for its queries.
7. Read Models with Kafka Streams
For read models that are simple aggregations, Kafka Streams can build them without an external database, as a KTable backed by a local state store and a compacted changelog topic:
KTable<String, BigDecimal> balances = builder
.stream("account-events", Consumed.with(Serdes.String(), eventSerde))
.groupByKey(Grouped.with(Serdes.String(), eventSerde))
.aggregate(() -> BigDecimal.ZERO,
(accountId, event, balance) -> balance.add(event.signedAmount()),
Materialized.<String, BigDecimal, KeyValueStore<Bytes, byte[]>>as("balances")
.withValueSerde(decimalSerde));
The balances store can be queried through interactive queries, and the KTable can be written to a compacted topic so other services get the latest balance per account. Use exactly_once_v2 here, because at-least-once processing of a sum can count an event twice after a failure. See KStream and KTable for the underlying concepts.
8. Rebuilding Read Models by Replaying Events
The biggest practical benefit of event sourcing is that read models are disposable. To fix a bug in a projection or add a new one:
- Deploy the new projection with a new consumer group (for example
balance-view-v2) and a new target table, starting from the earliest offset. - Let it catch up while the old version keeps serving queries.
- Switch the query side to the new table, then remove the old projection.
This only works if the event topic still contains every event. Configure it with retention.ms=-1 (or long retention with tiered storage) and cleanup.policy=delete; never compact an event-sourcing topic, because compaction keeps only the latest record per key and destroys the history. See message replay for resetting offsets of an existing group.
9. Living with Eventual Consistency
Read models lag slightly behind the write side, usually by milliseconds, sometimes longer. The classic symptom is a user who withdraws money and immediately sees the old balance. Common remedies:
- Return the new version from the command (as
withdrawdoes) and let the UI wait until the read model reports that version, or show the expected state optimistically. - Read your own writes from the write side for the few screens that must be exact, and use read models everywhere else.
- Monitor projection lag like any consumer lag, so staleness is visible.
10. Designing Events
- Name events in the past tense after business facts:
MoneyWithdrawn, notUpdateBalance. - Include what consumers need (amount, currency, IDs, time) and an event ID and version for idempotency.
- Plan for schema evolution: events are kept for years, so use Schema Registry with a transitive compatibility mode, or upcast old event versions when reading.
- Keep personal data out of the event log where possible (or store it encrypted with a deletable key), because immutable events conflict with deletion requests under privacy law.
11. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Complete audit trail and the ability to reconstruct any past state | More moving parts: event store, publishing, projections |
| New read models without touching the write side | Eventual consistency between commands and queries |
| Read models optimised independently for each query | Event schema changes must stay compatible for years |
| Natural integration with other services through Kafka | Unnecessary complexity for simple CRUD domains |
12. Common Mistakes
- Treating a Kafka topic as a database with per-entity reads. Loading one account by scanning a partition does not scale; keep an indexed store or a state store for the write side.
- Multiple writers per entity without a version check. Two instances can both append events based on the same old state.
- Compacting the event topic. Compaction keeps only the last event per key, so the history needed for replays is gone.
- Non-idempotent projections. Redelivered events double-count amounts.
- Using event sourcing everywhere. It pays off for domains with rich history and audit needs, not for simple reference data.
13. Summary
Event sourcing records every change as an immutable event and derives state from them; CQRS separates the command side from read models built for queries. Kafka is an excellent backbone for distributing events and building and rebuilding read models, but it does not provide per-entity optimistic concurrency or indexed reads, so keep a versioned event store (published through an outbox or CDC) or a strict single writer per entity. Key events by entity ID, keep the event topic uncompacted with long retention, make projections idempotent, and design events for long-term schema evolution.
14. Related Reading
- Saga pattern with Kafka: coordinating multi-service workflows with events
- Transactional outbox: publishing events reliably from a database
- Retention vs compaction: why event logs must not be compacted
- Idempotent consumer: safe projections under redelivery
15. References
Event Sourcing and CQRS Interview Questions and Answers
Common interview questions on Event Sourcing and CQRS, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is the difference between event sourcing and CQRS?
Answer: Event sourcing is about storage: an entity’s state is recorded as an append-only sequence of immutable events, and current state is derived by replaying them. CQRS is about structure: commands that change state are handled by a write model, and queries are served by separate read models. They are independent patterns that are often combined, because events are a natural way to keep read models up to date.
Q. Why must events of the same entity be keyed by the entity ID in Kafka?
Answer: Kafka orders records only within a partition. Keying by entity ID sends all events of one entity to the same partition, so projections receive them in the order they happened. With random keys, a withdrawal could be applied before the deposit it depends on, and version-based idempotency checks in projections would not work.
Intermediate questions
Q. Can Kafka be used as the event store in an event-sourced system?
Answer: Partly. Kafka is a durable, ordered, replayable log, ideal for distributing events and rebuilding read models. But it cannot append conditionally on an entity’s current version, and it has no index to load one entity’s events quickly. Use it as the store only with a single writer per entity, such as a Kafka Streams application that owns each partition and validates commands against a state store; otherwise keep events in a database with a version constraint and publish them to Kafka.
Q. How do you rebuild or add a read model in an event-sourced system on Kafka?
Answer: Start the new projection with a new consumer group from the earliest offset, writing into a new table or index, and let it catch up while the old read model keeps serving queries. Then switch reads over and retire the old one. This requires the event topic to keep all events: unlimited (or very long, tiered) retention and the delete cleanup policy.
Q. Why should an event-sourcing topic not use log compaction?
Answer: Compaction keeps only the latest record for each key and eventually removes older ones. For an event-sourced entity that would delete its history, so replays would rebuild wrong state. Compaction suits topics that hold the latest state per key, such as a snapshot or a KTable changelog, not the event log itself.
Tricky and scenario questions
Q. Two instances of an account service handle withdrawals for the same account at the same moment, and both succeed although the balance covers only one. How do you prevent this?
Answer: Both instances read the same old state and appended an event. Make appends conditional on the version: store events with a unique (account_id, version) constraint so only one write of version N succeeds, and retry the losing command against the new state, where the balance check fails correctly. With Kafka as the source of truth, route all commands for an account through one partition and process them with a single writer per partition instead.
Q. Users complain that after transferring money, the dashboard still shows the old balance for a moment. Is this a bug, and how would you handle it?
Answer: It is expected eventual consistency: the read model is updated asynchronously from the event stream. Handle it in the experience rather than by giving up CQRS: return the new version from the command and have the UI wait for, or poll until, the read model reaches it, or show the expected balance optimistically. For the few views that must be exact immediately, read from the write side. Monitor projection lag so delays stay small.