TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About · Labs · Cheat sheets · Learning paths

All concepts · event sourcing · cqrs · architecture · distributed systems

Event sourcing and CQRS

Event sourcing stores every state change as an immutable event and rebuilds state by replaying them; CQRS splits the model that handles commands from the read models that answer queries, which are updated from those events.

16 min7 animations

📚 Builds on📬 Apache Kafka🧥 Message queues vs event streams

🖨️ Cheat sheet

A passbook, not a slate

Picture two banks. The first keeps each customer's balance on a chalk slate. When Ana pays in £100, the clerk rubs out the old number and chalks the new one. It's quick, but the slate only ever knows today's number. Ask it "why do I have £120?" and it has no idea.

The second bank gives Ana a passbook. Every time she pays in or takes out money, the clerk writes a new line at the bottom: "paid in £100", "took out £30". Nobody ever rubs a line out. If the clerk makes a mistake, they don't scribble over it; they write a new line that puts it right.

Each line is called an event: something that happened. The balance isn't written down anywhere. You work it out by adding up the lines, and you can always see how you got there.

Storing events instead of state

In a classic CRUD design a row holds the current state, and every update overwrites it. The history is lost unless you build an audit table on the side.

Event sourcing turns this around: the source of truth is an append-only sequence of events, facts about what happened, named in the past tense (MoneyDeposited, MoneyWithdrawn). Current state is a function of those events, computed by folding over them.

TermMeaning
EventAn immutable record of something that happened, with its data and metadata (time, id, version)
StreamThe ordered events of one entity, such as account-42
Event storeDurable storage for streams: append and read in order, never update or delete
AggregateThe entity whose state is rebuilt from its stream and which decides on new events
ProjectionCode that reads events and builds a view for queries

Mistakes aren't fixed by editing an event. You append a compensating event (DepositReversed), so the history still shows both what happened and how it was corrected. Accountants have worked this way for centuries.

Events instead of current state5 steps
Ana's passbook01234🙋‍♀️Ana🪧 Chalk slate🧮Adding up
Press play and watch it happen!

Adding up from the top

When Ana asks the clerk to take out some money, the clerk first needs to know her balance. So they open the passbook and add up every line from the top. This is called a replay.

After years, the passbook has thousands of lines, and adding them all up every time takes ages. So now and then the clerk writes the running total on a subtotal card tucked in the cover: "up to line 6, £125". Next time they start from the card and only add the lines after it. The card is just a shortcut. If it's lost, the clerk can always add up from the top again, because the lines are the real record.

Replay and snapshots

To handle a command, the application loads the aggregate: it reads the entity's stream in order and applies each event to an empty object. Event handlers on the aggregate only change state; they never check rules or call other systems, because they also run during every replay.

Long streams make loading slow, so many systems store snapshots: the aggregate's state as of version N. Loading then means "latest snapshot, plus events after N". A snapshot is a cache derived from events, not the truth. You can delete snapshots and rebuild them, and you must invalidate them when the aggregate's state shape changes.

Before adding snapshots, check whether you need them. A well-chosen aggregate (one account, one order) often has tens or hundreds of events, which load quickly. Very long streams usually mean the aggregate boundary is too wide.

Replay and snapshots5 steps
Ana's passbook012345678🧑‍💼Clerk🗂️ Subtotal card
Press play and watch it happen!

The clerk and the board in the window

The bank does two different jobs, and it gives them to different people.

The clerk at the counter takes Ana's slips: "please take out £40". The clerk checks the passbook, makes sure there's enough money, and only then writes the new line. If there isn't enough, the clerk says no and writes nothing.

Lots of people just want to look at balances, though, and the clerk is busy. So the bank has a balance board in the window, called a read model. A board keeper reads each new passbook line and updates the board. Anyone can glance at the board without bothering the clerk.

The board keeper is quick, but not instant. For a moment after the clerk writes a line, the board still shows the old number. It always catches up.

