CQRS (Command Query Responsibility Segregation)

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…

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 })
}

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)
  }
}

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:

Three levels of CQRS

  1. Split only the code. One database, but the code that changes (execute) is separate from the code that reads (query).
  2. Split the models, same database. A tidy write table, plus a read table like trackingView updated from events.
  3. 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:

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

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.

What you will learn