CQRS Pattern - Command And Query Responsibility Segregation

What is CQRS Pattern?

CQRS means Command Query Responsibility Segregation. This pattern was first introduced by Greg Young and Udi Dahan. Basically, this pattern was inspired by the pattern called CQS (Command Query Separation) which was introduced by Bertrand Meyer. In CQRS Pattern, we divide our operations of read and write into two parts - Command side and Query side. Now here, the Command side will manage the create, update, delete operations while the Query side will manage to get data from the database by executing the query.

How to use CQRS Pattern?

Here, I am going to show you a very basic example of CQRS which is easy to understand and hope will clear your doubts very well about CQRS.
We have a simple service for Student which can be,
Student Service
  1. void Student(StudentId)    
  2. Student Get Student(StudentId)    
  3. void Change Student Address(StudentId, NewAddress)    
  4. void Create Student(Student)  
Now, we are applying CQRS on this service which will divide the service into two parts -
  1. void Student(StudentId)  
  2. void Change Student Address(StudentId, NewAddress)  
  3. void Create Student(Student)  
  1. Student Get Student(StudentId)  
Here, we just applied the CQRS on the StudentService.

When do we use CQRS Pattern? 

There could be many scenarios where we can implement the CQRS. Some of the scenarios are listed below.
  • When we have the read operations greater than the write operations.
  • When we are performing multiple operations parallelly on the same data.
  • A scenario where users are guided through a complex process with complex domain models.
  • When we have enough individuals in our development team where some of them can manage the write side and some of them can work on the read side.

How CQRS affects our app?

Some of the main features od CQRS Pattern are listed below.
  • Both read and write sides can use an optimized schema for reading and writing operations.
  • It is easy to add or update on the reading side, without making any change on the writing side.
  • Our application can avoid complex joins while querying when we store materialized view in the database.
  • By implementing the CQRS, we can perform independent scaling, i.e., Horizontal scaling and Vertical scaling.
So here, we just learned some basics of CQRS which could help us in many situations. Hope to see you all on my new article. Until then, goodbye!!!.