CQRS: separate write and read models

Command Query Responsibility Segregation (CQRS), named by Greg Young from Bertrand Meyer's command-query separation, uses different models for changing data and for reading it.

  • The write side receives commands (WithdrawMoney), which are requests that may be refused. A command handler loads the aggregate, which enforces the business rules (no overdraft) and, if they hold, emits new events. The aggregate is the consistency boundary: one command changes one stream, atomically.
  • The read side has one or more read models: tables, documents or search indexes shaped for the screens that use them. Projections subscribe to the events and update them.

Because projections run after the events are stored, read models are eventually consistent: a query right after a command may see the old value. Common answers are to return the new version from the command and let the UI wait or poll until the read model reaches it, to update the UI optimistically, or to read the aggregate itself for the rare screen that must be exact.

CQRS doesn't require event sourcing (you can project from ordinary tables), and event sourcing doesn't strictly require CQRS. But querying across thousands of event streams is impractical, so event-sourced systems almost always add read models. Projections often consume events from Kafka, and each must be able to cope with seeing an event twice.

Commands write, read models answer6 steps
Passbook01234🙋‍♀️Ana🧑‍💼Clerk🧑‍🎨Board keeper🪧 Balance board🧍Bo
Press play and watch it happen!

Two clerks, one passbook

Ana and her partner Ben share an account with £120 in it. At the same moment, Ana asks one clerk for £100 and Ben asks another clerk for £80. Both clerks add up the passbook, both see £120, and both think "that's fine".

If both wrote their line, the account would end up £60 short. So the bank has a rule: when you read the passbook, count the lines, and only write the next line if nobody has written it in the meantime. Both clerks saw three lines, so both want to write line 4. Ana's clerk gets there first. Ben's clerk finds line 4 already taken, so they add up again, see only £20 left, and tell Ben no.

Optimistic concurrency on the stream

Two commands for the same aggregate can be handled at the same time, each from its own replay. Without a guard, both pass validation against the same state and both append, breaking the invariant.

Event stores solve this with optimistic concurrency: an append carries the expected version of the stream, the version the handler loaded. The store accepts the append only if the stream is still at that version; otherwise it rejects it (KurrentDB, formerly EventStoreDB, raises a wrong-expected-version error). The losing handler reloads the aggregate and re-runs the command, which may now be refused.

In a relational table this is a unique constraint on (stream_id, version): the second insert of version 4 fails. No locks are held while the command is processed, so conflicts are cheap when they're rare, which they are when aggregates are small. This works inside one stream only. A rule that spans aggregates (two accounts in a transfer) needs a process manager or saga that reacts to events and sends further commands, with compensating events if a later step fails, not one transaction across streams.

Two writers, one stream5 steps
Shared passbook012345🧑‍💼Clerk for Ana👩‍💼Clerk for Ben
Press play and watch it happen!

Old lines, new forms

Years ago, the bank's lines just said "paid in 100", and everyone knew that meant pounds. Now the bank takes euros too, so every new line says which money it was: "paid in €20". The old lines can't be rewritten, because nobody rubs anything out.

So the clerk keeps a translation card: "an old line with no currency means pounds". Whenever the clerk reads an old line, they read it through the card, and it looks just like a new one. This is called upcasting. The passbook stays exactly as it was written.

The never-rub-out rule has a catch. If Ana closes her account and asks the bank to forget her name, the bank can't scratch it out of the passbook. Careful banks write names in a secret code from the start, and keep the code key in a separate drawer. To forget Ana, they burn her key, and her name becomes unreadable everywhere.

Versioning events and erasing data

