CQRS: separate models for writes and reads
Validate writes on one model and serve each kind of read from a model shaped for it.
15 min readOne model rarely fits both jobs
Writes need a normalised model that enforces invariants: an order cannot ship twice, stock cannot go negative. Reads want something else entirely: a denormalised feed, a full-text search, a dashboard of totals. Forcing both through one schema produces joins across ten tables on every page view. Command Query Responsibility Segregation (CQRS) splits them: commands go to a write model that validates and records changes, and queries go to one or more read models, each shaped for a specific screen or API.
Keeping read models up to date
Read models are projections. Projectors consume the change stream, from event sourcing, an outbox or CDC, and update each read store: a search index, a Redis sorted set, a denormalised table. Because the projections are asynchronous, they lag the write model by milliseconds to seconds under normal load and by longer during a backlog. If a projection is corrupted or you need a new one, rebuild it by replaying the stream, which requires keeping the history.
Reading your own writes
The classic CQRS complaint: a user saves a change, the page reloads, and the old value is still there because the projection has not caught up.
- Return the new state from the command and render it directly
- Return a version token and let the read side wait until its projection has reached that version
- Read from the write model for that user for a few seconds after they write
- Update the UI optimistically and reconcile when the projection catches up
When it is worth it
CQRS pays off when reads and writes differ sharply in volume or shape: a 1 000-to-1 read ratio, reads that need search or ranking, or several very different views of the same data. For ordinary CRUD screens it adds a second store, a pipeline and eventual consistency for no benefit. Many systems apply it to one hot path (the feed, the search page) and keep everything else simple.
Key takeaways
- CQRS separates a write model that enforces rules from read models shaped for queries
- Read models are projections of a change stream and lag behind writes
- Plan explicitly for read-your-own-writes
- Apply CQRS to hot or complex read paths, not to every CRUD screen
Sign in to track lessons and earn badges.