What Is CQRS? Command Query Separation Explained
On this page
Learning Objective
State what CQRS actually asserts and what it does not, explain why a single model optimized for both writing and reading is usually optimized for neither, and separate the pattern itself from the event sourcing and separate-database choices that are frequently confused with it.
Concept Explanation
CQRS stands for Command Query Responsibility Segregation, and the claim it makes is narrower than its reputation. It says that the model used to change state and the model used to read state are two different models, and that trying to serve both with one is a compromise. That is the whole pattern. It does not require event sourcing, it does not require two databases, it does not require a message broker, and it does not require eventual consistency. Each of those is a choice that can be layered on top, and conflating them with CQRS itself is the single most common source of confusion about it.
The reason the separation pays is that the two sides want opposite things. The write side cares about invariants, so it wants a normalized model with a clear consistency boundary, enough structure to validate a command, and no redundancy that could become inconsistent. It handles one aggregate at a time and touches very little data. The read side cares about answering questions cheaply, so it wants denormalization, precomputed joins, data duplicated into exactly the shape each screen needs, and indexes tuned per query. It spans many entities and is typically one or two orders of magnitude higher in volume.
A single model serving both ends up arbitrating between those goals on every design decision, and the arbitration is usually resolved in favor of whichever side spoke loudest in the meeting. The familiar symptoms are recognizable in most mature codebases: an entity class that has grown fields nothing in the domain logic uses because a screen needed them; queries with six joins and a dozen left-outer branches because the normalized model does not match the way anyone actually asks questions; ORM eager and lazy loading configurations tuned for one code path and disastrous for another; and a rising tide of read-only view objects assembled by hand, which is CQRS being invented accidentally and without a name.
Separation comes in levels, and choosing the right level is the whole practical skill. The lightest is two code paths over one database and one schema: commands go through domain objects that enforce invariants, queries bypass them entirely and read straight into flat data transfer objects with hand-written SQL. This costs almost nothing, requires no new infrastructure, keeps everything strongly consistent, and delivers most of the clarity benefit. The next level adds separate read models in the same database, denormalized tables or materialized views updated alongside writes. Above that, the read models move to a different store chosen for its query characteristics, a search engine, a document store, a cache, updated asynchronously, which is where eventual consistency finally enters. The heaviest level combines all of that with event sourcing on the write side.
Getting this right means starting at the lightest level that solves the actual problem. The overwhelming majority of systems that benefit from CQRS benefit from the first level, and never need the others. Teams that begin at the heaviest level, two databases, asynchronous projection, event sourcing, and a broker, because the diagrams in conference talks all look like that, acquire eventual consistency, projection lag, rebuild tooling, and dual-write hazards in exchange for a separation they could have had for the cost of a second set of query methods.
| Level | What is separated | Consistency | Cost |
|---|---|---|---|
| 1. Separate code paths | Command handlers and query handlers over one schema | Strong - one database, one transaction | Almost none; a refactor, not an architecture |
| 2. Separate models, one database | Normalized write tables, denormalized read tables | Strong if updated in the same transaction | Redundant storage and update logic |
| 3. Separate read store | A different database chosen for query shape | Eventual - the read store lags the write store | Sync mechanism, lag handling, monitoring |
| 4. CQRS with event sourcing | Event log on the write side, projections on the read side | Eventual, plus full replay capability | Everything above plus the event-sourcing costs |
Worked Example: The Lightest Useful Separation
This is level one, over a single database, with no broker and no eventual consistency. It is where most systems should start, and it already removes the main pathology: one model trying to serve two purposes.
// --- WRITE SIDE: a rich domain object that exists to protect invariants. ---
// It loads only what a decision needs, and it never returns data to a screen.
class Order {
static async load(tx, id) {
const row = await tx.one('SELECT * FROM orders WHERE id = $1 FOR UPDATE', [id]);
const items = await tx.many('SELECT * FROM order_items WHERE order_id = $1', [id]);
return new Order(row, items);
}
addItem(sku, qty, unitPriceCents) {
if (this.status !== 'draft') throw new DomainError('Order is no longer editable');
if (this.totalCents + qty * unitPriceCents > this.creditLimitCents) {
throw new DomainError('Exceeds approved credit limit'); // the invariant
}
this.items.push({ sku, qty, unitPriceCents });
}
}
async function handleAddItem(cmd) {
return db.transaction(async (tx) => {
const order = await Order.load(tx, cmd.orderId);
order.addItem(cmd.sku, cmd.qty, cmd.unitPriceCents);
await order.save(tx);
});
}
// --- READ SIDE: no domain objects, no ORM, no lazy loading. One query that
// returns exactly the shape the screen renders, and nothing else. ---
async function getOrderSummaryPage(customerId) {
return db.many(`
SELECT o.id,
o.status,
o.placed_at,
c.display_name AS customer_name,
COUNT(i.id) AS item_count,
SUM(i.qty * i.unit_price_cents) AS total_cents,
s.carrier,
s.tracking_number
FROM orders o
JOIN customers c ON c.id = o.customer_id
LEFT JOIN order_items i ON i.order_id = o.id
LEFT JOIN shipments s ON s.order_id = o.id
WHERE o.customer_id = $1
GROUP BY o.id, c.display_name, s.carrier, s.tracking_number
ORDER BY o.placed_at DESC
LIMIT 50`, [customerId]);
}
// Same database. Same transaction guarantees. Strongly consistent. The only
// thing that changed is that one model stopped trying to do two jobs.Real-World Examples
- Greg Young introduced the term CQRS around 2010, building on Bertrand Meyer's command-query separation principle from object-oriented design, and has since spent considerable effort correcting the conflation this lesson warns about, stating publicly that CQRS is not an architecture, does not require event sourcing, and is applicable at the level of a single bounded context rather than a whole system. The frequency with which he has had to repeat that is itself evidence of how thoroughly the pattern got entangled with the technologies commonly shown alongside it.
- Martin Fowler's 2011 article on CQRS makes the same scoping argument from a different angle, warning that the pattern adds significant complexity and should be used only in the specific portions of a system where the read and write models genuinely diverge, and noting that applying it broadly is a common way to make a system harder to work with for no benefit. Both of the pattern's most cited sources therefore agree that the default answer is a single model, and CQRS is the exception you justify.
Review Questions & Answers
Because the two sides optimize in opposite directions and every design decision has to pick one. Normalization protects the write side from inconsistency and forces the read side into expensive joins; denormalization makes reads fast and gives the write side multiple copies of the same fact to keep in step. Indexes that make queries fast slow writes down. A model rich enough to enforce invariants loads more data than a screen needs, and a model flat enough for a screen cannot enforce anything. The compromises accumulate silently until both sides are mediocre and nobody can change either without breaking the other.
They have adopted the infrastructure commonly shown alongside CQRS rather than the pattern itself. The pattern is the separation of the write model from the read model, which can be done entirely within one schema and one transaction. Jumping to a separate store introduces eventual consistency, a synchronization mechanism, lag monitoring, and the dual-write problem, all of which are costs incurred to solve a problem the team has not yet demonstrated they have. The right sequence is to separate the models first, observe where the read workload actually strains the write schema, and then move only those read models.
A growing population of read-only view or data transfer classes assembled by hand, alongside entity classes that have accumulated fields the domain logic never touches, queries written to bypass the ORM for performance, and a naming convention that has quietly split into things that change state and things that fetch shapes for screens. That is the separation emerging under pressure without being acknowledged, which means it happens inconsistently, without a rule about which side owns what, and usually with the domain model still paying the cost of serving reads it no longer serves well.
At level three, when read models move to a separate store updated asynchronously. Levels one and two keep everything in one database and can update read tables inside the same transaction as the write, so a read immediately after a write sees the change and the system behaves exactly as a conventional one. Level three breaks that: the read store lags, the user can write and then read stale data, and the system needs lag monitoring, a strategy for read-your-own-writes, and a plan for what the interface shows during the window. That boundary is worth marking precisely because it is where CQRS stops being a code organization decision and becomes an architectural one with user-visible consequences.