Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 42 ยท Beyond HTTP

CQRS Basics

Learn CQRS in NestJS with @nestjs/cqrs: commands, queries, events, handlers, sagas, a read model, and an honest look at when the pattern is worth its extra code.

In a typical Nest service, one class does everything with an entity: OrdersService creates orders, updates them, lists them and counts them. That is simple and perfectly fine for most applications. As a system grows, the two sides of that class start to pull in different directions. Writes need strict rules, transactions and validation. Reads need to be fast, flexible and shaped for screens, often joining data from several places.

CQRS (Command Query Responsibility Segregation) is the idea of separating those two sides: commands change state and queries read it, each with its own model and handlers. Nest ships an official module, @nestjs/cqrs, with a command bus, a query bus and an event bus. This lesson explains the vocabulary, shows the Nest code, runs a miniature version of all three buses, and (just as important) tells you when not to use the pattern.

The framework code is read-only because it needs npm. The stand-ins are plain JavaScript implementations of the buses, so you can watch commands, events and a saga run.

The three messages

Command Do something. Changes state. One handler.
Query Ask something. Changes nothing. One handler.
Event Something happened. Many listeners.

Names tell the story. CreateOrder, GetOrder, OrderCreated.

1 / 2

The vocabulary

  • A command is a request to do something: PlaceOrderCommand, CancelOrderCommand. It is named in the imperative, carries the data needed, and has exactly one handler. It may fail (stock is gone), and it normally returns little or nothing beyond an id.
  • A query is a request for information: GetOrderQuery, ListOrdersQuery. It never changes state, so it can be cached, run against a replica, or served from a differently shaped copy of the data.
  • An event is a fact in the past tense: OrderPlacedEvent. It is announced after something happened, and zero or more listeners react (send an email, update statistics, start shipping).
  • A saga is a long-running reaction: it listens to events and issues new commands, for example "when a payment succeeded, issue a ship-order command".

The point is the separation: the code that decides whether an order may be placed is not tangled with the code that renders an order list.

Setting up @nestjs/cqrs

Install @nestjs/cqrs and import CqrsModule in the feature module:

TypeScript
import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';

@Module({
  imports: [CqrsModule],
  controllers: [OrdersController],
  providers: [
    PlaceOrderHandler,
    GetOrderHandler,
    SendConfirmationOnOrderPlaced,
    OrdersSagas,
  ],
})
export class OrdersModule {}

(Newer versions of the package use CqrsModule.forRoot() in the root module; check the guide for your installed version.) Handlers are ordinary providers. The controller no longer calls a service; it sends messages:

TypeScript
@Controller('orders')
export class OrdersController {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly queryBus: QueryBus,
  ) {}

  @Post()
  place(@Body() dto: PlaceOrderDto) {
    return this.commandBus.execute(new PlaceOrderCommand(dto.customerId, dto.items));
  }

  @Get(':id')
  get(@Param('id') id: string) {
    return this.queryBus.execute(new GetOrderQuery(id));
  }
}

Commands and handlers

A command is a small class holding data. A handler declares which command it handles with a decorator and implements execute:

TypeScript
export class PlaceOrderCommand {
  constructor(
    public readonly customerId: string,
    public readonly items: { sku: string; qty: number }[],
  ) {}
}

@CommandHandler(PlaceOrderCommand)
export class PlaceOrderHandler implements ICommandHandler<PlaceOrderCommand> {
  constructor(
    private readonly orders: OrdersRepository,
    private readonly eventBus: EventBus,
  ) {}

  async execute(command: PlaceOrderCommand): Promise<string> {
    const order = Order.place(command.customerId, command.items); // business rules live here
    await this.orders.save(order);
    this.eventBus.publish(new OrderPlacedEvent(order.id, order.customerId, order.total));
    return order.id;
  }
}

The handler validates rules (inside Order.place), persists, and publishes an event. It does not send the email or update the dashboard; those are other people's business. Nest also offers an AggregateRoot base class so an entity can record events (this.apply(new OrderPlacedEvent(...))) and let you publish them with publisher.mergeObjectContext(order).commit().

Queries and the read model

A query handler is the mirror image:

TypeScript
export class GetOrderQuery {
  constructor(public readonly id: string) {}
}

@QueryHandler(GetOrderQuery)
export class GetOrderHandler implements IQueryHandler<GetOrderQuery> {
  constructor(private readonly db: DataSource) {}

