Theory
Event Sourcing Deep Dive
π Overview
Event Sourcing is a paradigm shift where the primary data store contains a sequence of immutable events rather than the current state of an object. To determine the "current state," the system replays these events from the beginning. It provides an absolute audit trail and allows for "temporal queries"βviewing the system state as it was at any point in the past.
ποΈ Core Principles & Characteristics
- Immutable Log: Events can only be appended; they can never be updated or deleted.
- Aggregates: Domain objects that process commands and generate events.
- Snapshots: To avoid replaying millions of events, the system periodically saves the state (e.g., every 100 events) as a "snapshot."
- Projections: Read-models built by consuming the event stream (part of CQRS).
- Replay: The process of running events through the domain logic to reconstruct state.
βοΈ Trade-offs: Pros & Cons
- Pros:
- Perfect Auditability: Invaluable for finance, healthcare, and legal systems.
- No Data Loss: Unlike CRUD, which overwrites old data, Event Sourcing keeps every detail.
- High Write Performance: Appending to a log is significantly faster than updating complex relational rows.
- Cons:
- Read Complexity: Requires a separate "Read Model" (CQRS) to be performant.
- Versioning: Handling changes in event structure over years (Upcasting) is difficult.
- GDPR Compliance: "Right to be forgotten" is hard in an immutable log (requires encryption or tombstone patterns).
π Real-World Implementation
- Version Control (Git): Your code is a series of commits (events); the current file is the projection.
- Google Docs: Every keystroke is an event, allowing for "Undo" and collaborative conflict resolution.
- Accounting Systems: Every debit/credit is an event; the balance is the result of the sum.
π‘ Interview "Gotchas" & Tips
- Upcasting: How do you handle an old
OrderCreatedevent that is missing a newtax_idfield? (Answer: Use an Upcaster to transform the event on-the-fly during replay). - Poison Pills: A malformed event that crashes the replay logic. Need a strategy to skip or isolate these.
- Event Store vs. Message Bus: A message bus (Kafka) is for communication; an Event Store is for persistence.
- Snapshots: Explain that snapshots are an optimization, not the source of truth.
π Suggested Architecture Primitives
- Append-Only Event Log: The core storage.
- Snapshot Store: Optimized for fast key-value retrieval.
- Projection Engine: To transform events into searchable read models (e.g., ElasticSearch/Postgres).
Canvas