# CQRS

**Also known as:** Command Query Responsibility Segregation  
**Category:** Architectural Patterns (Across services)  
**Complexity:** 4/5  
**Guide:** https://layra4.dev/architectures/architectural/cqrs

*Reads and writes are different jobs, so give them different models.*

Most apps use one model for both jobs. The objects that enforce business rules on write are also joined and flattened to answer queries. CQRS (Command Query Responsibility Segregation) splits the two: a write model that protects the rules, and read models shaped for the screens that ask.

The read side is updated from the write side, often by events. When that update is asynchronous, reads lag writes by milliseconds, or seconds under load. That lag is the main cost, and the UI must be designed for it.

> **In one sentence.** Use one model to change state and enforce the rules, and separate read models, each shaped for one screen, to answer queries.

## Origin (≈2010)

Named by Greg Young. It scales up Bertrand Meyer’s Command–Query Separation (a method either changes state or returns data, never both) from one method to whole models and stores.

## The two sides

### Commands and the write model

A command is an intent to change state, such as PlaceOrder. The write model handles it: it loads one aggregate (a group of objects saved together), checks the rules and saves. It returns an acknowledgement, not data.

- Named in the imperative
- The only place business rules live
- Built for correctness, not for queries

### Queries and read models

A query asks for data and never changes state. It reads a read model: a table, view or document shaped for one screen. No joins across aggregates and no domain objects are needed.

- Free of side effects
- One shape per screen or use case
- Can live in another store, such as Redis or Elasticsearch

### Projections

A projection is the code that keeps a read model up to date. It handles each change from the write side, in the same transaction or later from an event. Read models can be deleted and rebuilt from events.

- Synchronous (same transaction) or asynchronous (events)
- Idempotent, because an event can arrive twice
- Rebuildable from the source of truth

> OrderPlaced → insert a row into orders_summary, which the UI reads

### Read lag (eventual consistency)

With asynchronous projections, the read side is behind the write side. A user can save a change and then not see it on the next screen. This is a design decision with UX consequences, not a bug.

- Measure the lag as a metric
- Show the user's own change optimistically
- Or read the user's own write from the write model

## Design rules

### Start with one database, not two

CQRS is a split in the code first. Command and query handlers over one Postgres database already give each side its own shape. Add a separate read store only when read load or query shape needs it.

### Design the UI for read lag

With asynchronous projections, a user can save and not see the change. Show it optimistically, or read the user's own write from the write model. Never assume a write is visible everywhere at once.

### Make projections idempotent and rebuildable

Events can arrive twice. A projection that upserts by ID and stores the last event position can replay from zero. That is how you fix a projection bug or add a new read model.

### Use it where reads and writes truly differ

An order history read 100 times per write, or a dashboard joining five tables, earns CQRS. A settings page with plain CRUD does not. Apply it per module, not to the whole system.

## Diagrams

Rendered as geometry on the guide page; not reproducible as text.

- `cqrs-split` — see https://layra4.dev/architectures/architectural/cqrs
- `cqrs-levels` — see https://layra4.dev/architectures/architectural/cqrs

## Write and read paths, split apart

```
src/catalog/
commands/                       # the write side: validate, change, emit
  add-product.ts                # loads the aggregate, enforces rules
  command-handler.ts            # one handler per command
domain/                         # rich model, used only by writes
  product.ts
queries/                        # the read side: shape data for the screen
  product-list.ts               # selects a view, returns a DTO
  query-handler.ts              # no domain model, just data → DTO
read-model/                     # projections the queries read from
  product-view.sql
```

Writes go through the domain and its rules. Reads skip it and select straight into a DTO. Later, each side can get its own store.

## Examples

### Separate command and query paths

```typescript
// WRITE — go through the aggregate, enforce the rules
export const cancelOrder = (orders: OrderRepository) =>
  async (cmd: CancelOrder) => {
    const order = await orders.ofId(cmd.id);
    if (!order) throw new NotFound("order", cmd.id);
    order.cancel(cmd.reason);   // invariant: can't cancel a shipped order
    await orders.save(order);
  };

// READ — skip the domain model entirely, hit the projection
export const listOpenOrders = (db: ReadDb) =>
  (q: ListOpenOrders): Promise<OrderRow[]> =>
    db.query(
      "select id, customer, total, placed_at from orders_summary where status = 'open'",
    );
```

