A courier scans KCL-0001 as delivering, and the command (the request to change the status) succeeds. On the next line of code, the tracking page still shows transit. A bug? No. It's a delay CQRS accepts on purpose, and this lesson shows why.
CQRS (Command Query Responsibility Segregation) separates the code that changes data from the code that reads it, down to the data model (the shape the data is stored in). Changes come in as commands to a strict write side. Reads are taken through queries (requests to read data) from a read side whose shape is ready to show. Picture the train timetable board at a station. Staff in the control room record each timetable change in the master book, with rules and signatures. The board on the platform shows a version passengers can read easily, and another staff member updates it a little later. A passenger who looks at the board right after the timetable changed still sees the old one, for a moment. In code, the master book is the write side, the board on the platform is the read side, and the staff member who updates the board is the code that copies changes from the write side to the read side.
The problem: one model for two needs
Kancil Courier's tracking page shows a parcel's status, progress and travel history. It's opened far more often than the status changes: for example dozens of times for every courier scan. With one model, every time the page opens, the server joins the shipments table, the history table and the couriers table again, though the result is the same as the last time the page opened.
The write side needs something else: strict validation. A status may only move by the rules from the State Pattern lesson (transit to delivering, not straight to delivered). One model serving both is never a full fit for either: not for reading, and not for writing. CQRS splits the two.
The write side: commands that validate
This is the write side. shipments keeps the shipment data, ALLOWED holds the valid status moves, and execute runs one command:
const shipments = {
"KCL-0001": { trackingNo: "KCL-0001", status: "transit" },
}
const ALLOWED = { picked_up: ["transit"], transit: ["delivering"], delivering: ["delivered", "transit"], delivered: [] }
const queue = [] // events waiting for the projector
let writeCount = 0
function execute(cmd) {
const s = shipments[cmd.trackingNo]
if (!s) throw new Error("Tracking number not found: " + cmd.trackingNo)
if (!ALLOWED[s.status].includes(cmd.status)) throw new Error("refused " + s.status + " → " + cmd.status)
s.status = cmd.status
writeCount++
queue.push({ type: "StatusChanged", trackingNo: cmd.trackingNo, status: cmd.status })
}
- A command is a request to change something, written as data:
{ type: "ChangeStatus", trackingNo: "KCL-0001", status: "delivering" }. It has the same shape as a command as data in the Command Pattern lesson. executechecks first, then writes. A refused command throws beforeshipments,writeCountorqueuechange.- After writing, the write side puts a
StatusChangedevent in the queue. An event is a record that something has happened. The read side is updated from that event later.
The read side: queries from a ready-made view
This is the read side. PROGRESS holds the progress percent for each status, trackingView keeps data that is ready to show, query reads it, and runProjector updates it from the events in the queue:
const PROGRESS = { picked_up: 25, transit: 50, delivering: 75, delivered: 100 }
const trackingView = {
"KCL-0001": { trackingNo: "KCL-0001", status: "transit", progress: 50, history: ["picked_up", "transit"] },
}
function query(q) {
if (q.type === "TrackParcel") return trackingView[q.trackingNo] // only reads, changes nothing
throw new Error("Unknown query: " + q.type)
}
function runProjector() {
while (queue.length > 0) {
const e = queue.shift()
const row = trackingView[e.trackingNo]
row.status = e.status
row.progress = PROGRESS[e.status]
row.history.push(e.status)
}
}
trackingViewis the read model: one row per tracking number holding everything the tracking page needs. This shape of data is called denormalized: the data is already joined and calculated, so a query only takes one row with no join (combining several tables).- A query only reads. A query that also changes data (for example, adding to a visit counter) breaks the separation.
runProjectorupdates the read model from the queued events, like the staff member who updates the timetable board. In a real app, the projector is a worker running on its own, a Laravel Job reading the queue for example. A result liketrackingViewis often called a projection.
A stale read right after a write
This is one command, then the same query before and after the projector runs. Each query's result is in its comment:
execute({ type: "ChangeStatus", trackingNo: "KCL-0001", status: "delivering" })
console.log(query({ type: "TrackParcel", trackingNo: "KCL-0001" }).status) // transit
runProjector()
console.log(query({ type: "TrackParcel", trackingNo: "KCL-0001" }).status) // delivering
This table shows what each part holds after each step:
| step | write side | queue | read side (tracking page) |
|---|---|---|---|
| start | transit | empty | transit, 50% |
execute(... "delivering") |
delivering | StatusChanged delivering |
transit, 50% |
query(...) |
delivering | StatusChanged delivering |
transit, 50% |
runProjector() |
delivering | empty | delivering, 75% |
query(...) |
delivering | empty | delivering, 75% |
The tracking page shows transit, though the delivering command succeeded. The read side only changes once the projector handles the event. This is called eventual consistency: both sides become the same in the end, but with a delay. Three ways to handle it:
- Show the command's result to whoever wrote it. The courier app, which sent the command, already knows the status is
delivering, so show that status right away without waiting for a query (optimistic UI). - Read from the write side for the writer (read-your-writes): the courier who just scanned reads from
shipments, customers read fromtrackingView. - Wait for the projection before the command counts as done. No stale reads, but commands get slower.
Three levels of CQRS
- Split only the code. One database, but the code that changes (
execute) is separate from the code that reads (query). - Split the models, same database. A tidy write table, plus a read table like
trackingViewupdated from events. - Split the databases. PostgreSQL for writing, for example, and Elasticsearch (a database for searching) or Redis for reading, synced through an event queue.
Start at the lightest level that solves your problem. Levels 2 and 3 bring sync code that has to be maintained, and stale reads when the read side is updated through a queue.
When CQRS is overkill
The term CQRS was popularised by Greg Young around 2010. It comes from Bertrand Meyer's Command Query Separation principle for methods: a method either changes state or returns a value, not both. Martin Fowler, in his article on CQRS, warns that for most systems CQRS adds risky complexity, and that it suits only certain parts of a system. For simple CRUD (an app that only creates, reads, updates and deletes data) with balanced reads and writes and a small team, one model is enough.
Exercise: createUserCQRS
In the exercise, you write a small version for user data. Its read side is updated right away inside the command (level 2 without a queue, so no stale reads). createUserCQRS() returns three methods:
execute(command): takes{ type: "RegisterUser", id, name }or{ type: "UpdateName", id, name }. Ifidornameis empty,throwan error before writing anything. If it's valid, keep the command inwriteStoreand setreadModel[id] = { id, name }.query(q):{ type: "GetUser", id }returnsreadModel[id];{ type: "GetAllNames" }returns an array of names sorted ascending (A to Z) with.sort().writeCount(): the number of commands that succeeded,writeStore.length.
The starter registers Budi and Ani, then renames Budi to Budi S.. The console then shows Budi S., Ani,Budi S., 3, caught invalid (from the command with id: ''), then 3 again, because a refused command isn't counted.
⚠️ Missteps on both sides
- Writing first, checking later. In the exercise, a
writeStore.push(command)placed before validation keeps a refused command too, andwriteCount()comes to 4. - Assuming the read side matches at once. A query right after a command can read stale data. Show the command's result to the writer, or read from the write side for that writer.
- A query that also changes data. The separation is gone, and the read model can't be rebuilt safely from the events.
- CQRS for small CRUD. Two models and syncing, with no matching benefit.
- In the exercise: forgetting
.sort(). An object keeps its keys in the order they were added, so without sort the result isBudi S.,Ani.
TL;DR: CQRS separates commands from queries. A command changes data through execute, which validates first and writes after. A query only reads, from a read model (data already joined and ready to show) like trackingView. The write side puts events (records that something has happened) in a queue, and a projector updates the read side from them. The result is eventual consistency: a query right after the delivering command still shows transit until the projector runs. Handle it by showing the command's result to the writer (who sent the command), by read-your-writes (the writer reads from the write side), or by waiting for the projector to finish. There are three levels: split the code, split the models, and split the databases. Start with the lightest. For simple CRUD (only creating, reading, updating and deleting data) with a small team, CQRS is more than you need. In the exercise, you write a small version for user data: validate before writing, sort the GetAllNames query with .sort(), and a refused command doesn't add to writeCount().
⚡ A write model apart from the read model
Meaning: CQRS separates the write side from the read side, down to the data model (the shape the data is stored in). The write side takes commands (requests to change data) and needs strict validation. The read side answers queries (requests to read data) and needs data already joined and ready to show. One model serving both is never a full fit for either need.
⚡ A command validates first
Write:
function execute(cmd) {
const s = shipments[cmd.trackingNo]
if (!s) throw new Error("Tracking number not found: " + cmd.trackingNo)
if (!ALLOWED[s.status].includes(cmd.status)) throw new Error("refused " + s.status + " → " + cmd.status)
s.status = cmd.status
writeCount++
queue.push({ type: "StatusChanged", trackingNo: cmd.trackingNo, status: cmd.status })
}
Meaning: execute takes one command (cmd) holding a tracking number and the new status. shipments is the write side's data, ALLOWED holds the valid status moves, and writeCount counts the writes that succeeded. A refused command throws before anything changes. After writing, the write side puts an event (a record that the status changed) in the queue. Later the projector, separate code, updates the read model (the read side's data) from that event. A query only reads the read model.
⚡ A stale read for a moment
Write:
execute({ type: "ChangeStatus", trackingNo: "KCL-0001", status: "delivering" })
console.log(query({ type: "TrackParcel", trackingNo: "KCL-0001" }).status)
Guess first: the status of KCL-0001 was transit. The delivering command succeeds, and the query runs on the very next line, before the projector runs. What status gets printed?
transit. The read side only changes once the projector handles the event. This is called eventual consistency: both sides become the same in the end, but with a delay.
Meaning: CQRS has three levels: split the code, split the models, and split the databases. Start at the lightest level. For simple CRUD (creating, reading, updating and deleting data) with a small team, one model is enough.