CQRS stands for Command Query Responsibility Segregation. It is an architectural pattern that separates operations that change data (commands) from operations that read data (queries), using different models — and optionally different data stores — for each. The idea comes from Bertrand Meyer's Command-Query Separation principle (a method should either change state or return data, not both), applied at the architecture level by Greg Young. Commands - Represent intent to change state: PlaceOrder, CancelBooking, ApproveLoan. - Validated and processed by command handlers using the write model (domain entities with business rules). - Usually return nothing or minimal data (an ID or status). Queries - Return data without side effects: GetOrderDetails, SearchProducts. - Use read models shaped for the consumer — DTOs from direct SQL projections, denormalised tables, caches or search indexes. Simple .NET example (CQRS-lite with one database) public sealed record PlaceOrderCommand(int CustomerId, List<OrderLine> Lines); public sealed class PlaceOrderHandler(AppDbContext db) { public async Task<int> Handle(PlaceOrderCommand cmd, CancellationToken ct) { var order = Order.Create(cmd.CustomerId, cmd.Lines); // domain rules db.Orders.Add(order); await db.SaveChangesAsync(ct); return order.Id; } } public sealed record GetOrderSummaryQuery(int OrderId); public sealed class GetOrderSummaryHandler(IDbConnection conn) { public Task<OrderSummaryDto?> Handle(GetOrderSummaryQuery q) => conn.QuerySingleOrDefaultAsync<OrderSummaryDto>( "SELECT o.Id, c.Name, o.Total, o.Status FROM Orders o JOIN Customers c ON c.Id = o.CustomerId WHERE o.Id = @OrderId", q); } Libraries such as MediatR, Wolverine or simple handler classes are commonly used to dispatch commands and queries. Full CQRS with separate stores - The write database emits events; projections update a read database (SQL read tables, Cosmos DB, Elasticsearch) optimised for queries. - Reads and writes scale independently; read models may be eventually consistent. - Often combined with event sourcing, where the write side stores events instead of current state. Benefits - Optimised, simpler queries; independent scaling; a cleaner write model; good fit with domain-driven design and event-driven systems. Drawbacks - More complexity, eventual consistency (with separate stores), synchronisation logic and duplicated data. When to use - Complex business domains, very different read and write workloads, heavy reporting or search requirements, collaborative domains. For simple CRUD applications, it is usually unnecessary.
Ravindra Wadile · · 0 likes