Command Query Responsibility Segregation

Blog > Design Patterns

Command Query Responsibility Segregation is an important architectural pattern that you should be aware of as a developer. It has many advantages to some of the most difficult problems when building complex and large scale applications.
However, this type of architecture is specially tuned to solve a very specific subset of problems. This adds considerable complexity to your application.
CQRS separates reading and writing into two different models. This means that every method should either be a Command that performs an action or a Query that returns data. A Command cannot return data and a Query cannot change the data.
The main principle behind CQRS is that you use two different models for reading and writing. However, the actual implementation of this idea can be handled in a number of different ways.
Firstly you might use two different models that talk to the same database. When a user issues a Command, the write model will update the database and then the read model will query the database to present the data to the User Interface. This is a good solution for applications that require synchronous processing and immediate results.

When should you use Command Query Responsibility Segregation?
Adding unnecessary complexity to a web application can be the kiss of death. You should always aim to write the simplest solution rather than go nuts for architecture just for the sake of it.
However, for certain types of web applications, I’m sure Command Query Responsibility Segregation would be the answer you are looking for.
Applications that are appropriate for CQRS will typically have many of the same characteristics.
For example, they will require a task-based UI, complex data processing, an imbalance in reads and writes, and eventual consistency would not be a problem.

We should consider implementing CQRS only in certain cases:
  • We have changed business requirements a lot
  • The business doesn’t know exactly where it’s heading
  • We have scalability issues
  • We collaborate with other teams (ie: other bounded contexts)
  • Multiple services compete to alter the same resources
  • We are orchestrating other services around us
  • What’s going on in our domain will affect them or vice-versa
  • Our domain is write-oriented, we don’t read our own data, other applications do
Unless you face these characteristics, you shouldn’t be using CQRS.
It’s always good to know about different approaches and common methods to solve difficult problems. One day you might face a situation where CQRS would be the perfect solution.