API / Microservices Design Patterns Interview Questions
What is CQRS (Command Query Responsibility Segregation) and when should you use it?
CQRS separates a service's data model into two distinct paths: a Command side that handles writes (state changes) and a Query side that handles reads. Each side can use a different data store, different data model, and even a different technology stack, optimised independently for its purpose.
On the Command side, commands express intent (PlaceOrder, UpdateShippingAddress) and mutate the authoritative write model. On the Query side, pre-built, denormalised read models serve specific views efficiently — for example, an order summary view that joins order, customer, and product data is materialised as a single flat document that can be served without any JOINs.
// Command side (write) class PlaceOrderCommand { orderId, customerId, items[] } class OrderCommandHandler { handle(PlaceOrderCommand cmd) { Order order = new Order(cmd.orderId, cmd.customerId, cmd.items); orderRepository.save(order); // write to normalised DB eventBus.publish(new OrderPlaced(order)); // update read models } } // Query side (read) class OrderSummaryQuery { orderId } class OrderQueryHandler { handle(OrderSummaryQuery q) { return orderSummaryReadModel.findById(q.orderId); // pre-built view } }
When to use CQRS:
- Read and write traffic profiles differ significantly (e.g., 100:1 read-to-write ratio) and require separate scaling strategies.
- Complex domain logic on the write side conflicts with simple, fast reads that need denormalised projections.
- You are using Event Sourcing (Q13), which pairs naturally with CQRS because events update separate read projections.
- The service needs to serve multiple different view shapes to different consumers (mobile, web, analytics) without a one-size-fits-all query model.
CQRS adds complexity: two models to maintain, eventual consistency between them (the read side lags the write side), and more infrastructure. It is over-engineering for simple CRUD services where a single model suffices.
More Related questions...