CQRS Pattern Flow
This document explains how the CQRS (Command Query Responsibility Segregation) pattern is implemented in MBC CQRS Serverless.
CQRS Overview
Command Flow - Write Path
The flow of write operations.
Command Flow Steps
- Request Received: Client sends POST/PUT/DELETE request
- DTO Validation: Controller validates input using class-validator
- Command Dispatch: Controller creates and dispatches command
- Business Logic: Command handler executes business rules
- Persistence: Command service persists to DynamoDB with optimistic locking
- Event Publishing: Domain events are published to SNS
- Response: Success response returned to client
Query Flow - Read Path
The flow of read operations.
Query Flow Steps
- Request Received: Client sends GET request
- Query Dispatch: Controller creates and dispatches query
- Data Retrieval: Query handler calls data service
- Database Query: Data service queries DynamoDB or RDS
- Response: Data returned to client
Key Components
Command Handler
@CommandHandler(CreateResourceCommand)
export class CreateResourceHandler
implements ICommandHandler<CreateResourceCommand> {
constructor(private readonly commandService: CommandService) {}
async execute(command: CreateResourceCommand): Promise<DataEntity> {
// 1. Validate business rules
// 2. Create entity
// 3. Persist and publish event
return this.commandService.publish(entity);
}
}
Query Handler
@QueryHandler(GetResourceQuery)
export class GetResourceHandler
implements IQueryHandler<GetResourceQuery> {
constructor(private readonly dataService: DataService) {}
async execute(query: GetResourceQuery): Promise<DataEntity> {
return this.dataService.getItem({
pk: query.pk,
sk: query.sk,
});
}
}
Benefits of CQRS
Adopting the CQRS pattern provides these benefits:
- Scalability: Read and write can be scaled independently
- Optimization: Optimize each side for its specific purpose
- Flexibility: Use different data models for reads and writes
- Performance: Denormalize read models for fast queries
- Auditability: Complete event history for audit trails