Under The Hood
backend nestjs NestJS 10+ (`@nestjs/cqrs`)

CQRS Pattern: CommandBus, QueryBus, EventBus, and Sagas

Last updated
Prerequisites:
NestJS Services and Dependency Injection
CQRS & Event Sourcing patterns
  • nestjs
  • cqrs
  • command-bus
  • query-bus
  • event-bus
  • sagas
  • architecture

Read at your depth

The practical view

The CQRS package (`@nestjs/cqrs`) separates read and write operations. **Commands** represent state-changing actions executed via `CommandBus.execute(new CreateUserCommand(data))`. **Queries** represent read-only operations executed via `QueryBus.execute(new GetUserQuery(id))`. **Events** announce past occurrences via `EventBus.publish(new UserCreatedEvent(id))`. **Sagas** listen to events and trigger subsequent commands asynchronously.

The same idea in other frameworks

nestjs equivalent
`commandBus.execute(new CreateUserCommand())` and `@CommandHandler(CreateUserCommand)`.

Legacy vs modern

Monolithic Service with Mixed Read/Write vs Clean CQRS Handlers

Monolithic services become bloated with hundreds of mixed methods; CQRS breaks features into isolated command and query handlers.

before → after
Monolithic Bloated Service
userService.createAndEmailAndLogAndAudit(data); // ❌ 2000-line service god object
Decoupled CQRS Command Handler
commandBus.execute(new CreateUserCommand(dto)); // ✅ NEW: Single-responsibility handler

Interview gotchas

Context

Interviewers test your knowledge of event-driven distributed transactions.

The mechanical answer

An **Event Handler** (`@EventsHandler`) is a terminal listener that performs side effects (e.g. sending an email or writing a log) when an event occurs. A **Saga** (`@Saga()`) is an RxJS stream operator that listens to events and **translates them into NEW Commands** to be dispatched to the `CommandBus`. Sagas orchestrate multi-step, asynchronous business workflows (e.g. `OrderCreatedEvent` -> maps to -> `ExecutePaymentCommand`).

Trap

A Saga must return an `Observable<ICommand>`. If a saga returns `void`, it will not dispatch commands.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.