Command Query Responsibility Separation (CQRS)

Definition

CQSR is an architectural pattern which states that while designing the data access layer in a project, it can be split into two separate units of codebase. Those two units of codebase are:

  1. Command
  2. Query

So this is called command query separation. In a simpler manner, it is a separation of code which reads data from a database from code which changes the state of data in a database. Thus the responsibility of reading data from a database and writing data to the database can be separated.

Benefits

  1. Two separate layers can be hosted on the same or multiple hosting environments.
  2. Most databases need to read data more frequently than to write data to the database, so we can create multiple databases to read from and one single database to write to and then the two databases can be synchronized.
  3. We can use multiple types of databases e.g. MSSQL for reading and MySQL for writing. So if there is separation of reading and writing then we can write different data access logic for two different types of databases.
  4. While separating the two things, we must create separate object classes for the Command layer and for the Query Layer. Thus we can create this object model independent of each other. The need of mapping of DTO objects of data layer and Domain model Objects can be avoided.
  5. Finally working with two separate units of code will improve the performance of the application. Data can be read faster than normal CRUD operations.
  6. This makes the complex business logic simpler by holding the single responsibility.
  7. A large team can work separately by dividing the responsibilities among the team members.

These are two ways you can make this happen

  1. We can separate interfaces for command and Query in the same layer of project.
  2. We can use two separate layers, one for commands and one for querying databases.


CQS.jpg