Back to 20 Concepts
distributed-data • Expert
Event Sourcing & CQRS (Command Query Responsibility Segregation)
Event Sourcing stores state as an immutable sequence of domain events rather than current state snapshots. CQRS splits the write model (optimized for validation) from the read model (optimized for denormalized queries).
Intuitive Mental Model
The Accountant's Transaction Ledger vs Bank Account Balance: The database does not just store "Balance = $100". It stores: +$500 Deposit, -$300 Rent, -$100 Groceries. You can rewind or replay history to any millisecond in time.
Architecture Blueprint & CodeProduction Standard
// Event Store:
// 1. AccountCreated { accountId: "acc_1", balance: 0 }
// 2. MoneyDeposited { accountId: "acc_1", amount: 500 }
// 3. MoneyWithdrawn { accountId: "acc_1", amount: 100 }
// Current State (Replayed) = $400Key Architectural Takeaways
- •Complete Audit Trail: Impossible to lose history or transaction records.
- •Read Model Projections: Background consumers project event streams into Elasticsearch, Redis, or SQL read replicas for instant queries.
Common Architectural Pitfall
Replaying 10,000,000 events from beginning of time on every read query.
Production Best Practice
Create periodic snapshot checkpoints (e.g. every 1,000 events) and replay from the latest snapshot.