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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
