Event Sourcing and CQRS
Event sourcing stores the history of state changes instead of the current state. CQRS separates the write model from the read model. They are independent patterns that are often used together, and both are frequently adopted for the wrong reasons.
The 60-second answer
Section titled “The 60-second answer”Event sourcing persists every state change as an immutable event in an append-only log; the current state is a fold over that log. CQRS splits writes (commands, validated against the aggregate) from reads (denormalised projections optimised per query). The benefits are a complete audit trail, time travel, and the ability to build new read models by replaying. The costs are eventual consistency between write and read models, schema evolution over years of events, projection rebuild time, and a much higher learning curve. I would use it where the history itself is the business value — ledgers, orders, permissions — not for a CRUD admin panel.
The model
Section titled “The model”command ─→ aggregate (validates) ─→ events appended to log │ ├─→ projection A: current order state (SQL) ├─→ projection B: analytics (warehouse) └─→ projection C: search indexread ────────────────────────────────────┘A concrete sequence for a bank account:
AccountOpened {account_id: 42, owner: "ana"}MoneyDeposited {account_id: 42, amount_cents: 10000}MoneyWithdrawn {account_id: 42, amount_cents: 2500, atm: "SP-01"}The balance is not stored; it is 10000 - 2500 = 7500, derived by folding the events in order.
Nothing is ever updated or deleted — corrections are new events (MoneyDepositedReversed).
Contrast with state-oriented storage, where you keep one row with balance = 7500 and lose the
reason.
Aggregates and command validation
Section titled “Aggregates and command validation”An aggregate is the consistency boundary. A command loads the aggregate’s events, rebuilds its state, validates the invariant, and appends new events.
class Account attr_reader :balance_cents, :frozen
def self.load(store, id) account = new store.events_for(id).each { |e| account.apply(e) } account end
def withdraw(amount_cents) raise "frozen" if frozen raise "insufficient funds" if amount_cents > balance_cents Events::MoneyWithdrawn.new(account_id: @id, amount_cents: amount_cents) end
def apply(event) case event when Events::MoneyDeposited then @balance_cents += event.amount_cents when Events::MoneyWithdrawn then @balance_cents -= event.amount_cents end endendThe rule: never validate against a read model. Validation that reads a projection is racy and defeats the point. Every invariant must be checkable from the aggregate’s own events.
Optimistic concurrency: the append includes the expected stream version, so two concurrent commands cannot both succeed. This is the write-side consistency mechanism.
Projections
Section titled “Projections”A projection consumes the event stream and writes a query-optimised view.
def handle(event) case event when Events::MoneyWithdrawn db.exec("UPDATE balances SET cents = cents - $1 WHERE account_id = $2", [event.amount_cents, event.account_id]) end checkpoint(event.position)endProjections are:
- Idempotent, because the stream will be redelivered. Store the last processed position in the same transaction as the view update.
- Rebuildable, because the log is the source of truth. Drop the table, replay from zero.
- Independent, so each consumer group can build a different view at its own pace.
- Lagging, so every read of a projection is potentially stale by some milliseconds to seconds.
That last point is the one candidates underestimate: with CQRS, “user updates their profile and immediately reloads the page” can show the old value. Fix it by reading your own writes from the event stream, by returning the updated state in the write response, or by waiting on the projection position before responding.
Snapshots
Section titled “Snapshots”Replaying 10,000 events to load an aggregate is slow. Store a snapshot every N events:
snapshot@v1000 + events 1001..1042 → current stateA snapshot is a cache, not a source of truth. It can be deleted and rebuilt, and it must be versioned so a schema change invalidates old snapshots rather than corrupting state.
Schema evolution
Section titled “Schema evolution”Events are immutable and will outlive your code. You will read events written by a version of the code you no longer have.
Strategies:
- Weak schema / tolerant reader. Consumers ignore unknown fields and tolerate missing ones. Cheapest, works well for additive changes.
- Explicit versions with upcasters:
event.v1 → event.v2transformations applied on read. - Copy-and-replace for breaking changes: write a new stream and retire the old one.
Never rename a field’s meaning in place. An event written two years ago will be interpreted by today’s code, and silently wrong data is worse than a failed parse.
When it is worth it
Section titled “When it is worth it”| Signal | Why event sourcing helps |
|---|---|
| The history is the business requirement | Audit, dispute resolution, regulatory reporting |
| You need to answer new questions about the past | Replay into a new projection |
| Multiple read models over the same facts | Analytics, search, operational views |
| Corrections must be explicit and traceable | Append a reversing event |
| You need temporal queries (“state at time T”) | Fold to a timestamp |
When it is not worth it:
- The domain is CRUD and nobody asks what happened before.
- The team has not operated a projection pipeline before.
- Strong read-after-write consistency is required everywhere.
- The data is simple enough that an audit table plus a trigger would do.
- You cannot afford to rebuild projections over a large log.
A plain audit_log table alongside normal mutable state gives you most of the audit benefit at a
fraction of the cost. That is a legitimate design, and saying so is a good answer.
CQRS without event sourcing
Section titled “CQRS without event sourcing”CQRS alone is much cheaper: write to a normal database, and maintain denormalised read tables (updated in the same transaction, or asynchronously). You get query-specific models without an event log.
write: orders, order_items (normalised, transactional)read: order_summary (one row per order, precomputed totals, customer name)The synchronous variant has no staleness but duplicates data. The asynchronous variant has staleness but scales reads independently. Both are common; neither is exotic.
CQRS without event sourcing is the sane first step. Event sourcing is the expensive one.
Follow-up questions
Section titled “Follow-up questions”- How do you handle a bug that wrote 10,000 wrong events?
- What is the read-after-write problem in CQRS and how do you solve it for the user?
- Why must projections be idempotent, and where do you store the checkpoint?
- How do you delete a user’s data from an immutable log (GDPR)?
- When does a snapshot become a liability?
- How do you version an event schema for five years of history?
Common traps
Section titled “Common traps”- “Event sourcing is an audit log.” An audit log is a side record; here the events are the state. Losing the log loses the system.
- “Replay is always possible.” Only if events are self-contained and external side effects (emails, payments) are kept out of the projection or made idempotent.
- “CQRS means eventual consistency everywhere.” Only if projections are asynchronous. CQRS with a shared transaction is strongly consistent.
- “Immutable means we cannot delete data.” Crypto-shredding (destroy the per-user encryption key) is the standard answer; a real delete also needs a compaction path.
- “It will make the system simpler.” It moves complexity from the model to the infrastructure. Budget for it.