CQRS — Command Query Responsibility Segregation
Separate write model (commands, business rules) from read model (queries, denormalized views).
Can use CQRS without event sourcing (dual DB schemas). Often paired together.
Write side
- Accept commands:
PlaceOrder,CancelOrder - Enforce invariants on write model / aggregate
- Persist events or updated rows
Read side
- Materialized views optimized for queries
- Updated synchronously (same txn — rare) or async projection (common)
Command → Write DB → event → Projector → Read DB (Elasticsearch, Redis, SQL view)
Eventual consistency on reads
User places order → read model may lag 100ms–seconds.
UX mitigations:
- Return write model ID; poll or push when ready
- Read-your-writes — route to primary or version check
Staff interview: state acceptable lag per use case.
Projection design
| Read model | Optimized for |
|---|---|
| Order by customer | customer_id index |
| Ops dashboard | pre-aggregated counts |
| Search | Elasticsearch full-text |
Multiple projectors consume same event stream — each builds its view.
CQRS + microservices
Each service may have internal CQRS. Cross-service: don't query another service's DB — call API or subscribe to events.
Anti-pattern: shared read replica across service boundaries.
vs caching
Cache = optional optimization on read path. CQRS = first-class separate schema maintained by pipeline.
Saga connection
Long-running workflows emit events; projectors update status views. Saga orchestration in Distributed Systems → Transactions.
When interviewer asks "CQRS?"
Answer: "Separates write complexity from read scale. Pays off when read patterns vastly outnumber writes or need different storage (graph vs relational). Costs operational complexity — projections, lag, schema drift."
Further Reading
- Martin Fowler — CQRSArticle15m
- microservices.io — CQRS patternArticle15m
- Eventuate — Event-driven architecture patterns (sagas + CQRS overview)Reference20m
Hands-On Tasks (Optional)
Architecture drills and whiteboard exercises. Assumes Communication & Data Transfer and Distributed Systems fundamentals.
- Design CQRS read models for orders15m
Write model: Order aggregate. Read models: customer order history (list), ops dashboard (counts by status). How do projections update? Lag tolerance?