advanced

NestJS CQRS module

Understand commands, queries, handlers, events, sagas, transactional boundaries, and when CQRS adds more ceremony than value.

The `@nestjs/cqrs` package separates writes (commands) from reads (queries). Commands mutate state through handlers; queries return data without side effects. Events decouple reactions from the write path.

					@CommandHandler(CreateOrderCommand)
export class CreateOrderHandler implements ICommandHandler<CreateOrderCommand> {
  constructor(private readonly repo: OrdersRepository) {}
  async execute(command: CreateOrderCommand) {
    const order = Order.create(command.payload);
    await this.repo.save(order);
    return order.id;
  }
}
				

`CommandBus`, `QueryBus`, and `EventBus` dispatch messages to registered handlers. Sagas orchestrate multi-step workflows across events. CQRS shines when read and write models diverge or event-driven reactions multiply.

On interviews: when CQRS adds value versus ceremony, transactional boundaries per handler, and eventual consistency trade-offs on the read side.

Common pitfalls: CQRS for simple CRUD, handlers that call other handlers in chains without clear boundaries, and events without idempotency.

Checklist:

  • Use commands for writes, queries for reads.
  • One handler per message type.
  • Publish domain events after successful commits.
  • Add CQRS only when model complexity justifies it.