Polski

Article · CQRS · Event Sourcing

CQRS: one model for changing, another for reading

Command Query Responsibility Segregation without overdoing it: from Bertrand Meyer's CQS, through three levels of CQRS, to projections and eventual consistency. Commands, queries and projections in C#, TypeScript, Java, Go and Python.

By · · 12 min read

The board in Halina's kitchen shows the queue of tickets: what to make, how many pieces, how many minutes the customer has been waiting. To display it, the system ran a query joining five tables and computed everything on the fly, while the same ORM Order model also handled placing orders, discounts and invoices. Every read optimisation broke the writes and vice versa. CQRS (Command Query Responsibility Segregation) separates these two responsibilities: one model for changing state, another for reading.

1988
the CQS principle – Bertrand Meyer, "Object-Oriented Software Construction"
2009
"Clarified CQRS" – Udi Dahan sorts out the concepts
3
levels of CQRS – from separate handlers to separate data stores

Context and forces

  • Asymmetric load – the kitchen board, order history and menu are read hundreds of times more often than an order is placed.
  • Different data shapes – writes need an aggregate with rules, reads need a flat list ready for display.
  • Complex write rules – the hundred-pierogi limit, statuses and payments shouldn't compete with report performance.
  • Many views of the same data – the kitchen, the customer, Halina in the admin panel and accounting all see an order differently.

From CQS to CQRS

In 1988, Bertrand Meyer formulated the CQS (Command–Query Separation) principle at the method level: a method either changes the state of an object or returns a value – never both. In the late 2000s, Greg Young lifted it to the architectural level: if methods can be separated, so can models. Udi Dahan in Clarified CQRS (2009) and Martin Fowler in a short 2011 post added an important caveat: it's a pattern for selected parts of a system, not for the whole.

Structure

Diagram: CQRS: commands go to the write model, queries to the read model
LevelWhat it meansConsistencyWhen it's enough
1. Separate commands and queriesSeparate request and handler classes, the same database and modelimmediatealmost always – good order in the code
2. Separate read modelsQueries read views or denormalised tables in the same databaseimmediate or eventualwhen screens need joins and aggregations
3. Separate storesRead models in another database (Elasticsearch, Redis, a replica), updated by eventseventuallarge read scale, search, reporting

What it looks like in code

The write side goes through the aggregate, the read side reads a table tailored to the kitchen board – no ORM and no joins:

Command and query

CommandAndQuery.cs
// WRITE SIDE – a command changes state through the domain model and returns (almost) nothing
public sealed record MarkOrderReady(Guid OrderId) : IRequest;

internal sealed class MarkOrderReadyHandler(OrdersDb db, IPublisher events) : IRequestHandler<MarkOrderReady>
{
    public async Task Handle(MarkOrderReady cmd, CancellationToken ct)
    {
        var order = await db.Orders.Include(o => o.Lines).SingleAsync(o => o.Id == cmd.OrderId, ct);
        order.MarkReady();                                    // invariants guarded by the aggregate
        await db.SaveChangesAsync(ct);
        await events.Publish(new OrderReady(order.Id, order.Phone), ct);
    }
}

// READ SIDE – a query never changes state and reads a model shaped for the screen
public sealed record GetKitchenBoard(int Limit = 30) : IRequest<IReadOnlyList<KitchenTicketView>>;
public sealed record KitchenTicketView(Guid OrderId, string Summary, int Pieces, DateTime PlacedAt, int MinutesWaiting);

internal sealed class GetKitchenBoardHandler(IDbConnection sql)
    : IRequestHandler<GetKitchenBoard, IReadOnlyList<KitchenTicketView>>
{
    public async Task<IReadOnlyList<KitchenTicketView>> Handle(GetKitchenBoard q, CancellationToken ct) =>
        (await sql.QueryAsync<KitchenTicketView>(new CommandDefinition("""
            SELECT TOP (@Limit) OrderId, Summary, Pieces, PlacedAt,
                   DATEDIFF(minute, PlacedAt, SYSUTCDATETIME()) AS MinutesWaiting
            FROM read.KitchenBoard           -- a denormalised table, no joins
            ORDER BY PlacedAt
            """, new { q.Limit }, cancellationToken: ct))).AsList();   // Dapper, no ORM tracking
}
kitchen.cqrs.ts
import { CommandHandler, ICommandHandler, IQueryHandler, QueryHandler, EventBus } from "@nestjs/cqrs";

// WRITE SIDE
export class MarkOrderReadyCommand {
  constructor(public readonly orderId: string) {}
}

@CommandHandler(MarkOrderReadyCommand)
export class MarkOrderReadyHandler implements ICommandHandler<MarkOrderReadyCommand> {
  constructor(private readonly orders: OrdersRepository, private readonly events: EventBus) {}

