Event Sourcing (ES) and CQRS: A Deep Dive
As Sherlock Holmes might deduce from the clues in your query, Event Sourcing and CQRS form a powerful architectural pattern for building scalable, auditable systems. They shine in domains like finance, e-commerce, or any system needing rich audit trails, temporal queries, or high throughput.
Quick Definitions
- Event Sourcing (ES): The application's state is derived by replaying a sequence of immutable events stored in an append-only log, rather than mutating a single "current state" in a database. Events capture what happened (facts), not how the state looks now.
- CQRS (Command Query Responsibility Segregation): Separates writes (Commands → mutate via events) from reads (Queries → optimized views). ES powers the write side; projections build read-optimized models.
Together: Commands → Events (ES store) → Projections → Read Models.
1. Command → Event Flows
Commands are imperative requests (e.g., PlaceOrder). An Aggregate (e.g., Order root entity) validates the command against its current state (replayed from events), then emits new events (e.g., OrderPlaced, ItemAdded).
Architecture Sketch (high-level flow):
[Client] → Command → [Command Handler] → [Aggregate] → Events → [Event Store] (append-only)
↓
[Projections] → [Read DBs]
↓
[Client] ← Query ← [Query Handler] ← [Read Model/View]
Pseudocode Example (C#-inspired):
public class PlaceOrderCommand { public Guid OrderId; public string Product; public int Qty; }
public class OrderAggregate {
private List<IDomainEvent> _changes = new();
public void Handle(PlaceOrderCommand cmd) {
if (/* validation fails */) throw new InvalidCommandException();
_changes.Add(new OrderPlaced(cmd.OrderId, cmd.Product, cmd.Qty));
}
public IEnumerable<IDomainEvent> GetChanges() => _changes;
}
public class CommandHandler {
private readonly IEventStore _store;
public async Task Handle(PlaceOrderCommand cmd) {
var aggregate = await _store.Load<OrderAggregate>(cmd.OrderId);
aggregate.Handle(cmd);
await _store.AppendEvents(cmd.OrderId, aggregate.GetChanges()); // Append to stream
}
}
2. Append-Only Logs and Serialization
- Event Store: A partitioned log (e.g., per Aggregate ID). Streams are append-only:
EventId | Timestamp | Type | Data | Metadata.
- Serialization: Events as JSON/Avro/Protobuf with schema versioning. Stored immutably for replay.
- Tools: EventStoreDB, Kafka, Azure Cosmos DB (with partitioning).
Log Structure Sketch (ASCII):
Stream: order-123 (append-only)
Seq# | EventType | Data (JSON snippet) | Version
1 | OrderPlaced | {"product":"laptop","qty":1} | 1
2 | ItemAdded | {"product":"mouse","qty":1} | 2
3 | OrderShipped | {} | 3 ← Current head
3. Read Models and Projections
- Projections: Subscribers (e.g., via Kafka Streams, Axon Server) replay events to build read models (denormalized views in SQL/NoSQL for fast queries).
- Types:
- Live Projections: Real-time (eventual consistency).
- Catch-up Projections: Replay from snapshot + tail log.
Sketch:
Event Store ─events─→ [Projector 1] → [SQL DB: OrderSummary {Id, Total, Status}]
→ [Projector 2] → [Mongo: Inventory {Product, Stock}]
→ [Projector 3] → [ES: CustomerOrders {CustId → [OrderIds]}]
Code Sketch (Projection):
public class OrderSummaryProjection {
public async Task Project(OrderPlaced evt) {
await _readDb.Execute($"INSERT INTO OrderSummary (Id, Total) VALUES (@id, @total)");
}
}
4. Idempotency and Replay
5. Snapshotting
- Snapshots: Periodic "checkpoints" of aggregate state (e.g., every 1000 events) to avoid full replays.
- Store:
{AggregateId, Version, SerializedState}.
- Load: Snapshot (if exists) + delta events.
Flow Sketch:
Load: If snapshot@ver=500 exists → Replay 501..head (fast)
Save: After append, if (newVersion % 1000 == 0) → Snapshot state@newVersion
Code:
if (await _store.TryGetSnapshot(id, out var snapshot)) {
aggregate = Deserialize<Order>(snapshot.Data);
var events = _store.ReadStream(id, snapshot.Version + 1);
foreach (var evt in events) aggregate.Apply(evt);
}
6. Consistency Models
- Eventual Consistency: Default. Writes immediate (optimistic CC), reads lag (projections async).
- Options:
| Model | Use Case | Tradeoff |
|---|
| Strong | Outbox pattern + 2PC | Slow, complex |
| Causal | Read-your-writes (check event version) | Medium |
| Eventual | Most apps (projections) | Fast, scalable |
- Saga/Outbox for distributed txns.
7. Evolution/Versioning
8. Scaling
- Sharding: Partition streams by Aggregate ID (hash).
- Event Store: Kafka (high throughput), EventStoreDB (ACID streams).
- Projections: Parallel (e.g., Kafka Streams), materialized views.
- CQRS Bonus: Scale writes/reads independently (e.g., writes to Kafka, reads to Cassandra).
- Horizontal: Multiple projectors, polyglot reads.
Scaling Sketch:
Writes: 10k cmd/s → EventStore (sharded) → Kafka (replicated)
Reads: [ElasticSearch] [Redis Cache] [SQL OLAP]
9. Testing
Pros/Cons Summary
| Pros | Cons |
|---|
| Auditability, scalability | Complexity, learning curve |
| Temporal queries, flexibility | Event store cost, projections lag |
Tools Stack Example: Axon Framework (Java), EventFlow (.NET), Lagom (Scala), or custom with Kafka + Postgres.
This pattern deduces a system's past from its events—much like Holmes from clues. Questions on implementation?