Stored events outlive the code that wrote them, so every event type is effectively a public schema. Strategies, roughly from cheapest:

  • Additive, tolerant changes: add optional fields with defaults, and have readers ignore unknown fields.
  • Upcasting: tag events with a schema version and convert old versions to the current one as they're read (MoneyDeposited v1 without a currency becomes v2 with GBP). Stored bytes are untouched; upcasters chain v1 to v2 to v3.
  • New event type: when the meaning changes, introduce MoneyDepositedV2 and handle both.
  • Copy and transform: rewrite the store into a new one. A last resort, since it breaks "events are immutable".

Immutability collides with the right to erasure under GDPR. Common answers are to keep personal data out of events and reference it by id from a store you can delete from, or crypto-shredding: encrypt each person's personal fields with their own key and delete the key, including from key-store backups, to make that data unreadable in every event, backup and copy. Get legal advice on whether that counts as erasure in your case.

Upcasting old events4 steps
Ana's passbook0123🔤 Translation card🧑‍💼Clerk
Press play and watch it happen!

When the bank has a bad day

Most days the bank runs smoothly. Here is what can go wrong.

The board keeper falls behind. Ana pays in, the clerk writes the line, and Ana looks at the board. It still shows the old number, as if her money vanished. The bank has a few answers. The clerk can tell Ana which line she wrote, and Ana can ask the board for "line 4 or newer" and wait until it says yes. Or the bank can have the keeper update the board before the clerk says "done", which is slower but never wrong.

The keeper makes a mistake. For a week they copied the wrong number onto the board. The passbook is fine, so the keeper starts a second, fresh board from line one, and the bank swaps boards when the new one has caught up. One strange line can also stop the keeper dead, because they can't make sense of it. Everyone's board freezes until someone sorts that line out.

The bank also tells the head office about every new line, but the clerk does it in a separate step. If the clerk writes the line and then trips before phoning, the head office never hears. So the clerk first writes a "to phone" note in the same go as the line, and a messenger phones from that pile. The messenger may sometimes phone twice, so head office ignores a line it has already heard.

What can go wrong

Optimistic concurrency conflicts are covered in Optimistic concurrency on the stream, event schema changes in Versioning events and erasing data, and skipped events in Gaps in the global position (in the Spring deep layer below). The failures below are the ones left over, mostly on the read side.

  • A projection falls behind. It is slower than the write rate, or it is restarting. Queries return stale data, and a user doesn't see their own write. You'd observe the gap between the stream's head position and the projection's checkpoint (lag) growing. Fixes: scale or batch the projection, and alert on lag; for read-your-writes, use the minimum-version wait below (the other options are in CQRS above).
  • A projection bug needs a full rebuild. The code wrote wrong numbers for days. Fixing the code doesn't fix the data already in the read model. You reset the checkpoint and replay from event zero, and replay time grows with history (hours on a large store). Build the corrected read model alongside the old one under a new table name, let it catch up, switch reads over (blue/green), then drop the old one.
  • A poison event stops a projection. One event throws every time (a null field, an unknown type, an old shape nobody upcasts). The projection retries forever, its checkpoint stops and lag climbs while the process looks alive in the logs. Fix the handler and redeploy, or after a bounded number of retries move the event to a dead-letter store and keep going, accepting that the read model now lacks that event until it is fixed and replayed.
  • An old consumer can't read a new event. A new field or renamed type arrives and an older projection or another service fails to deserialise it. The symptom is the same stuck checkpoint as above. Prevent it with tolerant readers, additive changes and upcasting (see versioning above), and deploy consumers before producers.
  • The store and the message bus disagree (dual write). The handler appends to the event store and then publishes to Kafka as a separate step. A crash between the two leaves an event no other service ever hears about. Reversing the order publishes events that were never stored. Neither can be made atomic with the other. Fix it with a transactional outbox: write the event and an outbox row in one database transaction, and a relay publishes from the outbox (or use change data capture on the event table). The relay may publish twice, so consumers must be idempotent. For a failure that spans aggregates or services, see sagas.

Waiting for a minimum version can be as simple as a bounded poll on the query side:

