Typorithm · medium

CQRS

cqrsarchitecturecommandsqueriesread-model
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn CQRS

0%

Scale & Decoupling

CQRS splits writes from reads: commands mutate state through one model, queries return data through a separate read-optimized model. The two sides can use different stores and scale independently.

A command expresses an intent to change state — PlaceOrder — and its handler writes without returning data. A query expresses a request for data — GetOrder — and its handler reads without mutating anything.

Each side can have its own model and store: the write store optimized for consistency, the read view denormalized and shaped for fast lookups.

CQRS pays off when reads and writes have very different shapes or load: read-heavy systems, or where the two sides need to scale on separate hardware.

01

Commands mutate; queries return data — never both.

02

Write side and read side use separate models.

03

Each side can scale independently.

function handlePlaceOrder(cmd) {
  writeStore.append(new OrderPlaced(cmd))
}

function handleGetOrder(query) {
  return readView.findById(query.orderId)
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Command handler

A command handler accepts an intent to change state; it does not return data.

function handlePlaceOrder(cmd)

2. Write side

The write side mutates the system of record, here by appending an event.

writeStore.append(new OrderPlaced(cmd))

3. Query handler

A query handler returns data and never mutates state.

function handleGetOrder(query)

4. Read side

The read side serves from a read-optimized view, separate from the write store.

readView.findById(query.orderId)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

CQRS: Lesson & Practice · Typorithm | ApplyDjinn