CQRS and Materialized Views
CQRS separates command-side invariants from read-side projections; a materialized view is derived state optimized for a query.
CQRS and Materialized Views
CQRS separates command-side invariants from read-side projections; a materialized view is derived state optimized for a query. Commands validate and update authoritative state in a transaction. An outbox records events atomically. Projectors consume events and update read models using stable event identity and version checks. Projections are rebuildable from retained events or snapshots. Read APIs declare projection lag and may use the authoritative path for read-your-writes.
Mechanism and worked example
An order service stores normalized orders and inventory reservations. A customer dashboard projection joins order summaries and shipment milestones into a query-friendly document. Replay rebuilds the view; a projection version enables blue/green rebuild and cutover.
| Component | Owns | Recovery |
|---|---|---|
| Command model | Authoritative invariants | Database backup and transaction log |
| Outbox | Durable event intent | Relay retry and deduplication |
| Projector | Transforms events | Checkpoint and replay |
| Read model | Query-optimized derived state | Rebuild and versioned cutover |
Failure modes and operations
Projection lag shows stale status. Duplicate or out-of-order events can regress a view without version guards. Rebuild can overload source or collide with live writes. Deleted records can reappear if tombstones expire before replay. Old events need compatible readers.
Trade-offs and design boundary
CQRS improves read-model flexibility and isolates read load but introduces eventual consistency, duplicate state, projection operations and replay complexity. For simple CRUD, one transactional model and indexes are usually cheaper.
Interview transfer exercise
A user places an order but the dashboard projection is delayed. Return the command result or read authoritative order state until projection catches up; do not promise immediate projection consistency.
Read the diagram
Command commits state and outbox → Relay publishes stable event identity → Projector applies event version → Read API exposes freshness or authoritative fallback
A user places an order but the dashboard projection is delayed. Return the command result or read authoritative order state until projection catches up; do not promise immediate projection consistency.
Your design draft
Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.
Self-review checklist
Self-guided practice. Automated AI feedback and code execution are not connected.