🦅 NestJS Advanced

What is the CQRS pattern and how does NestJS support it?

Answer

CQRS (Command Query Responsibility Segregation) separates read operations (Queries) from write operations (Commands), allowing each to be independently scaled and optimized. The @nestjs/cqrs module provides the infrastructure. Commands: represent an intent to change state — class CreateUserCommand { constructor(public readonly name: string) {} }. Handlers: @CommandHandler(CreateUserCommand) class CreateUserHandler implements ICommandHandler<CreateUserCommand>. Dispatch: await this.commandBus.execute(new CreateUserCommand(name)). Queries work similarly with QueryBus. Events use EventBus for domain events. Combined with Event Sourcing (storing state changes as events), CQRS enables audit trails, temporal queries, and high-write-throughput architectures.