CQRS -Command Query Responsibility Segregation

Itspriyakar
2 min readFeb 23, 2021

While I was working on an existing application, I came across situations where I had to stay back late .. this time not due to a production issue but our system users complained regarding slowness issues. That was weird. At first, I didn’t know that it would turn into a project of its own but yes it was great learning by doing for me.

So the slowness issues were reported especially during month ends. So we started questioning each finding. Reindexing, optimizing queries was a very common thing to do which was not solving the problem this time.

So we started revisiting the application architecture and found out an interesting thing that was not the root cause but was contributing to the slowness issue definitely.

We found out that one of our reporting modules was pointing to the primary DB to query data which was mainly used to generate the big month-end reports. According to the data analysis, no of reading Operations were way more than other operations like create, update, delete. So decided to dedicate separate servers for reading operations which were one of the solutions to the performance issue.

So we used the CQRS (Command Query Responsibility Segregation) design pattern.

What is CQRS?

CQRS stands for Command-Query Responsibility Segregation. In order to implement CQRS, instead of having one unified model, you need to introduce two: one for reads(Query model) and the other one for writes (command model).

Why is it needed?

Write Models/Commands can cause side effects whereas Query/Read doesn't. This can save you from issues. CQRS encourages you to decouple a single, unified domain model and create two models: one for handling commands or writes, and the other one for handling queries, reads.

A cache can be set up for the specific part of the application when a separate set of APIs are designed for queries.

Benefits of CQRS

  1. Scalability

In an enterprise application, number of reads may vary as compared to write operations. So having different models for Query and Command can enable independent scaling.

2. Performance

Features like caching and rate-limiting can be implemented to enhance performance.

3. Simplicity

By having 2 separate models lots of complexity can be offloaded like concurrency handling.

Cons of CQRS

  1. Stale Data Issue

If we alter a resource (by sending a Command) and read this same resource right away, we won’t see our changes. In case we have real-time replications in place the data will be eventually consistent.

Summary

CQRS is a good design pattern that should be considered while architecting any application to avoid side effects and to empower the system in terms of Scalability, Performance, Simplicity.

--

--