Here’s a row from a normal accounts table:
id | owner | balance
acc1 | Asha | 150.00
How did Asha’s balance get to ₹150? A ₹100 deposit and a ₹50 one? ₹200 minus ₹50? A single ₹150 transfer? There’s no way to know. Every update overwrote the one before. The table keeps only the ending of the story.
Your bank doesn’t work like that. Your passbook lists every deposit and withdrawal, and the balance is simply what they add up to. If something looks wrong, you can go through the lines and find out why.
Event sourcing stores data the passbook way. This article finishes the Asynchronous systems thread. In the last article, events were messages that services used to tell each other what happened. Here, events become the data itself.
What event sourcing is
Instead of storing the current state, you store every change as an event, in order, and never edit or delete them. The current state is worked out by replaying the events from the start.
- The events are the source of truth. The balance isn’t stored anywhere permanent; it’s calculated from the events.
- The event log is append-only. Like a Git history, you only ever add to it.
- State = replay(events). Start empty, apply each event in order, and you get the current state.
It’s the same idea behind Git (commits, not just the latest files), database write-ahead logs, and accounting ledgers, which have worked this way for centuries.
How it works in code
The event store can be a plain database table. The key detail is the unique constraint on the account and its version number:
CREATE TABLE events (
aggregate_id VARCHAR(64) NOT NULL, -- e.g. the account id
version INT NOT NULL, -- 1, 2, 3… per account
event_type VARCHAR(100) NOT NULL, -- MoneyDeposited, MoneyWithdrawn…
payload JSONB NOT NULL, -- the event's data
occurred_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (aggregate_id, version) -- no two events can claim the same slot
);
To load an account, read its events in order and apply each one. To change it, check the business rules against the current state, then record a new event:
// Java · an account rebuilt from its events
public class Account {
private BigDecimal balance = BigDecimal.ZERO;
private int version = 0;
// 1. Rebuild: apply past events. No rules here, just facts.
void apply(AccountEvent event) {
switch (event) {
case MoneyDeposited e -> balance = balance.add(e.amount());
case MoneyWithdrawn e -> balance = balance.subtract(e.amount());
default -> { }
}
version++;
}
// 2. Decide: check the rules, then produce a new event.
MoneyWithdrawn withdraw(BigDecimal amount) {
if (amount.compareTo(balance) > 0) throw new InsufficientFundsException();
return new MoneyWithdrawn(amount); // saved as version + 1
}
}
Notice the split. apply only replays facts; it never says no. Rules like “no overdraft” live in the command (withdraw), which runs once, before the event is saved. That’s what keeps replaying the past safe.
Snapshots: don’t replay a million events
An account with 10 events rebuilds instantly. One with a million doesn’t. The fix is a snapshot: every so often (say, every 500 events), save the calculated state. To load, start from the latest snapshot and replay only the events after it.
CQRS: a separate model for reading
Event sourcing is great for writing changes, but awkward for questions like “show me all accounts with a balance over ₹1 lakh”. You can’t run that across raw events.
So event sourcing almost always comes with CQRS (Command Query Responsibility Segregation): use one model for writes and another for reads.
- Write side: commands check rules and append events. That’s all it does.
- Read side: projections listen to new events and keep read models up to date: an ordinary table with each account’s current balance, a monthly statement view, a search index. Queries hit these directly, so reads are as fast as any normal database.
Two things to know about projections:
- They lag a little. A projection updates just after the event is saved, so for a moment the read side can be behind. If a user must see their own change straight away, read it from the write side, or wait for the projection to catch up.
- They’re disposable. Need a new report? Write a new projection and replay all past events into it. You get a full history for a feature you built today. If a projection has a bug, fix it, delete the table and replay.
Projections should read from the event store itself, not from a second “publish” call made after saving. Otherwise you’re back to the dual-write problem we covered in the last article.
What you get, and what it costs
What you get:
- A complete audit trail, for free. Every change, when it happened, and why. Banks, healthcare and legal systems often need this anyway.
- Time travel. “What was this account’s balance on 1 January?” Replay events up to that date.
- New views of old data. Add a projection today and fill it from years of history.
- Easier debugging. Replay one account’s events step by step and watch exactly where it went wrong.
What it costs:
- More complexity. Event stores, projections, snapshots and versioning are a lot more to build and learn than a single table.
- Eventual consistency on the read side.
- Changing events is hard, because old events live forever (more below).
- Deleting data is hard, because the log is append-only (see puzzle 3).
| Normal tables (CRUD) | Event sourcing | |
|---|---|---|
| Stores | the current state | every change |
| History | lost on every update | complete |
| Audit trail | build it yourself | built in |
| Queries | easy | need projections (CQRS) |
| Changing the shape | a migration | old events must still be readable |
| Complexity | low | high |
Use it when history really matters (money, bookings, orders, compliance), the domain is naturally a series of steps, or you need “what was true at time T?”. Skip it for simple data like user settings, profiles or a product catalog. Most systems use event sourcing for one or two core areas, and ordinary tables everywhere else. In Java, frameworks like Axon help, and EventStoreDB (now KurrentDB) is a database built for it, though PostgreSQL works fine to start.
Changing events over time
An event written five years ago must still load today. So:
- Add fields; don’t rename or remove them. Give new fields a sensible default for old events.
- For bigger changes, use upcasting: when an old
MoneyDeposited v1is read, convert it on the fly intov2(for example, addingcurrency = "INR"), so the rest of the code only deals with the newest version. - Don’t rewrite old events in place, except in rare emergencies. They’re your record of what happened.
What breaks, and how to fix it
| What breaks | What you see | The fix |
|---|---|---|
| Two changes at the same moment | Two withdrawals both pass the balance check, and the account goes negative | Optimistic concurrency: save with the expected version; the unique (aggregate_id, version) key rejects the loser, which reloads and retries |
| Loading gets slow | Busy accounts take seconds to rebuild | Snapshots every few hundred events |
| The read side is behind | A user saves a change and doesn’t see it on refresh | Show the result from the write side, or wait for the projection to reach that version; alert on projection lag |
| An event shape changes | Old events fail to load after a deploy | Additive changes only, plus upcasters for old versions |
| A projection has a bug | A report shows wrong totals | Fix the projection, drop its table, replay all events into it |
Puzzle 1: two withdrawals at once
Without protection, both events are saved, and the balance becomes −₹60. Each request checked the rule against a balance that was about to change.
The fix is optimistic concurrency. Each request saves its event as version 6, the version it expects to come next. The first insert succeeds. The second hits the PRIMARY KEY (aggregate_id, version) and fails. That request reloads the account (now ₹20, version 6), runs the check again, and correctly refuses the withdrawal.
Make sure the conflict fails loudly. An INSERT … ON CONFLICT DO NOTHING would silently drop the second event and tell the user their withdrawal worked.
Puzzle 2: the interest bug
Not for this bug. Replaying runs apply(), and apply() just adds up the amounts stored in the events. The wrong amounts are now recorded facts: “we paid Asha ₹50 interest”. Replaying with fixed code produces exactly the same wrong balance.
Replay fixes views (a bug in a projection or report). It doesn’t fix facts. For wrong facts, do what an accountant does: add correcting events. For each account, calculate the difference and append an InterestCorrected event for −₹45. The history now honestly shows the mistake and the fix, which is exactly what an auditor wants to see.
Puzzle 3: “delete my data”
There are three common approaches, best first:
- Keep personal data out of events. Store the name and email in a normal table, and put only the customer ID in events. Deleting the row deletes the personal data, and the events stay meaningful.
- Crypto-shredding. Encrypt each customer’s personal fields with their own key. To “delete” them, destroy the key. The events remain, but that data can never be read again.
- Rewrite as a last resort. Replace personal fields in old events with
[deleted]. It works, but it breaks the rule that events never change, so do it with a careful, audited tool.
Plan for this on day one. Adding it to a store that already holds years of personal data is painful.
Key takeaways
- Event sourcing stores every change as an event, and works out the current state by replaying them. Nothing is overwritten.
- Rules belong in commands;
apply()only replays facts. That’s what makes replay safe. - Snapshots keep loading fast. They’re shortcuts, not the truth.
- CQRS projections turn events into fast read tables. They lag a little, and can always be rebuilt.
- Use optimistic concurrency (a unique version per aggregate), fix wrong facts with correcting events, and plan for personal data deletion up front.
- Use it where history matters, like money, orders and bookings, and keep ordinary tables everywhere else.
That completes the Asynchronous systems thread: messaging, event-driven architecture, and event sourcing. Next comes Part 10, reliability and fault tolerance, starting with designing for failure.
Comments