Notes

Part 9 of 10

Event sourcing and CQRS

Every model so far reads data in the form it was written. In complex apps no single form serves every read, so it can help to write in one form and derive read-friendly forms. This builds on systems of record, derived data, and ETL, but now you deliberately pick one form tuned for writes and others tuned for reads.

The most write-friendly form is an event log: each write is a self-contained record (perhaps JSON) with a timestamp, appended to a sequence. Events are immutable: never edited or deleted, though later ones may override earlier ones. An event can carry any properties.

Take a gym: members book and pay by card, companies buy blocks of passes by invoice and assign them later, some spots are held for trainers, bookings get canceled, and classes move between studios of different sizes. Even "how many spots are left on Tuesday?" gets hard.

Every change ("class was scheduled", "spot was booked", "booking was canceled") is first stored as an event. Each new event also updates several materialized views (projections, read models), like a member's booking status, the manager's dashboard charts, or the day's attendance sheets.

  • Event sourcing: events are the source of truth, and every state change is an event.
  • CQRS (command query responsibility segregation): separate read-optimized forms, derived from the write-optimized one.

A user's request is a command, and it is checked first. Only once it has run and proved valid (a spot was free) does it become a fact and get appended. So the log holds only valid events, and a view builder may not reject one.

A class booked through a log

Step 1 of 5

The first event: a class was scheduled with 3 spots. Both read views are worked out from the log.

Name events in the past tense, like "spot was booked", since they record what happened. A later cancellation is a new event; the booking stays, because it did happen.

The log resembles a star schema fact table, as both hold past events, but:

  • Fact rows share one set of columns; events come in many types with different properties.
  • Fact tables have no order; events must be handled in order (booking before its cancellation).

Benefits

Guess first

A read view shows the wrong number of spots because of a bug. What is the cleanest fix?

A read view shows the wrong number of spots because of a bug. What is the cleanest fix?
  • Intent is clear: "booking was canceled" says why, while a set of changed, deleted, and inserted rows does not.
  • Views are reproducible: same events, order, and code give the same view, so you fix a view bug by fixing the code and rebuilding, which makes debugging easy.
  • Many views: each shaped for its queries, in any database or model, denormalized for speed, or even only in memory if rebuilding on restart is fine.
  • Easy change: a new screen is a new view of the existing log, new event types or properties leave old events alone, and new behavior can hook onto old events (offer a canceled spot to the waiting list).
  • Undo: a later event can cancel a wrong one and views correct themselves, unlike a committed transaction in an update-in-place database, and fewer one-way actions make change easier.
  • Audit: the log is an audit trail, which regulated industries value.
  • Write speed: sequential appends let a log take more writes than a typical database, absorbing bursts while views catch up at their own pace.

Try it

A class booked through a log

1 events in the log

Event log, only added to

  1. 1. Class was scheduled with 3 spots

Spots left

3

Who's coming

Nobody yet

The class is scheduled.

The views are never edited directly. Both are worked out from the log, so rebuilding them always gives the same answer.

Pitfalls

  • Outside data: a live exchange rate gives a different answer on rebuild, so store the rate in the event, or look up the rate for the event's timestamp from a source that always answers the same.
  • Erasing personal data: immutable shared logs clash with laws like GDPR (a per-user log can just be deleted), so keep personal data outside events or encrypt it with a key you later throw away (crypto-shredding), both of which make rebuilding harder.
  • Side effects: rebuilding must not repeat outside actions, like sending confirmation emails again.

Event sourcing can sit on any database, or on purpose-built tools like EventStoreDB, MartenDB (on PostgreSQL), and the Axon Framework. Brokers like Kafka can hold the log, with stream processors updating views (chapter 12). The one hard rule: every view must process events in exactly log order, which is tricky in distributed systems (chapter 10).