Command Query Responsibility Separation (CQRS)
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.
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:
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.
- Two separate layers can be hosted on the same or multiple hosting environments.
- 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.
- 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.
- 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.
- Finally working with two separate units of code will improve the performance of the application. Data can be read faster than normal CRUD operations.
- This makes the complex business logic simpler by holding the single responsibility.
- A large team can work separately by dividing the responsibilities among the team members.
These are two ways you can make this happen
- We can separate interfaces for command and Query in the same layer of project.
- We can use two separate layers, one for commands and one for querying databases.