1long deadline = System.nanoTime() + Duration.ofSeconds(2).toNanos();2while (balances.versionOf(id) < minVersion && System.nanoTime() < deadline) {3    Thread.sleep(50);4}
ChoiceYou gainYou pay
Synchronous projection (same transaction as the append) vs asynchronousReads always see the write; no lag to handleSlower commands, the write path can fail on a read-model bug, and read models must live in the same database
Snapshots vs replaying the full streamFast loading of long streamsExtra storage, invalidation when the state shape changes, and more code to get wrong
One stream per aggregate vs bigger streamsFew conflicts and short replays; each command touches one small streamRules across aggregates need sagas; one big stream gets slow to load and conflicts more
Rebuilding a read model in place vs blue/greenSimple, no extra storageUsers see a half-built view; blue/green needs double storage and a switch-over step
A crash between the write and the phone call4 steps
Passbook01234To-phone pile01234🧑‍💼Clerk🛵Messenger🏢Head office
Press play and watch it happen!

Running the bank in Java

In a Java program, the same people show up as pieces of code. A counter takes requests from the app. The clerk is a small piece of code that adds up the passbook, checks the rules and writes one new line, but only if the next line is still empty. The passbook is a table where rows are only ever added.

The board keeper is another piece of code that wakes up every half second, reads any new lines and updates a balance table. The app reads balances from that table, never from the passbook.

Event sourcing in Spring

A plain Spring sketch with JDBC and Java 21. The event store is one table; the unique constraint is the optimistic concurrency check:

1CREATE TABLE events (2  position  BIGSERIAL PRIMARY KEY,      -- global order, for projections3  stream_id TEXT   NOT NULL,4  version   BIGINT NOT NULL,            -- per-stream order, for concurrency5  type      TEXT   NOT NULL,6  payload   JSONB  NOT NULL,7  UNIQUE (stream_id, version)8);

The aggregate rebuilds itself from events and decides on new ones:

