Video in progress
What is event sourcing, and how is it different from "write to a table, then send an event"?
In event sourcing the primary data isn't the current state in a table but the sequence of changes (events). The current state is obtained by replaying the events. In plain CRUD + events, the source of truth is the table, and the event is only a notification.
📖 Answer
In the usual approach, balance = 700 sits in the account table. How it got to 700 is in the logs or, if you have one, in a separate audit table.
In event sourcing, what's stored is this:
account-42:
1 AccountOpened {owner: "Ali"}
2 MoneyDeposited {amount: 1000}
3 MoneyWithdrawn {amount: 300}
The balance is the result of applying the events from the beginning:
sealed interface AccountEvent permits AccountOpened, MoneyDeposited, MoneyWithdrawn {}
Account rebuild(List<AccountEvent> events) {
Account acc = new Account();
for (AccountEvent e : events) {
switch (e) {
case AccountOpened o -> acc.open(o.owner());
case MoneyDeposited d -> acc.add(d.amount());
case MoneyWithdrawn w -> acc.subtract(w.amount());
}
}
return acc;
}
In Java 21, with a sealed interface and pattern matching the compiler checks that such a switch is exhaustive: if a new event type is added, the place you forgot won't compile.
What you get: the full history comes for free, you can answer "what was the balance on the 15th of last month", and you can rebuild a new read model from old events. Storing the event and publishing it is a single write, so the dual write problem goes away.
The cost:
- queries are hard: for "accounts with a balance over 1000" you need a separate projection (a read model);
- the event schema lives forever: you have to be able to read the format from 3 years ago;
- rebuilding on a long history is slow, so you need snapshots;
- the way of thinking is completely different for the team.
In practice, applying event sourcing not to the whole system but to one or two domains where history and audit really matter (accounts, ledger, order state) works well. Event sourcing and Kafka aren't the same thing: the event store is usually a DB (PostgreSQL, EventStoreDB), and Kafka is for distribution.
Sign up to mark studied questions and save your progress.