CQRS / Event Sourcing (Overview)
Separate write and read concerns; optionally persist domain history as events.
📌 Key IdeaCQRS separates command and query models for scalability and clarity. Event sourcing stores state changes as immutable events, enabling replay/audit but increasing operational complexity.
Why It Matters
- Read and write workloads often diverge, and one model cannot optimize both well.
- Event sourcing adds auditability and replay capability for complex domains.
- Understanding trade-offs helps avoid over-engineering simple CRUD systems.
Visual
🧩 CQRS + Event Sourcing high-level flow
Write command -> validate -> append Event
|
v
project/read-model updates
|
v
query side serves reads
Write/read models can evolve independently.When to Use
- Complex domains with divergent read/write workloads.
- Strong audit/history requirements and replay value.
- Systems benefiting from independently scaled read models.
When NOT to Use
- Simple CRUD domains where complexity offers little gain.
- Teams lacking operational maturity for eventual consistency + projection maintenance.
Code Variations
Event append + projection sketchjava
eventStore.append(new OrderPlaced(orderId, items));
projection.apply(new OrderPlaced(orderId, items));Real systems handle idempotency, ordering, retries, and projection lag.
Common Confusions Cleared Up
CQRS vs Event Sourcing
CQRS is model split (commands/queries). Event sourcing is persistence model (events as source of truth). They are often used together but independent choices.
Interview Q&A
Quick Cheat Sheet
CQRSSeparate write and read models.
Event sourcingPersist events; rebuild state by replay.
CostComplexity and eventual consistency management.