What is the NestJS CQRS module and what does it actually provide?

@nestjs/cqrs is a small library that gives a NestJS application three in-process dispatchers and a set of decorators for wiring handlers to them. You import CqrsModule into your application, and Nest's dependency injection discovers classes marked with @CommandHandler, @QueryHandler, @EventsHandler and @Saga, then registers each one with the matching bus:

  • CommandBus routes a command object to exactly one handler and returns whatever that handler returns.
  • QueryBus does the same for queries, with one handler per query type.
  • EventBus delivers a published event to zero or more event handlers and to sagas, which are RxJS streams that can map events to new commands.

All of this runs in memory, inside the same Node.js process that received the HTTP request. The module is not a message broker and not an event store. It does not imply event sourcing, and it does not require a separate read database. Queries usually hit the same tables the commands write to.

HTTP ─▶ Controller ─┬─▶ CommandBus ─▶ CommandHandler ─▶ Repository + transaction ─▶ COMMIT
                    │                                                                 │
                    │                                                                 ▼
                    │                                                EventBus ─▶ EventHandlers / Sagas
                    │
                    └─▶ QueryBus ───▶ QueryHandler ───▶ same database (read)

Running more instances does not distribute events. Each instance publishes only to its own handlers, and an event is lost if its process dies before the handler runs.

Teams adopt the module because it makes write, read and side-effect paths explicit and individually testable. It pays off for backend teams with non-trivial business logic in a single NestJS service. It adds little for thin CRUD.

+------------ Node.js process (one instance, in-memory buses) -------------+
|      HTTP                                                                |
|        v                                                                 |
| +--------------+     +----------------+                                  |
| |  Controller  |---->|   CommandBus   |                                  |
| +--------------+     +----------------+                                  |
|        | query               v                                           |
|        v             +----------------+                                  |
| +--------------+     | CommandHandler |                                  |
| |   QueryBus   |     +----------------+                                  |
| +--------------+             v                                           |
|        v             +----------------+        +------------------+      |
| +--------------+     | Repository+tx  |-COMMIT>|     EventBus     |      |
| | QueryHandler |     +----------------+        +------------------+      |
| +--------------+             |                    |           |          |
|        |                     |                    v           v          |
|        |                     |                 +--------+ +-------+      |
|        |                     |                 | Event  | | Sagas |      |
|        |                     |                 |handlers| +-------+      |
|        |                     |                 +--------+     |          |
|        |                     |                   new commands->CommandBus|
+--------|---------------------|-------------------------------------------+
         v read                v write
   +------------------------------------+
   |  same database (one set of tables) |
   +------------------------------------+
  Instance B runs its own buses; events are never shared across processes.
  An event is lost if this process dies before its handlers run.

Request flow through @nestjs/cqrs inside a single Node.js process: commands and queries are dispatched in memory to handlers that use the same database, and events are published to local event handlers and sagas only after the transaction commits.

How do you implement commands and queries with the command bus?

Start with the write side. A command is a plain class whose constructor holds the intent and nothing else, for example a CreateOrderCommand with a customer ID and line items. It carries no behaviour, so you can construct it in a controller, a test or a scheduled job without pulling in dependencies.

The handler is a class decorated with @CommandHandler(CreateOrderCommand) that implements ICommandHandler<CreateOrderCommand>. Its execute method holds the business logic and receives repositories through normal constructor injection. Register the handler in the providers array of the feature module that imports CqrsModule. A handler that is not listed there is never discovered, and the bus throws at dispatch time rather than at startup. In the controller, inject CommandBus and call commandBus.execute(new CreateOrderCommand(...)).

Queries follow the same pattern with @QueryHandler and IQueryHandler, dispatched through QueryBus. Read from the same database with a thin repository method or a query builder that selects only the columns the response needs. Keep query handlers free of side effects such as writes, event publishing or cache mutation. That guarantee is the reason to separate reads from writes at all. A separate read model is not required at this stage.

Typing needs deliberate attention. By default, execute resolves to a loosely typed result, so any or unknown leaks into controllers and erases the contract. You can state the result type when you call the bus by supplying the command and result types as generics. Some versions of the package also let a command or query class declare its result type through a generic base class. Check what your installed version offers, and choose one convention for the codebase.

