CQRS — Command Query Responsibility Segregation

Sumanth Kumar
3 min readFeb 8, 2021

CQRS (Command Query Responsibility Segregation) is a pattern in which read and write to the application is separated into different models. Write to the system is represented as command and read as a query.

If we talk about any application what we do is write some data to our system and do a few business validations and give that data back when the user needs it. Most of the times, we see there’s enough overlap between the write and read sides, so sharing a model makes it easy to build the application. But there are few applications, in which we can clearly say that writing and reading from the application are quite different and their models don’t share anything in common. I still feel such suitability for the project as a whole is very less, but when we implement our project in different bounded contexts, we might have that suitability in few of the bounded contexts and in such contexts, write and read separation helps us achieve a lot of benefits.

One of the major benefits, I could see is high performance because we know reads and writes to the system are two separate things, so choosing a data store for read and write independently gives us scope for optimization and increase in performance. We can also scale them independently when we see either writes/reads to the system are very huge with respect to other.

CQRS

Another advantage of having both of these separated is, when a domain is too complex, it gets difficult to write something to the system as it involves a lot of business validation and it might be very complex to understand and validate such behavior. In such cases, following DDD (Domain Driven Design) and keeping business logic stick to the domain models helps in building the application and refactoring it at times. On the other hand, reads will not be that complex because it might just be projecting what we have in our data store and nothing else. So having these separated gives a clear picture of what that part of the application is responsible for and makes it easy to design the system and models.

When command and query are separated into two applications, most of the times communication between both of them happens through events. Write side of the application validates the business context and generates an event which will be stored in the database as an event itself for quick writes and will be published to query side of the application to create the state required for view. The store which collects all these events is called an event store and can be used for event sourcing.

Separating writes from reads could help us wonderfully while designing systems that would be complicated otherwise. However, in the case of simpler systems where reads and writes are almost similar, we might want to do away with separating these as implementing this pattern could add additional complexity.

--

--