System ArchitectureBackend Engineer

What is CQRS (Command Query Responsibility Segregation) and why is it used?

Pass interviews with Hintsage AI assistant

Answer.

CQRS is a pattern that separates responsibility between commands (Commands) and queries (Queries). A command changes the state of the system, while a query only reads data. Often, different data models and separate interfaces are designed for these tasks.

Advantage of CQRS: it allows for optimizing data access processes for reading and writing separately, which improves the performance of complex systems, facilitates scaling, and optimization for different load scenarios.

Code example (CQRS using C#):

interface ICommand { } interface IQuery<TResult> { } class CreateOrderCommand : ICommand { public int OrderId { get; set; } } class GetOrderQuery : IQuery<Order> { public int OrderId { get; set; } } class OrderCommandHandler { public void Handle(CreateOrderCommand command) { // Making changes to the database } } class OrderQueryHandler { public Order Handle(GetOrderQuery query) { // Reading data from the database without changes return new Order(); } }

Key features:

  • Separates state modification operations from reading operations
  • Allows for optimizing storage and processing of each part separately
  • Enhances the consistency and security of the architecture, especially under high load

Trick Questions.

Is CQRS a version of CRUD split into two classes?

No, CQRS is more than just splitting methods. Typically, separate models, data structures, and interfaces are created for both the querying and command parts, and different databases are often used.

Is CQRS suitable for all projects?

No. Implementing CQRS makes sense only for complex, scalable systems with high performance and processing independence requirements. For small projects, it is often excessive.

Does CQRS guarantee eventual consistency?

Not necessarily. CQRS can be implemented with eventual consistency in distributed systems, but the pattern itself does not guarantee this.