// orders.cqrs.ts: write and read paths through the buses, with explicit result types
import { Body, Controller, Get, Injectable, Module, Param, Post } from '@nestjs/common';
import { CommandBus, CommandHandler, CqrsModule, ICommandHandler, IQueryHandler, QueryBus, QueryHandler } from '@nestjs/cqrs';

export interface OrderSummary { id: string; status: string; total: number }

// Thin data access. Replace with your ORM repository or query builder.
@Injectable() export class OrdersRepo {
  async insert(customerId: string, items: { sku: string; qty: number }[]): Promise<string> { return 'ord_123'; }
  async findSummary(id: string): Promise<OrderSummary | null> { return null; } // SELECT id, status, total only
}

// Commands and queries carry intent only, with no dependencies.
export class CreateOrderCommand { constructor(readonly customerId: string, readonly items: { sku: string; qty: number }[]) {} }
export class GetOrderQuery { constructor(readonly orderId: string) {} }

@CommandHandler(CreateOrderCommand)
export class CreateOrderHandler implements ICommandHandler<CreateOrderCommand> {
  constructor(private readonly repo: OrdersRepo) {}
  execute(cmd: CreateOrderCommand): Promise<string> { return this.repo.insert(cmd.customerId, cmd.items); }
}

@QueryHandler(GetOrderQuery)
export class GetOrderHandler implements IQueryHandler<GetOrderQuery> {
  constructor(private readonly repo: OrdersRepo) {}
  // Read only: no writes, no events, no cache mutation.
  execute(q: GetOrderQuery): Promise<OrderSummary | null> { return this.repo.findSummary(q.orderId); }
}

@Controller('orders')
export class OrdersController {
  constructor(private readonly commandBus: CommandBus, private readonly queryBus: QueryBus) {}
  // Without the second generic, the result is any and the contract is lost.
  @Post() async create(@Body() body: { customerId: string; items: { sku: string; qty: number }[] }): Promise<{ id: string }> {
    const id = await this.commandBus.execute<CreateOrderCommand, string>(new CreateOrderCommand(body.customerId, body.items));
    return { id };
  }
  @Get(':id') get(@Param('id') id: string): Promise<OrderSummary | null> {
    return this.queryBus.execute<GetOrderQuery, OrderSummary | null>(new GetOrderQuery(id));
  }
}

// Handlers missing from providers are never discovered, and dispatch fails at runtime.
@Module({ imports: [CqrsModule], controllers: [OrdersController], providers: [OrdersRepo, CreateOrderHandler, GetOrderHandler] })
export class OrdersModule {}

A minimal NestJS feature module that defines a command, a side-effect-free query and their handlers, registers the handlers as providers, and dispatches both from a controller with explicit result-type generics so the controller receives typed values instead of any.

How do event handlers work, and what happens when they fail?

The simplest way to emit a domain event is to inject EventBus into the command handler and call EventBus.publish() with an event instance after the work succeeds. Any class decorated with @EventsHandler(SomeEvent) and implementing handle() receives it. The command handler stays a plain service, and your ORM entities stay as they are.

The alternative is to have an entity extend AggregateRoot. Its methods call apply() to record events. The handler wraps the entity with EventPublisher.mergeObjectContext() and calls commit() after saving, which dispatches the recorded events. This pushes you toward a rich domain model where entities own behaviour. If your entities are anemic ORM classes with public fields and no logic, bolting AggregateRoot onto them adds ceremony without the benefit, and plain EventBus is enough.

Either way, the command does not await event handlers. That has four consequences:

  • Response timing: the HTTP response can return before handlers run, so a client that immediately reads data a handler writes may not see it yet.
  • Errors stay out of the request: an exception in a handler never reaches the original caller.
  • Silent failures: unless each handler catches, logs and reports its own errors, failures can go unnoticed. How the package surfaces unhandled handler errors varies between versions, so don't rely on it.
  • Lost events: if the process crashes after commit() or publish() but before handlers finish, nothing in memory persists and nothing retries.

