Say your order dashboard gets slow every day after lunch. Support opens it, finance opens it, the warehouse opens it. Behind it sits one Order model doing two jobs: guarding every rule about how an order may change, and answering a wide query that joins customers, payments, discounts, shipments and support tickets. Nobody planned it that way. The model that was built to change orders safely also became the easiest place to read them from, and now it's not great at either.
CQRS (Command Query Responsibility Segregation) is a name for pulling those two jobs apart. The name is a mouthful, the core idea is small, and the useful part is knowing how far to take it. This post covers where the idea comes from, what each side looks like in code, the levels you can adopt it at, and when to leave it alone.
Where the idea comes from
It starts with Bertrand Meyer's command-query separation (CQS) from Object-Oriented Software Construction: a method either changes state (a command) or returns a result without changing observable state (a query), not both (Martin Fowler on CommandQuerySeparation). Greg Young took it a level up. In his CQRS Documents he explains that people first treated CQRS as "CQS at a higher level" until it was recognized as its own pattern: where you had one object handling both, you now have two, one for commands and one for queries. He adds that the split isn't very interesting by itself and gets interesting once you look at it as architecture.
Martin Fowler's CQRS article (2011), where he says he first heard the pattern described by Greg Young, is still the best short read on it, mostly because of its warning: for most systems, CQRS adds risky complexity.
Commands guard the rules, queries serve the screen
A command asks the system to do something: approve a refund, cancel a subscription, book a room. A query asks what's true right now: list pending refunds, show the order summary. Each side has a different job, so each can take a different shape.
The command side protects the business. It cares about validation, invariants, permissions, idempotency and transactions. Name commands after what the user means. Microsoft's CQRS pattern guide uses a hotel example: "Book hotel room" rather than "Set ReservationStatus to Reserved." The first tells you the intent, and the rules hang off it naturally.
The query side serves a screen. It can be denormalized, precomputed and shaped exactly like the page that uses it. The same guide describes queries as returning plain data objects with no domain logic, and never changing data. Here's the split in TypeScript, with the persistence calls left abstract:
// Command: named after intent, changes state, returns nothing
type ApproveRefund = { refundId: string; approvedBy: string }
async function approveRefund(cmd: ApproveRefund): Promise<void> {
const refund = await refunds.load(cmd.refundId)
if (refund.status !== 'requested') {
throw new Error('Refund is not waiting for approval')
}
refund.approve(cmd.approvedBy)
await refunds.save(refund)
}
// Query: shaped for one screen, never changes state
type PendingRefundRow = { id: string; customerName: string; amount: number }
async function listPendingRefunds(): Promise<PendingRefundRow[]> {
return db.many(
`SELECT r.id, c.name AS "customerName", r.amount
FROM refunds r JOIN customers c ON c.id = r.customer_id
WHERE r.status = 'requested'`
)
}
That's already CQRS in its smallest form: same codebase, same database, two clearly separate paths. The command doesn't return a report, and the query doesn't sneak in a data fix on the way out.
How far to take it
CQRS isn't one switch. It's more like a dial, and most teams should stop well before the end.
| Level | What changes | What it costs |
|---|---|---|
| 1. Separate handlers | Command and query code live in different functions or modules. Same model, same database. | Almost nothing. Mostly naming and discipline. |
| 2. Separate read models, same database | Queries read from views or tables shaped for screens. | Someone has to keep those shapes fresh. |
| 3. Separate read store | The write side publishes events; a projector updates a different store (a document database, a search index). | Eventual consistency, messaging failures, rebuild tooling. |
| 4. With event sourcing | The event log is the write model; every read model is a projection of it. | A different way of modeling the whole domain. |
Level 2 is often the sweet spot. In PostgreSQL, a materialized view gives you a read model with no extra infrastructure:
-- A read model for the order dashboard (one shipment per order here)
CREATE MATERIALIZED VIEW order_summary AS
SELECT o.id, c.name AS customer_name, o.total, o.payment_status, s.eta
FROM orders o
JOIN customers c ON c.id = o.customer_id
LEFT JOIN shipments s ON s.order_id = o.id;
-- Required for CONCURRENTLY, which lets readers keep reading during a refresh
CREATE UNIQUE INDEX order_summary_id_idx ON order_summary (id);
REFRESH MATERIALIZED VIEW CONCURRENTLY order_summary;
Per the PostgreSQL docs, a plain refresh can block readers, while CONCURRENTLY doesn't, as long as there's a unique index on plain columns covering all rows. You decide how often to refresh, and that interval is exactly how stale the dashboard is allowed to be.
Level 3 is where the real bill arrives. Azure's guide points out that you usually can't put the database write and the message publish in one distributed transaction, so it recommends a transactional outbox plus an idempotent consumer that tolerates duplicates. If you're heading there, read The Outbox Pattern first. Level 4 is a separate decision with its own trade-offs, covered in Event Sourcing for Beginners. CQRS doesn't require it.
What you pay once the read side moves out
A separate read model has to be kept up to date, and that's a job with failure modes. Events can arrive late, twice or not at all if the pipeline is weak. The screen may show an old status for a moment. The team needs answers to some plain questions: where does the truth live, how do we rebuild a read model from scratch, how do we measure how far behind it is, and who gets paged when the projector stops?
Freshness is also a product question. Some screens can live with a status that's a second old, like an analytics dashboard. Some can't, like the confirmation page right after checkout. For screens like that, one option is to show the user what their own command just did (the values they submitted, or the version number the write produced) instead of reading it back through the projector. Talk this through with product and support before you build, because they'll get the tickets. For the user-facing side of this, Eventual Consistency Is a Promise About Time goes deeper.
When it's worth it, and when it isn't
Fowler's advice is to use CQRS only on specific parts of a system, the bounded contexts that need it, and to treat most of the system as plain CRUD if that's what it is. Azure's guide lists the same "not suitable" cases: simple domains and simple CRUD screens.
| Good fit | Probably not |
|---|---|
| Reads vastly outnumber writes and need their own tuning | A CRUD admin screen with one table and modest traffic |
| Strict write rules, broad reporting (finance, inventory) | Nobody can name a read pain or a write pain |
| A support console that combines data owned by several services | The only reason is that it sounds senior |
| Task-based UIs where each action maps to a business command | A small team without anyone to run projectors and rebuilds |
Udi Dahan's Clarified CQRS makes a point worth keeping: queries can read from a separate store that's allowed to be a bit out of sync, because the data on a user's screen is stale anyway by the time they act on it. The server still validates every command that arrives, so the rules hold even when the view was old.
A small way to start
- Split command functions from query functions in the module that hurts most. No new infrastructure.
- Rename commands after intent:
ApproveRefund,CancelSubscription, notupdateStatus. - Pick one slow screen and give it a read model, a view or materialized view in the same database.
- Measure how stale it gets and how long a full rebuild takes. Put both on a dashboard.
- Only when one database can't serve both sides, move the read model to its own store, with an outbox in front.
Try this week
- Find one function in your codebase that both changes data and returns a big report. Split it in two.
- List your three slowest screens and check whether they read straight from write-side tables.
- For one screen, write down how stale its data may be. Ask product if they agree.
- If you already run projectors, try a full rebuild in staging and time it.
CQRS works best as a small, honest split: commands about intent and rules, queries about showing people what they need. Keep the two together while they're small, and separate them on purpose when they start pulling against each other. For the bigger picture of data spread across services, see Who Owns the Data?.