Course contentsShow
← Databases & SQL
Lesson 1727 of 1,95316. Distributed Data ArchitecturesFree lesson

Event Sourcing

Reconstruct state by storing the history of immutable events rather than current snapshots.

In this lesson, you will learn how to shift from storing "current state" to capturing the complete history of changes as an immutable sequence of events.

From State to Stream

In traditional relational modeling, we often overwrite data. If a user updates their email address, we UPDATE users SET email = 'new@ex.com' WHERE id = 1. In doing so, the previous state is permanently destroyed. Event Sourcing flips this paradigm: instead of storing the result of an action, we store the action itself as an immutable event.

In an Event Sourcing architecture, your database acts as an append-only log. The current state of an entity is merely a derivative of its past. If you want to know a user's current email, you replay every EmailChanged event associated with that user from the beginning of time.

The Anatomy of an Event Log

Consider a simplified bank account ledger. Instead of a row with a balance column, your table looks like this:

EventIDAggregateIDEventTypePayloadTimestamp
1acct_01AccountOpened{"owner": "Alice"}10:00
2acct_01FundsDeposited{"amount": 500}10:05
3acct_01FundsWithdrawn{"amount": 200}10:10

To reconstruct the current state (a balance of 300), you perform a simple query:

SELECT payload 
FROM event_store 
WHERE aggregate_id = 'acct_01' 
ORDER BY timestamp ASC;

Why Do This?

  1. Perfect Audit Log: You never lose track of why or when data changed. The history is the source of truth.
  2. Temporal Querying: You can "travel back in time" to see exactly what the state was at any specific timestamp by replaying events up to that point.
  3. Debugging: If a calculation bug occurs, you can fix the logic and replay the events to derive the correct historical state.

While replaying thousands of events for every query is inefficient, we typically solve this by calculating a "Snapshot" of the state at specific intervals (e.g., every 100 events) and storing it to expedite reads.

Key Takeaway: By shifting the source of truth from the current state to an immutable log of events, you gain a complete historical audit trail and the ability to derive state at any point in time.