Tutorials System Design Mastery
Event Sourcing & CQRS: Decoupling reads from writes
On this page
Event Sourcing & CQRS
In traditional apps, we only store the "Current State" (e.g., balance = $100). In Event Sourcing, we store every Event that ever happened (+ deposit $50, - withdraw $20). Current state is just the sum of all events.
1. CQRS (Command Query Responsibility Segregation)
Separate the "Write" model from the "Read" model.
- Command: Performs the update (e.g., SQL Server). High transactional integrity.
- Query: Performs the fetch (e.g., Elasticsearch or Read-only replicas). Optimized for fast searching.
2. Why use them together?
When an Event is saved to the Event Store (Write), a background worker updates the Search Index (Read). This makes your app incredibly fast for users (O(1) reads) and provides a perfect "Audit Log" of everything that ever happened.
4. Interview Mastery
Q: "What is a 'Snapshot' in Event Sourcing?"
Architect Answer: "If a user has 1 million events, calculating their balance by reading every event would take forever. A **Snapshot** is a memoized current state saved every 1,000 events. When we need the current state, we load the latest snapshot and then only replay the few events that happened *after* that snapshot. This keeps the system fast even as history grows."
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!