1sealed interface AccountEvent permits Deposited, Withdrawn {}2record Deposited(long pence) implements AccountEvent {}3record Withdrawn(long pence) implements AccountEvent {}4 5class Account {6    private long balance;7    private long version;8 9    static Account replay(List<AccountEvent> history) {10        var account = new Account();11        history.forEach(account::apply);12        return account;13    }14 15    private void apply(AccountEvent event) {      // state changes only, no rules16        switch (event) {17            case Deposited d -> balance += d.pence();18            case Withdrawn w -> balance -= w.pence();19        }20        version++;21    }22 23    Withdrawn withdraw(long pence) {               // rules here, before the event exists24        if (pence > balance) throw new InsufficientFundsException();25        return new Withdrawn(pence);26    }27 28    long version() { return version; }29}

The command handler loads, decides and appends with the expected version:

1@Service2class AccountCommandHandler {3    private final EventStore store;4 5    AccountCommandHandler(EventStore store) {6        this.store = store;7    }8 9    @Transactional10    public void handle(WithdrawMoney cmd) {11        var account = Account.replay(store.load(cmd.accountId()));12        var event = account.withdraw(cmd.pence());13        // INSERT ... version = expected + 1; fails if another writer got there first14        store.append(cmd.accountId(), account.version(), event);15    }16}

A projection tracks its position and updates its table in the same transaction, so a crash can't apply an event twice or skip one (it can still skip events for another reason; see Gaps in the global position below):

1@Component2class BalanceProjection {3    private final EventStore store;4    private final Checkpoints checkpoints;5    private final JdbcClient jdbc;6 7    BalanceProjection(EventStore store, Checkpoints checkpoints, JdbcClient jdbc) {8        this.store = store;9        this.checkpoints = checkpoints;10        this.jdbc = jdbc;11    }12 13    @Scheduled(fixedDelay = 500)14    @Transactional15    public void catchUp() {16        long last = checkpoints.get("balances");17        for (StoredEvent e : store.readAfter(last, 500)) {18            long delta = switch (e.event()) {19                case Deposited d -> d.pence();20                case Withdrawn w -> -w.pence();21            };22            jdbc.sql("""23                    INSERT INTO account_balance (account_id, balance) VALUES (:id, :delta)24                    ON CONFLICT (account_id) DO UPDATE SET balance = account_balance.balance + :delta25                    """)26                .param("id", e.streamId()).param("delta", delta).update();27            last = e.position();28        }29        checkpoints.save("balances", last);30    }31}

With JdbcTemplate or JdbcClient, Spring translates the unique-constraint violation into DuplicateKeyException (a DataIntegrityViolationException). Catch it outside the transaction and run the whole load-decide-append again in a new one (a small loop, or a retry library), a few times at most. @Scheduled needs @EnableScheduling, and running one projection instance at a time (or taking a lock on its checkpoint row) keeps two pollers from applying the same events. To feed other services, publish events to Kafka from the store, for example with a transactional outbox or change data capture, rather than writing to the database and Kafka separately.

Axon Framework packages all of this for Java: command and event handlers, an event store (Axon Server, or a JPA database), streaming event processors for projections, snapshots and event versioning. Axon Framework 5 reworked the API: aggregates became event-sourced entities (@EventSourcedEntity), events are published through an injected EventAppender instead of the static AggregateLifecycle.apply, and upcasters gave way to event transformations. Axon 4 material won't carry over unchanged, so follow the reference guide for the version you use.

🔧 Going deeper

What you gain: a complete audit trail for free; temporal queries ("what was the balance on 1 March?") by replaying up to a point; debugging by replaying production events; and new read models later, built by running a new projection from event zero over years of history you already have.

What it costs: more moving parts, eventual consistency that the UI must handle, schema evolution forever, projection rebuilds that can take hours on big stores, and a team that must think in events.

When not to use it: plain CRUD with no interest in history (a settings page, a product catalogue), small apps, or teams new to the pattern on a deadline. Apply it to the parts of a system where history and auditability matter, not to everything. An audit table or change data capture may give you enough history at a fraction of the cost.

Gaps in the global position: with a sequence or BIGSERIAL, a transaction that took position 41 can commit after one that took 42. A projection that has already read 42 and moved its checkpoint will never see 41. Real event stores and libraries handle this, for example by recording each event's transaction id (pg_current_xact_id()) and only reading events from transactions older than the oldest one still running (pg_snapshot_xmin(pg_current_snapshot())), or by tolerating gaps for a short while and revisiting them. If you roll your own, this is the bug you'll hit.

Rebuilding a read model: drop its table, reset its checkpoint to zero and let it catch up. Build the new version alongside the old one and switch reads over when it's current, so users never see a half-built view.

Event sourcing in a Spring app5 steps
Passbook01234🪟Counter🧑‍💼Clerk🧑‍🎨Board keeper🪧 Balance board
Press play and watch it happen!

🧩 Quick quiz

Quick quiz! 5 questions about Event sourcing and CQRS, told the same way as the story.
  1. The clerk wrote "paid in £100" when Ana only paid in £10. How does the passbook bank put it right?
  2. The subtotal card falls behind the radiator and is lost. What happens?
  3. Ana takes out £40, the clerk says done, and a second later the board in the window still shows the old amount. Is something broken?
  4. Two clerks both add up the shared passbook, see three lines and £120, and both try to write line 4. What stops the account going short?
  5. The bank now writes which money each line is in. What does it do with the old lines that don't say?
Answer every question to check.Passing marks Event sourcing and CQRS as done.
Got the hang of Event sourcing and CQRS? Mark it as done, and your paths show how far you’ve got.

Saved in this browser.

📨 Event-driven systemsStep 3 of 5

← Previous on the path🧥 Message queues vs event streamsNext on the path →🧳 Sagas and distributed transactions