  async execute({ orderId }: MarkOrderReadyCommand): Promise<void> {
    const order = await this.orders.get(orderId);
    order.markReady(); // invariants guarded by the aggregate
    await this.orders.save(order);
    this.events.publish(new OrderReadyEvent(order.id, order.phone));
  }
}

// READ SIDE
export class GetKitchenBoardQuery {
  constructor(public readonly limit = 30) {}
}

@QueryHandler(GetKitchenBoardQuery)
export class GetKitchenBoardHandler implements IQueryHandler<GetKitchenBoardQuery> {
  constructor(private readonly db: Kysely<ReadDb>) {}

  execute({ limit }: GetKitchenBoardQuery): Promise<KitchenTicketView[]> {
    return this.db
      .selectFrom("kitchen_board") // a denormalised table maintained by a projection
      .selectAll()
      .orderBy("placed_at")
      .limit(limit)
      .execute();
  }
}
KitchenCqrs.java
// WRITE SIDE
public record MarkOrderReady(UUID orderId) {}

@Service
class MarkOrderReadyHandler {
    private final OrderRepository orders;
    private final ApplicationEventPublisher events;

    MarkOrderReadyHandler(OrderRepository orders, ApplicationEventPublisher events) {
        this.orders = orders;
        this.events = events;
    }

    @Transactional
    public void handle(MarkOrderReady cmd) {
        var order = orders.findById(cmd.orderId()).orElseThrow();
        order.markReady();                                  // invariants guarded by the aggregate
        events.publishEvent(new OrderReady(order.id(), order.phone()));
    }
}

// READ SIDE
public record KitchenTicketView(UUID orderId, String summary, int pieces, Instant placedAt) {}

@Service
class KitchenBoardQueries {
    private final JdbcClient jdbc;

    KitchenBoardQueries(JdbcClient jdbc) { this.jdbc = jdbc; }

    @Transactional(readOnly = true)
    public List<KitchenTicketView> board(int limit) {
        return jdbc.sql("""
                SELECT order_id, summary, pieces, placed_at
                FROM read_kitchen_board              -- denormalised, no joins
                ORDER BY placed_at LIMIT :limit
                """)
            .param("limit", limit)
            .query(KitchenTicketView.class)
            .list();
    }
}
kitchen/cqrs.go
package kitchen

// WRITE SIDE
type MarkOrderReady struct{ OrderID string }

type MarkOrderReadyHandler struct {
	Orders OrderRepository
	Events EventPublisher
}

func (h MarkOrderReadyHandler) Handle(ctx context.Context, cmd MarkOrderReady) error {
	order, err := h.Orders.Get(ctx, cmd.OrderID)
	if err != nil {
		return err
	}
	if err := order.MarkReady(); err != nil { // invariants guarded by the aggregate
		return err
	}
	if err := h.Orders.Save(ctx, order); err != nil {
		return err
	}
	return h.Events.Publish(ctx, OrderReady{OrderID: order.ID, Phone: order.Phone})
}

// READ SIDE – a separate, read-only path straight to a view table
type KitchenTicketView struct {
	OrderID  string    `json:"orderId"`
	Summary  string    `json:"summary"`
	Pieces   int       `json:"pieces"`
	PlacedAt time.Time `json:"placedAt"`
}

func KitchenBoard(ctx context.Context, db *sql.DB, limit int) ([]KitchenTicketView, error) {
	rows, err := db.QueryContext(ctx,
		`SELECT order_id, summary, pieces, placed_at FROM read_kitchen_board ORDER BY placed_at LIMIT $1`, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []KitchenTicketView
	for rows.Next() {
		var v KitchenTicketView
		if err := rows.Scan(&v.OrderID, &v.Summary, &v.Pieces, &v.PlacedAt); err != nil {
			return nil, err
		}
		out = append(out, v)
	}
	return out, rows.Err()
}
kitchen/cqrs.py
from dataclasses import dataclass

from sqlalchemy import text


# WRITE SIDE
@dataclass(frozen=True)
class MarkOrderReady:
    order_id: str


class MarkOrderReadyHandler:
    def __init__(self, orders: "OrderRepository", events: "EventPublisher"):
        self.orders, self.events = orders, events

    def __call__(self, cmd: MarkOrderReady) -> None:
        order = self.orders.get(cmd.order_id)
        order.mark_ready()  # invariants guarded by the aggregate
        self.orders.save(order)
        self.events.publish(OrderReady(order_id=order.id, phone=order.phone))


# READ SIDE – plain SQL against a denormalised view, returns dicts ready for JSON
def kitchen_board(session, limit: int = 30) -> list[dict]:
    rows = session.execute(
        text("SELECT order_id, summary, pieces, placed_at FROM read_kitchen_board "
             "ORDER BY placed_at LIMIT :limit"),
        {"limit": limit},
    )
    return [dict(r._mapping) for r in rows]

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • CQRS and event sourcing
  • Trade-offs
  • Adoption path
  • In practice
  • Anti-patterns
  • Related topics
  • Test yourself

Create a free account · Sign in