Topic 13.12
Event Sourcing
In one line
Store the history of changes as an append-only event log — the state is derived, never stored as a mutable row.
Think of it like this
Keeping your bank statement (every single transaction ever made) instead of just a single 'current balance' number. You can always recompute the current balance by replaying the statement, and you never lose the history of how you got there.
Key ideas
- 01
Instead of saving current state, save the SEQUENCE of events that produced it (OrderPlaced, PaymentReceived, Shipped).
- 02
State reconstruction: replay events to rebuild any aggregate — also gives you point-in-time snapshots for free (audit!).
- 03
Projections: read models built FROM events — a natural partner for CQRS (13.13).
- 04
The audit/source-of-truth story is why finance, compliance, and 'explainable' systems love it.
- 05
Costs: event store is append-only + immutable; snapshotting needed for replay speed; schema evolution of events is a discipline.
- 06
Idempotent consumers of events → the projection is automatically rebuildable (replay from zero).
- 07
Interview: 'the ledger of events is my source of truth; the read side is derived — I can rebuild it any time'.
Java / Spring map
- →
Store events in Postgres (event table) or Kafka (log); project via a subscription; snapshot aggregates.
Code & diagrams
The shape interviewers want in a sentence map.
WRITE SIDE (append-only):
events: OrderPlaced(orderId, items, at)
PaymentSucceeded(orderId, cents, at)
OrderShipped(orderId, at)
→ never UPDATE a row; always append an event.
READ SIDE (projection):
order_status = replay(events) → 'SHIPPED'
snapshots: store state at event #N to avoid replaying 3M events.
SUPERPOWER:
- audit history is native
- 'the production bug corrupted state' → rebuild from events
- read models can be re-created triviallyExplain without notes
Your customer calls about a dispute: where does event sourcing make the answer 10x cheaper? (audit trail)
Practice
Design the bank-account aggregate as events + snapshot + projections, and label each.
Trade-offs
- ↔
Event stores complicate deletion/privacy (GDPR) and schema changes; snapshots and tombstones handle it at cost.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Completion checklist
I can justify event sourcing by audit/replay needs and name its two main costs.