Beginner System Architecture

CQRS: Command Query Responsibility Segregation

CQRS stands for Command Query Responsibility Segregation. The idea is to split the part of your system that changes data (commands) from the part that reads data (queries). In a traditional design, the same model handles both. CQRS says: use one model to write and a different model to read.

Command vs query

  • A command changes state and returns little or nothing: “CreateOrder”, “CancelOrder”.
  • A query reads state and changes nothing: “GetOrderSummary”.
Write side (commands)        Read side (queries)
  CreateOrder                  GetOrderList
  UpdateAddress                GetOrderDetails
  CancelOrder                  GetDashboard

The shape

Client
  |--- command --> Write Model --> Write DB
  |                                   |
  |                            (sync or events)
  |                                   v
  |--- query   --> Read Model  <-- Read DB (optimized for reads)

The write model enforces rules and stays normalized. The read model can be denormalized and shaped exactly for the screens that need it, so queries are fast.

A simple split

// Command: validates and changes state
function handleCancelOrder(cmd) {
  const order = repo.load(cmd.orderId);
  order.cancel();          // business rules run here
  repo.save(order);
}

// Query: just reads a precomputed view
function getOrderSummary(orderId) {
  return readDb.findSummary(orderId); // no rules, fast
}

Advantages

  • Reads and writes scale independently.
  • Read models are tuned for specific views, so queries are fast.
  • The write side stays focused on rules, the read side on speed.

Disadvantages

  • More code and more moving parts.
  • The read side may lag behind the write side (eventual consistency).
  • Overkill for simple CRUD where one model is enough.

When to use it

CQRS shines when reads and writes have very different loads or shapes, when complex reporting is needed, or when paired with event sourcing. For a basic app with simple data, a single model is simpler and better. Adopt CQRS only when the pain it solves is real.