  async execute(query: GetOrderQuery): Promise<OrderSummaryDto> {
    return this.db.query('SELECT id, customer_name, total, status FROM order_summaries WHERE id = $1', [query.id]);
  }
}

Here the handler reads from a table or view (order_summaries) built for the screen, not from the write entities. That is the read model: a copy of the data shaped for questions. Event handlers keep it up to date. You can start without a separate table (the query handler just reads the same database), and split later only if reads and writes need to scale or evolve independently.

Events and sagas

Event handlers react to what happened:

TypeScript
@EventsHandler(OrderPlacedEvent)
export class SendConfirmationOnOrderPlaced implements IEventHandler<OrderPlacedEvent> {
  constructor(private readonly mailer: MailService) {}

  async handle(event: OrderPlacedEvent) {
    await this.mailer.sendOrderConfirmation(event.customerId, event.orderId);
  }
}

Several handlers can listen to the same event, and adding a new reaction means adding a new class, not editing PlaceOrderHandler. A saga is an RxJS stream of events that returns commands:

TypeScript
@Injectable()
export class OrdersSagas {
  @Saga()
  paymentThenShip = (events$: Observable<any>): Observable<ICommand> =>
    events$.pipe(
      ofType(PaymentSucceededEvent),
      map((event) => new ShipOrderCommand(event.orderId)),
    );
}

Sagas model workflows that cross several steps: place an order, take payment, reserve stock, ship. If a step fails, the saga issues compensating commands (refund, release stock). That is powerful, and it is also where complexity grows quickly.

Stand-in: command, query and event buses

Here is a miniature of the three buses. A CommandBus maps each command class to its single handler, a QueryBus does the same for queries, and an EventBus fans out to many listeners. The handlers use a plain array as the write store and a separate map as the read model, updated by an event handler. This is not @nestjs/cqrs itself, only the mechanism.

Node.js Three buses and a read model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The command handler never touches the e-mail or the read model; adding a third reaction means registering one more event handler. The failed command published no event, so nothing downstream changed.

Stand-in: a saga as an event-to-command rule

A saga turns events into commands. This stand-in keeps a list of such rules and runs a small workflow (order, then payment, then shipping), including a failed payment that triggers a compensating command. It uses plain async functions where Nest uses RxJS operators.

Node.js A saga with a compensating command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the second line: the saga did not ship, it issued ReleaseStock. Real sagas must also survive restarts and duplicate events, so production systems persist saga state and make handlers idempotent; the queues lesson covers the same concerns.

When to use CQRS (and when not to)

CQRS is a tool for a specific kind of pain, not a default architecture.

  • Good fits: reads and writes with very different shapes or scale; complex write rules; many independent reactions to the same change; auditing; teams working on different parts of the same domain.
  • Poor fits: simple CRUD screens, small teams, early prototypes. There you pay for extra files (a command, a handler, an event and a query for every action) and gain little.
  • Costs to expect: more classes and indirection, harder debugging (you jump through buses), and eventual consistency if the read model is updated by events: a query right after a command may not see the change yet.

A sensible path: start with ordinary services. If one service grows unmanageable, introduce commands and queries for that area only. Add a separate read store or event sourcing (saving events as the source of truth) only when you can name the problem it solves.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about commands and queries is correct?

    The split is the heart of CQRS: commands (writes) and queries (reads) are separate messages with separate handlers.
  2. 2. How many handlers does a command normally have in @nestjs/cqrs, and how about an event?

    A command is addressed to a single handler that decides the outcome. An event is a fact that any number of listeners may react to.
  3. 3. What does a saga do?

    A saga maps events to commands, such as shipping after payment succeeds or refunding after a failure.
  4. 4. Which is a downside to expect when the read model is updated by events?

    The read model is updated after the event is handled, so there can be a short delay.
  5. 5. Which project is least likely to benefit from CQRS?

    Simple CRUD gains little from extra classes and indirection. Use ordinary services until a real problem appears.

Summary

  • CQRS separates commands (change state) from queries (read state), each with its own handlers and often its own model.
  • @nestjs/cqrs provides CommandBus, QueryBus and EventBus; handlers are providers marked with @CommandHandler, @QueryHandler and @EventsHandler.
  • A command has one handler, publishes events, and returns little; events fan out to many independent listeners.
  • Sagas turn events into commands to coordinate workflows, including compensations when a step fails.
  • A read model shaped for screens speeds up queries but introduces eventual consistency.
  • Use CQRS only when the complexity it removes is bigger than the files it adds; start with plain services.

Next, serve HTML pages and static files from Nest in Server-Side Views and Static Files.