What it is
Command Query Responsibility Segregation (CQRS) uses one model to change data and another model to read it. Commands ("place order", "change address") go to a write model that validates input and enforces business rules. Queries go to one or more read models built for the screens and APIs that need them: denormalised, pre-joined, possibly in a different store. The name extends Bertrand Meyer's command-query separation (CQS) from methods to whole models; Greg Young and Udi Dahan popularised it around 2010.
Why it exists
Reads and writes rarely look alike. Writes touch one aggregate and must be correct; reads join many entities and must be fast. Reads often outnumber writes 10:1 or 100:1. One normalised model makes the expensive reads compete with the important writes for the same connections and locks, and forces every screen's query shape onto the domain model. Separating them lets each side be shaped, stored and scaled for its own job.
How it works
- A command arrives (
PlaceOrder). The command handler loads the aggregate from the write store, runs the rules and commits. - The change is published as an event (
OrderPlaced), ideally through a transactional outbox so the event and the commit cannot diverge. - A projector (projection handler) consumes events and updates one or more read models: a row per order list entry, a document per customer page, a search index.
- A query reads the read model directly, with no business logic in the way.
Read models are disposable: because they are derived from the write side, you can drop one and rebuild it by replaying events (or re-running a query over the write store). The read side is eventually consistent: between the commit and the projection there is a window in which a query returns the previous state.
Levels of CQRS. Not all-or-nothing:
- Code-level: separate command and query handlers over one database (in .NET often MediatR-style handlers, or plain classes); queries may use Dapper or SQL views. No lag.
- Same database, separate read tables updated in the same transaction or by triggers/materialised views. Little or no lag, limited independence.
- Separate read stores updated asynchronously from events. Full independence, real lag.
// Command side: rules and one aggregate per transaction
public async Task<long> Handle(ChangeAddress cmd, CancellationToken ct)
{
var order = await _db.Orders.SingleAsync(o => o.Id == cmd.OrderId, ct);
order.ChangeAddress(cmd.Address); // invariants live here
_db.Outbox.Add(OutboxMessage.From(new AddressChanged(order.Id, cmd.Address, order.Version + 1)));
await _db.SaveChangesAsync(ct); // order + outbox, one transaction
return order.Version; // let the caller wait for this version
}
// Query side: no domain model, just the shape the screen needs
public Task<OrderSummary?> Handle(GetOrderSummary q, CancellationToken ct) =>
_readDb.QuerySingleOrDefaultAsync<OrderSummary>(
"select * from order_summaries where order_id = @Id and version >= @MinVersion", q);
When to use it
- Read and write workloads differ strongly in volume, shape or scaling needs.
- Screens need data from many aggregates or contexts (dashboards, search, feeds).
- The write model has rich rules you want to keep free of query concerns.
- You already use event sourcing: the event store is a poor query engine, so read models are needed anyway.
When not to
- CRUD screens where reads and writes have the same shape.
- Small systems where one database comfortably serves both.
- Domains where users must see every change immediately everywhere and you cannot design around lag.
- Teams not yet comfortable operating queues, replays and lag monitoring.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Separate read store | Fast, screen-shaped queries; scale reads independently | Eventual consistency, a second store, projection code |
| Asynchronous projections | Commands stay fast; read side can fail without blocking writes | Lag, stale reads, replay tooling |
| Synchronous read-table updates | No lag | Slower commands; a failing read table fails writes |
| Many read models | Each screen gets the perfect shape | More projections to maintain and rebuild |
Alternatives
- Read replicas: copies of the same model; scale reads without new query shapes. Also lag (see database replication).
- Caching: cache-aside on the hot queries; cheap, but same shapes and invalidation issues.
- Materialised views / indexed views in the database: precomputed joins without a separate pipeline.
- Search engine as a secondary index: effectively a single read model for search, fed by change data capture.
Failure modes
- Silent lag. A slow or stuck projector produces no errors, only older answers. In the lesson, stale reads multiply while the error rate stays at zero.
- Lost or duplicated events. Publishing without an outbox can drop events (read model never updates); at-least-once delivery means projectors must be idempotent (track the last applied event position or version per read model).
- Out-of-order events. Projections that assume order break when partitions or retries reorder events; key by aggregate and check versions.
- Read-your-writes surprises. Users save, reload and see the old value, then save again.
- Rebuild pain. A new read model over years of history can take hours to project; plan for parallel rebuild and cut-over.
In production
Make projectors idempotent and checkpointed. Expose projection lag as a metric (oldest unprocessed event age, checkpoint gap) and alert on it. Return the new version from commands; let queries accept a minimum version and wait briefly, or route a user to the write side right after their write. Keep read models disposable and rebuildable; version their schemas so a new projection can be built alongside the old one. Use an outbox (or CDC) between the write store and the broker.
Common misconceptions
- "CQRS requires event sourcing." No. A relational write model plus an outbox works fine. Event sourcing usually implies CQRS, not the other way round.
- "CQRS means two databases." Separate code paths over one database are already CQRS, without lag.
- "Eventual consistency means minutes of staleness." Typical lag is milliseconds to seconds; the point is that it is non-zero and unbounded under failure.
- "CQRS is an architecture for the whole system." It is a pattern for a bounded context, applied where it pays.
Interview angle
Use CQRS when you can name the asymmetry: "90% reads, joins over five tables, feed shaped per user". Draw command → write store → outbox → broker → projector → read store ← query service, then volunteer the consistency story: lag, stale reads, how you monitor it, how users see their own writes (versions, waiting, sticky routing), idempotent projectors, rebuilds by replay. Saying you would start with separate handlers over one database shows judgement.
Model assumptions
The simulation is a simplified model, not a benchmark. Requests arrive as a Poisson stream; 10% are commands, and keys follow Zipf(1.0) over 40 orders, so a few orders are hot. Before the split: an API with 32 workers (5 ms) and one database with 10 connections, 35 ms per join query and 12 ms per command (lognormal, cv 0.4). After the split: the gateway routes writes to the command service (16 workers, 8 ms) and reads to the query service (16 workers, 20 ms) over a read model answering in ~4 ms. The command service commits, then publishes to a queue consumed by a projector (simulated messages). How far the read model trails the write model is modelled as asynchronous replication with a fixed delay (150 ms, later 2 s), drawn as the link between the two databases; a read is counted stale when its order had a write acknowledged that the read model had not yet applied. The single user's write-then-read sequences are scripted packets on top of the simulated traffic. Numbers show behaviour and orders of magnitude only.