Lots of people describe CQRS as a complicated pattern. Young programmers read that Command doesn’t return any data, and that Query, unlike Command, mustn’t update data. But what does it really mean? The return type of Command should be of type void? Maybe there are some exceptions?
What happens when we are forced to make POST /api/orders? It is important to know what the ID of the created resource is. There are situations in which we want Command to tell more about modifications made to data (e.g. the date of expected arrival of order). This is more convenient for us and better for performance (less requests, less network traffic).
When it comes to Query, the situation is clear - it should return the data which we asked for. Never modify them.
BUT, I have a feeling that Command is not explained properly, but is almost as simple as Query.
Command vs Query
Sometimes people say that Command doesn’t return any data, it modifies them. It is true, but it is about the purpose of its creation. So the statement should be:
The purpose of Command isn’t fetching data.
Command is allowed to return information about modified data—or the result of a state change—via a response DTO the same way as Query (in MediatR naming). There is no difference between Command and Query in code structure.
It goes about a few rules:
- Query should only return data, it mustn’t modify application data (usually the request has suffix
Queryand the handler has suffixQueryHandler) - Command’s task is to modify application data and, if needed, to return information about the new state (usually the request has suffix
Command, and the handler has suffixCommandHandler).
When we take into account responsibility and naming, those are all the rules. When we see examples of CommandHandler and QueryHandler, all should become clear.
Here is a simple query example:
public sealed record GetOrderQuery(Guid Id) : IRequest<Result<GetOrderResponseDto>>;
public sealed record GetOrderResponseDto
{
public required Guid Id { get; init; }
public required Guid ProductId { get; init; }
public required int Quantity { get; init; }
public required decimal TotalPrice { get; init; }
public required DateTimeOffset ExpectedDeliveryAt { get; init; }
public required DateTimeOffset CreatedAt { get; init; }
}
public sealed class GetOrderQueryHandler(IOrderRepository orderRepository)
: IRequestHandler<GetOrderQuery, Result<GetOrderResponseDto>>
{
public async Task<Result<GetOrderResponseDto>> Handle(
GetOrderQuery request,
CancellationToken cancellationToken)
{
var order = await orderRepository.GetByIdAsync(
request.Id,
cancellationToken
);
if (order is null)
{
return Error.NotFound(
ErrorCodes.OrderNotFound,
$"Order '{request.Id}' was not found.");
}
return new GetOrderResponseDto
{
Id = order.Id,
ProductId = order.ProductId,
Quantity = order.Quantity,
TotalPrice = order.TotalPrice,
ExpectedDeliveryAt = order.ExpectedDeliveryAt,
CreatedAt = order.CreatedAt,
};
}
}
and a simple command:
public sealed record CreateOrderCommand(Guid ProductId, int Quantity)
: IRequest<Result<CreateOrderResult>>;
public sealed record CreateOrderResult
{
public required Guid Id { get; init; }
public required Guid ProductId { get; init; }
public required int Quantity { get; init; }
public required decimal TotalPrice { get; init; }
public required DateTimeOffset ExpectedDeliveryAt { get; init; }
}
public sealed class CreateOrderCommandHandler(
IProductRepository productRepository,
IOrderRepository orderRepository,
TimeProvider timeProvider)
: IRequestHandler<CreateOrderCommand, Result<CreateOrderResult>>
{
public async Task<Result<CreateOrderResult>> Handle(
CreateOrderCommand request,
CancellationToken cancellationToken)
{
var product = await productRepository.GetByIdAsync(
request.ProductId,
cancellationToken
);
if (product is null)
{
return Error.NotFound(
ErrorCodes.ProductNotFound,
$"Product '{request.ProductId}' was not found.");
}
var order = Order.Create(
product,
request.Quantity,
timeProvider.GetUtcNow()
);
orderRepository.Add(order);
await orderRepository.SaveChangesAsync(cancellationToken);
return new CreateOrderResult
{
Id = order.Id,
ProductId = order.ProductId,
Quantity = order.Quantity,
TotalPrice = order.TotalPrice,
ExpectedDeliveryAt = order.ExpectedDeliveryAt,
};
}
}
At first glance we can see the difference in naming and the command’s role in mutating data. To be honest, that is the most important lesson that we should remember about CQRS.
The full sample is Example.Cqrs.
Where is the hard part?
The hard part comes with another CQRS rule that states that Query should use different data models than Command (usual implementation of that is separated database or separated tables). This implies that the command must perform some action that will fire read model update. It can be done in two ways.
Asynchronous
In this approach Command should emit some event to the message broker (e.g., RabbitMQ, Azure Service Bus, etc). Publication should happen through implementation of the Outbox Pattern to the broker. The second move that should happen is receiving that message and its processing.
At this moment we have to be careful to process messages only once (brokers are at-least-once delivery). We can do that in two ways:
- Indempotency - processing messages a few times results in the same data state.
- With the help of the Inbox Pattern
Synchronous
Assuming we implemented the read model using separated tables in the RDBMS, we can update it in the same transaction as the write model, from the write model data we already have.
Both approaches add big complexity to our system, but do we really always need it? Nope. We can stay with a simple version where we use the same models (probably same tables in database), but it is closer to CQS than CQRS. This is still good, we gain separation of responsibilities in handlers, one for queries, one for commands.
Do we always need full CQRS implementation?
Full implementation of CQRS requires lots of additional code and complexity. But do we always need it?
If there is no justification for building such a complicated solution, I don’t see any reason to complicate the code. This becomes more complex if our domain model is complex, which implies problems with performance in searching data in the database. Then we need a query-optimized database schema. This is less common in practice; usually CQS is more than enough and we shouldn’t add additional complexity to our system with full CQRS without any good reason. You aren’t gonna need it (YAGNI).
By the way, YAGNI is one of my favorites ;)
Trade-offs
The points above are trade-offs, the hard parts you need to weigh before implementation. What’s more important is that we cannot complicate the system without any good reason.
In my experience, it’s worth implementing full CQRS especially when we have performance problems on the read side - then we can create a read model that is query-optimized.
Read models can have very different structure or even less data in database tables. Sometimes when we start thinking about a read model, we see that some of the data, or nested structures are not needed. Remember that each system is different and you should make decisions on all the data you have. In practice, you’ll often decide on only part of that data.
TL;DR
CQRS is based on a few rules:
- Query mustn’t mutate the system data,
- Command mutates application state and can return information about the performed action,
- Query and Command use different models (common implementations use different databases)
After a command runs, update the read model via:
- Same transaction
- Asynchronous update that goes through message broker
Most of the time there is no justification for implementing complexity in our system, and it is a good choice to implement CQRS where Command and Query use the same data model (e.g., same tables in database), which is closer to CQS than CQRS, we still benefit on separation at the class level.
Comments
Join the conversation using your GitHub account. You can also browse the discussions on GitHub.