The command path loads an aggregate, checks the rule and saves. The query path never touches the aggregate. It reads a table shaped for the screen.

## When to use

- Reads outnumber writes by 10x or more and need to scale on their own
- Screens need shapes the write model can only serve with heavy joins
- You use event sourcing and need a way to query the events

## When not to use

- Simple CRUD, where one model serves reads and writes well
- The UI cannot accept even a second of stale reads
- A small team that cannot run projections and their rebuilds

## Benefits

- Each side is tuned for its job: correctness on writes, speed on reads
- Reads scale out on their own, with replicas or a separate store
- Queries become simple selects against tables shaped for the screen

## Costs

- More moving parts: two models, projections and the sync between them
- Read lag that the whole team, and the UI, must handle
- Projection rebuilds and event versioning become ongoing work

## Pitfalls

- Applying CQRS to plain CRUD. Every feature now needs a command, an event and a projection, but no screen got faster.
- Assuming CQRS needs two databases. The team adds Kafka and a second store before a single query is slow.
- Ignoring read lag in the UI. Users save, see the old value, and save again, which creates duplicates.
- Treating CQRS and event sourcing as one decision. They are independent, and each works without the other.

## Similar patterns, compared

CQRS is confused with two neighbours. CQS shares its name and core idea, but works on one method. Event sourcing usually arrives with CQRS, but it is a separate decision about how writes are stored.

### CQRS vs Command–Query Separation

CQRS is Meyer's CQS scaled up: the same command-versus-query split, moved from one method to whole models and datastores. — [Command–Query Separation](https://layra4.dev/architectures/tactical/command-query-separation)

**What is genuinely the same**

- Both separate operations that change state from operations that return data
- Both make reads safe to reason about, with no hidden writes inside a query
- Greg Young named CQRS after CQS and generalised it directly from Meyer's principle

**What actually differs**

- CQS is a rule about one method's signature; CQRS is a split between two models
- CQS costs nothing; CQRS adds projections, sync and often eventual consistency
- You follow CQS everywhere by default; you use CQRS only where reads and writes truly differ

**Pick CQRS when:** Reads and writes have truly different shapes or scale, and you will pay for two models to serve each well.

### CQRS vs Event Sourcing

Often used together, but independent. CQRS splits reads from writes; event sourcing decides how the write side stores its state. — [Event Sourcing](https://layra4.dev/architectures/architectural/event-sourcing)

**What is genuinely the same**

- People say “CQRS/ES” as if it were one pattern
- Both build read models with projections
- Both usually mean reads that lag a little behind writes

**What actually differs**

- CQRS works over plain tables; it needs no events at all
- Event sourcing stores events instead of rows; CQRS says nothing about storage
- Event sourcing almost always needs CQRS to answer queries; CQRS rarely needs event sourcing

**Pick CQRS when:** You need read models shaped for screens, and current state in normal tables is enough.

## Related patterns

- [Command–Query Separation](https://layra4.dev/architectures/tactical/command-query-separation) — the method-level rule CQRS scales up
- [Event Sourcing](https://layra4.dev/architectures/architectural/event-sourcing) — a write side that stores every change as an event
- [Outbox](https://layra4.dev/architectures/infrastructure/outbox) — publishes the events that update read models, reliably
- [Database Replication](https://layra4.dev/architectures/data-storage/database-replication) — read replicas: the simplest way to scale reads first
- [Consistency Models](https://layra4.dev/architectures/key-design-principles/consistency-models) — read-your-writes and the other guarantees behind read lag

## Further reading

- *CQRS Documents* — Greg Young — The foundational write-up of the pattern.
- *CQRS (bliki)* — Martin Fowler — A short, careful definition and its warnings.
- *Implementing Domain-Driven Design, ch. 4* — Vaughn Vernon (2013) — CQRS inside a DDD architecture.
