00:00

Event Sourcing and CQRS with Kafka

Last updated:

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:

Events of account acc-42
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

NeedKafka’s strength or gap
Durable, ordered, replayable log of eventsStrength. A topic keyed by entity ID keeps each entity’s events in order, retained as long as you configure
Distributing events to many consumersStrength. Any number of projections, services and analytics jobs can read independently
Building and rebuilding read modelsStrength. 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 quicklyGap. There is no index by key; you would scan a whole partition
Keep history foreverPossible 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

Event sourcing and CQRS with KafkaA client sends a command such as withdraw 50 to the account command service. The service loads the account's current state, checks business rules, and appends a MoneyWithdrawn event to the account_events table, whose unique account ID and version constraint prevents concurrent conflicting writes. CDC or an outbox relay publishes the event to the Kafka topic account-events, keyed by account ID. Projections consume the topic: one updates a balance view, another builds monthly statements, a third feeds a search index. A query API reads from the read models. Command sideQuery side Client"withdraw 50" Command servicecheck rules account_eventsunique (account_id,version) CDC / outboxpublish account-eventskey = accountId Query API balance view monthly statements search index append
The command side appends versioned events; Kafka distributes them; projections build read models for queries.

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.

account_events.sql
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)
);
AccountCommandService.java
@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:

BalanceProjection.java
@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:

BalanceTopology.java (excerpt)
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:

  1. Deploy the new projection with a new consumer group (for example balance-view-v2) and a new target table, starting from the earliest offset.
  2. Let it catch up while the old version keeps serving queries.
  3. 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 withdraw does) 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, not UpdateBalance.
  • 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

AdvantagesLimitations
Complete audit trail and the ability to reconstruct any past stateMore moving parts: event store, publishing, projections
New read models without touching the write sideEventual consistency between commands and queries
Read models optimised independently for each queryEvent schema changes must stay compatible for years
Natural integration with other services through KafkaUnnecessary 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.

15. References