Treat event handlers as best-effort side effects. Anything the operation must guarantee belongs in the command handler.

import { Logger } from '@nestjs/common';
import { CommandHandler, ICommandHandler, EventBus, EventsHandler, IEventHandler } from '@nestjs/cqrs';
import { PlaceOrderCommand } from './place-order.command';
import { OrdersRepository } from './orders.repository';
import { Mailer } from './mailer';

export class OrderPlacedEvent {
  constructor(public readonly orderId: string, public readonly email: string) {}
}

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

  async execute(cmd: PlaceOrderCommand): Promise<string> {
    // Critical work: awaited, so failures reach the caller.
    const order = await this.orders.create(cmd.customerId, cmd.items);
    // Fire-and-forget: the command does not wait for event handlers.
    this.eventBus.publish(new OrderPlacedEvent(order.id, cmd.email));
    return order.id;
  }
}

@EventsHandler(OrderPlacedEvent)
export class SendConfirmationHandler implements IEventHandler<OrderPlacedEvent> {
  private readonly logger = new Logger(SendConfirmationHandler.name);
  constructor(private readonly mailer: Mailer) {}

  async handle(event: OrderPlacedEvent): Promise<void> {
    // Best-effort side effect: catch and log, because no one else will see this error.
    try {
      await this.mailer.sendOrderConfirmation(event.email, event.orderId);
    } catch (err) {
      this.logger.error(`Confirmation email failed for order ${event.orderId}`, (err as Error).stack);
    }
  }
}

The command handler awaits the order write it must guarantee and publishes OrderPlacedEvent without waiting, while the event handler catches and logs its own failures because they never reach the original request.

Where should database transactions and event publishing go?

The command handler owns the unit of work. It opens the database transaction, loads what it needs, applies the change, and commits. Only after the commit resolves does it publish events. With AggregateRoot, that means calling apply() inside the transaction to queue events on the aggregate, then calling commit() on the merged aggregate once the database transaction has succeeded. If you use EventBus directly, call publish() after the commit.

The ordering matters because event handlers run against whatever they read. If you publish before the commit and the transaction then rolls back, a handler may already have sent an email, invalidated a cache, or written a projection for an order that does not exist. Publishing after the commit rules that out.

This ordering guarantees one thing: no handler ever sees rolled-back state. It does not guarantee that events are delivered at all. If the process crashes, is killed during a deploy, or throws between the commit and commit()/publish(), the data is persisted but the event is lost.

That gap is where an outbox pattern becomes relevant. With an outbox, the event is written to a table inside the same transaction as the state change, and a separate process delivers it afterwards. You do not need one when handlers only do things you can afford to miss or rebuild. You do need one once a lost event means a customer is never notified or a downstream system drifts out of sync.

import { CommandHandler, EventPublisher, ICommandHandler } from '@nestjs/cqrs';
import { DataSource } from 'typeorm';
import { PlaceOrderCommand } from './place-order.command';
import { Order } from './order.aggregate';
import { OrderEntity } from './order.entity';

@CommandHandler(PlaceOrderCommand)
export class PlaceOrderHandler implements ICommandHandler<PlaceOrderCommand> {
  constructor(
    private readonly dataSource: DataSource,
    private readonly publisher: EventPublisher,
  ) {}

  async execute(command: PlaceOrderCommand): Promise<string> {
    // The handler owns the unit of work: the callback commits or rolls back as a whole.
    const order = await this.dataSource.transaction(async (manager) => {
      // Order.place() calls this.apply(new OrderPlacedEvent(...)).
      // apply() only queues the event on the aggregate; nothing is published yet.
      const aggregate = this.publisher.mergeObjectContext(
        Order.place(command.orderId, command.customerId, command.lines),
      );
      await manager.save(OrderEntity, aggregate.toPersistence());
      return aggregate;
    });

    // Reaching this line means the transaction committed. If it threw, we never
    // get here and the queued events are dropped, so no handler sees rolled-back state.

    // Crash gap: the order is persisted, but if the process dies or throws
    // between the commit above and the call below, OrderPlacedEvent is lost.
    // Closing this gap is what an outbox is for.
    order.commit();

    return order.id;
  }
}

