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.
| Term | Meaning |
|---|---|
| Event | An immutable record of something that happened, with its data and metadata (time, id, version) |
| Stream | The ordered events of one entity, such as account-42 |
| Event store | Durable storage for streams: append and read in order, never update or delete |
| Aggregate | The entity whose state is rebuilt from its stream and which decides on new events |
| Projection | Code 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.
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.
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.
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.
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
(
MoneyDepositedv1 without a currency becomes v2 withGBP). Stored bytes are untouched; upcasters chain v1 to v2 to v3. - New event type: when the meaning changes, introduce
MoneyDepositedV2and 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.
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) {3Thread.sleep(50);4}
| Choice | You gain | You pay |
|---|---|---|
| Synchronous projection (same transaction as the append) vs asynchronous | Reads always see the write; no lag to handle | Slower 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 stream | Fast loading of long streams | Extra storage, invalidation when the state shape changes, and more code to get wrong |
| One stream per aggregate vs bigger streams | Few conflicts and short replays; each command touches one small stream | Rules across aggregates need sagas; one big stream gets slow to load and conflicts more |
| Rebuilding a read model in place vs blue/green | Simple, no extra storage | Users see a half-built view; blue/green needs double storage and a switch-over step |
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 (2position BIGSERIAL PRIMARY KEY, -- global order, for projections3stream_id TEXT NOT NULL,4version BIGINT NOT NULL, -- per-stream order, for concurrency5type TEXT NOT NULL,6payload JSONB NOT NULL,7UNIQUE (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 {}45class Account {6private long balance;7private long version;89static Account replay(List<AccountEvent> history) {10var account = new Account();11history.forEach(account::apply);12return account;13}1415private void apply(AccountEvent event) { // state changes only, no rules16switch (event) {17case Deposited d -> balance += d.pence();18case Withdrawn w -> balance -= w.pence();19}20version++;21}2223Withdrawn withdraw(long pence) { // rules here, before the event exists24if (pence > balance) throw new InsufficientFundsException();25return new Withdrawn(pence);26}2728long version() { return version; }29}
The command handler loads, decides and appends with the expected version:
1@Service2class AccountCommandHandler {3private final EventStore store;45AccountCommandHandler(EventStore store) {6this.store = store;7}89@Transactional10public void handle(WithdrawMoney cmd) {11var account = Account.replay(store.load(cmd.accountId()));12var event = account.withdraw(cmd.pence());13// INSERT ... version = expected + 1; fails if another writer got there first14store.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 {3private final EventStore store;4private final Checkpoints checkpoints;5private final JdbcClient jdbc;67BalanceProjection(EventStore store, Checkpoints checkpoints, JdbcClient jdbc) {8this.store = store;9this.checkpoints = checkpoints;10this.jdbc = jdbc;11}1213@Scheduled(fixedDelay = 500)14@Transactional15public void catchUp() {16long last = checkpoints.get("balances");17for (StoredEvent e : store.readAfter(last, 500)) {18long delta = switch (e.event()) {19case Deposited d -> d.pence();20case Withdrawn w -> -w.pence();21};22jdbc.sql("""23INSERT INTO account_balance (account_id, balance) VALUES (:id, :delta)24ON CONFLICT (account_id) DO UPDATE SET balance = account_balance.balance + :delta25""")26.param("id", e.streamId()).param("delta", delta).update();27last = e.position();28}29checkpoints.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.
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.