Command Palette

Search for a command to run...

PHASE 13Advanced ~7 min· topic 11 of 13

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.

0/13 · 0%

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

  1. 01

    Instead of saving current state, save the SEQUENCE of events that produced it (OrderPlaced, PaymentReceived, Shipped).

  2. 02

    State reconstruction: replay events to rebuild any aggregate — also gives you point-in-time snapshots for free (audit!).

  3. 03

    Projections: read models built FROM events — a natural partner for CQRS (13.13).

  4. 04

    The audit/source-of-truth story is why finance, compliance, and 'explainable' systems love it.

  5. 05

    Costs: event store is append-only + immutable; snapshotting needed for replay speed; schema evolution of events is a discipline.

  6. 06

    Idempotent consumers of events → the projection is automatically rebuildable (replay from zero).

  7. 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

state = fold over eventsdiagram
Rendering diagram…
EventSourcingSketch.mdmarkdown

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 trivially

Explain without notes

01

Your customer calls about a dispute: where does event sourcing make the answer 10x cheaper? (audit trail)

Practice

01

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.

Back to phase