A NestJS command handler that applies events inside a TypeORM transaction and publishes them with commit() only after the transaction resolves, with the remaining post-commit crash gap marked in comments.

When should you use sagas, and when should you avoid them?

A saga in @nestjs/cqrs is a class property decorated with @Saga(). It receives the stream of every event published on the event bus and returns a stream of commands. The module subscribes to that stream and dispatches each emitted command through the command bus. A typical saga pipes the event stream through ofType(OrderPlacedEvent) to filter by event class, then map(event => new ReserveStockCommand(event.orderId)) to turn each match into a command. The saga does no work itself. It only decides what should happen next.

This fits simple in-process follow-ups: after an order is placed, reserve stock; after a user registers, create a default workspace. The reaction is immediate, it uses data already on the event, and it keeps the triggering handler unaware of what follows.

Sagas are a poor fit for long-running or cross-service processes. The stream exists only in memory, so a restart loses any in-flight state. Nothing records that step two ran and step three is pending. Retries, timeouts and compensation all have to be written by hand with RxJS operators, and none of them survive a crash. If a process waits on payment confirmation for hours or spans several services, it needs a persisted state machine or a workflow engine, not an observable.

Sagas also hide control flow. A command emits an event, the saga maps it to another command, and that command emits more events. None of this appears at the call site. Keep chains to one or two hops. Log every event-to-command mapping with a correlation ID so you can reconstruct the path a request took.

Which endpoints deserve a command or query, and how should you organise the code?

Give an endpoint a command or query only when it does at least one of these: triggers more than one side effect, enforces invariants that span several entities, or is called from more than one entry point, such as HTTP, a queue consumer and a CLI job. A GET /users/:id or a single-row update does none of these, so a plain service method is enough. Wrapping it in a command, a handler and a module registration adds work and buys nothing.

Group by feature, not by pattern. A module such as orders/ holds commands/, queries/, events/ and a plain orders.service.ts for simple CRUD. Avoid a global top-level commands/ folder, because it scatters each feature across the codebase.

The costs are real:

  • Each operation needs several extra classes, and every handler has to be registered.
  • Go-to-definition stops at commandBus.execute(), so you have to search for the handler by name.
  • Without a written team convention, some developers will use the bus and others will inject services directly, and the codebase ends up mixing both for no clear reason.

The payoff is small, single-purpose handlers that are quicker to review. Side effects also move out of the write path, so adding a notification does not mean editing the order logic.

Plain service In-process CQRS CQRS with broker and read models
Indirection None One bus hop Bus, broker, projections
Typing Direct calls Weaker across the bus Schema contracts at boundaries
Delivery Synchronous call In-memory, lost on crash Broker-dependent, usually at-least-once
Operational cost Lowest Low High
Fits CRUD Multi-effect workflows Independent scaling and consumers

How do you test CQRS handlers, and when should you go beyond in-process CQRS?

A handler is a plain class with injected dependencies, so the cheapest useful test constructs it directly with new, passing a mocked repository and an EventBus stub whose publish is a spy. Call execute() and assert on two things: the state change sent to the repository, and the exact events passed to publish. Those events are the contract with the rest of the system, so check their type and payload, not just that publish was called.

Routing through the CommandBus adds module setup and tests no extra logic when the handler is the unit. Keep a TestingModule that imports CqrsModule for a few wiring tests that confirm each command reaches its registered handler.

Event handlers need extra care. Publishing does not wait for an async handler to finish, so asserting right after a command often checks state the handler has not written yet. Unit-test event handlers by calling handle() directly and awaiting it. Reserve bus-level checks for wiring.

In-process CQRS is enough until a specific signal shows otherwise. Each signal below justifies one step, not a full redesign:

Signal Minimal next step
A lost event after a crash is unacceptable Outbox table written in the same transaction, relayed by a poller
Other services must consume the same events Real message broker, fed from the outbox
Read load or query shape outgrows the write schema Separate read model updated by event handlers
Audit history or replay is a stated requirement Event sourcing for that aggregate only

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to nestjs cqrs, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Consumers learn about a breaking change at review time rather than from production errors.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.