CQRS (Command Query Responsibility Segregation) splits one model into two: a write model that accepts commands and enforces the business rules, and one or more read models shaped for the questions the app asks. A projector copies each change from the write side into the read models, so reads and writes can scale, store and evolve separately. The price is a short delay between a write and the moment every read model reflects it.
Think of it like
The kitchen and the menu board
Orders go to the kitchen, which checks stock and cooks. The menu board out front is updated from the kitchen's changes, so customers read it without interrupting the cooks, and for a minute after the last portion sells it may still say the dish is available.
At a glance
- Intent
- Handle state changes (commands) and data reads (queries) with separate models, each designed for its own job.
- Problem
- One model serving both sides fits neither: normalized tables that keep writes correct need joins and heavy indexes for every screen, and read traffic competes with writes on the same database.
- Solution
- Commands go to a write model that validates and commits. Each committed change is published, and a projector updates denormalized read models that queries hit directly.
- Trade-off
- More moving parts and eventual consistency: a read right after a write can return the old answer until the projector catches up.
How it works
- 1
A command reaches the write model
The handler loads the current state, checks the rules and commits, or refuses. In the visualizer, the Command row sends
DepositandWithdrawfor accountacc-42; a withdrawal larger than the balance is refused and nothing changes. - 2
The change is published
The committed change becomes an event. The visualizer's write side happens to be event-sourced, so the event is appended to the event store; with an ordinary database you would publish it through an outbox or change data capture instead.
- 3
A projector updates each read model
It runs asynchronously and keeps its own checkpoint per view. Here there are two read models built from the same events: a balance view and a statement view. Set Projector lag to 1 to 3 events, or pick the scenario Read-your-writes gap, to see the views fall behind the log.
- 4
Queries read only the views
They never touch the write side. In the Query row, Read view returns whatever the view holds now (possibly stale), Wait for vN sends the version the last command returned and waits until the view reaches it, and Use command reply shows the state the command returned without querying.
- 5
Read models are disposable
A view can be dropped and rebuilt from the source of truth. The scenario Fix a projection bug, rebuild shows a balance view that ignored withdrawals being repaired with Fix bug + rebuild view, which replays the log into a fresh view.
type Withdraw = { accountId: string; amount: number };
type Withdrawn = Withdraw & { version: number };
// Write side: check the rule, commit state + outbox row together.
async function handleWithdraw(cmd: Withdraw) {
return db.transaction(async (tx) => {
const acc = await tx.accounts.load(cmd.accountId);
if (acc.balance < cmd.amount) throw new Error("Insufficient funds");
const version = await tx.accounts.debit(acc, cmd.amount);
await tx.outbox.add({ type: "MoneyWithdrawn", ...cmd, version });
return { version }; // no view data
});
}
// Projector: shapes the event for one screen.
async function onWithdrawn(e: Withdrawn) {
await statementView.append(e.accountId, -e.amount, e.version);
}
// Read side: one lookup, no rules, no joins.
const getStatement = (id: string) => statementView.find(id);When to use it, and when not to
Use it when
- Reads far outnumber writes, or need a different store (search, analytics, a cache) than the write side
- Several screens want the same data in very different shapes
- The write side has rich rules that a read-optimized schema would get in the way of
- You already publish events, so feeding read models is cheap
Avoid it when
- The domain is simple CRUD: one model and a few indexes are enough
- Users must see their own writes instantly everywhere and you cannot afford the mitigations
- The team cannot operate the projector, its lag and its rebuilds
- You assume it requires event sourcing: it does not, and a plain database plus outbox or CDC works
In practice
- Search indexes as read models: a relational database is the write side, and a CDC tool such as Debezium streams its changes through Kafka into Elasticsearch or OpenSearch for queries.
- Database materialized views: PostgreSQL's
CREATE MATERIALIZED VIEWwithREFRESH MATERIALIZED VIEWis a small, same-database read model. - Axon Framework: a Java framework with separate command, event and query buses, built around CQRS and event sourcing.
- EventStoreDB: an event store whose subscriptions feed projections that build read models.
- Read replicas are a lighter relative: they scale reads, but serve the same schema, so they split the load without splitting the model.
Related patterns
| Pattern | How it relates |
|---|---|
| Event Sourcing | A common write side for CQRS: the event log is the truth, and projections are the only way to query it efficiently. |
| Materialized View & Denormalization | A read model is a materialized view kept up to date from the write side's changes. |
| Transactional Outbox | Makes sure every committed write publishes its event, so read models never silently miss a change. |
| Database Replication | Read replicas also separate reads from writes, but copy the same schema instead of building new shapes. |
Key takeaways
- CQRS separates a write model that enforces rules from read models shaped for queries.
- A projector keeps read models up to date asynchronously, so they are eventually consistent with the write side.
- CQRS does not require event sourcing; an ordinary database plus an outbox or CDC can feed the read models.
- Read models are disposable: they can be dropped and rebuilt from the source of truth.
Common pitfalls
- Ignoring the read-your-writes gap, so a user saves a form and the next page shows the old value.
- Publishing changes with a dual write instead of an outbox or CDC, so a crash leaves a read model permanently missing an update.
- Applying CQRS to a whole system instead of the few areas where reads and writes really differ.
Interview tips
- When you propose CQRS, name how changes reach the read side (outbox or CDC) and how you handle read-your-writes, for example by returning the new version from the command and waiting for it on the query.
Test yourself
What does CQRS separate?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.