Event Sourcing and Event Streams
Store state as an immutable append-only sequence of domain events, enabling full audit trails, time-travel debugging, and event replay.
Most software developers are taught to think of databases as storage containers for current state. When a customer changes their shipping address, the application issues an UPDATE customers SET street = '...' WHERE id = 42. The old street name is permanently overwritten and vanishes from the database.
In many high-stakes domains (such as banking, healthcare, supply chain logistics, and insurance), this destructive in-place mutation creates critical problems:
- Loss of intent and causality: You know a bank account currently holds $150, but you cannot prove whether that balance resulted from ten small deposits or a single $10,000 transfer followed by large withdrawals.
- Fragile audit logs: Organizations attempt to fix this by writing separate audit rows in shadow tables or reading database change logs. But if the application writes to the main table and fails to write to the audit table, records diverge.
- Inability to time travel: If regulators ask for the exact financial state of the ledger as of 11:45 PM on December 31st, a mutable database cannot reconstruct that point in time without restoring old full-disk backups.
Event Sourcing fundamentally rethinks data persistence: instead of storing current state, you store an immutable, append-only log of every state-changing event that has ever occurred.
01Core concepts and intuition
In Event Sourcing, the append-only event stream is the single source of truth. Current state is never stored as the authoritative record; current state is simply a derived projection calculated by replaying past events in chronological order.
Think of an accounting ledger: accountants never take an eraser to a ledger book to change a balance. When money leaves an account, they append a new debit transaction line. The balance is simply the sum of all lines from the beginning of time.
Key components of Event Sourcing
- Domain Events: An immutable record of something meaningful that happened in the business domain in the past.
- Events are named as past-tense verbs:
AccountOpened,FundsDeposited,WithdrawalAttempted,OrderCancelled. - Events are factual and cannot be altered or deleted. If an error was made, a compensating event is appended (e.g.,
ChargeReversed).
- Events are named as past-tense verbs:
- The Event Store: An append-only database optimized for sequential writes and fast retrieval of event streams by aggregate ID (e.g., EventStoreDB, Apache Kafka, or PostgreSQL with an append-only table).
- Aggregate Reconstitution (Event Replay): To process a new business command, the system loads all past events for that specific entity ID, passes each event sequentially into the domain object to build its current in-memory state, validates the new command against that state, and appends the resulting new event.
Loading the rest of the lesson…