CQRS (Command Query Responsibility Segregation), is all about using separate operations for different responsibilities like Update and Read. It helps in enhancing the performance, scalability and security of the overall architecture.

In this blog we’ll discuss couple of real time problems and corresponding solutions to those problems using CQRS. Also considerations while implementing CQRS to your solution.

Problem –

While working with traditional CRUD application, you can face some challenges that will eventually adversely impact the performance of the application and thereby a bad user experience, some of these are-

  • Difference in read and write representations of the data like the object may contain a column that is not even required.
  • It risks data contention when records are locked in the data store
  • It can make managing security and permissions more complex
  • Negative effect on performance due to load on the data store and data access layerCQRS-1

Solution-

CQRS comes to the rescue. Where you can segregate the responsibility of Command (Update) and Query (Read) to separate models, repository, schema. You can implement the CQRS for above problem in following way-

  • Separate “query model” for reading data and the “update model” for writing data.
  • The read store can be a read-only replica of the write store or completely different schema
  •  Using multiple read-only replicas can greatly increase query performance

CQRS-2

Problem –

In Microservice architecture, there are several issues/challenges that we face. When you are working in distributed architecture, you are bound to face challenges. Some of them are as follows-

  • No longer straightforward to join the queries
  • The data is not easily queried
  • Consistency across the databases is no longer easy to maintain

Solution-

In Microservice architecture

  • Define a view database, which is a read-only replica or completely different schema.
  • The application keeps the secondary up to data by subscribing to Domain events published by the service that owns the data.CQRS-3Issues and Considerations
    • It may add complexity in terms of resiliency and eventual consistency
    • There is a risk of potential code duplication
    • Consider applying CQRS to limited sections of your system
    • A typical approach to deploying eventual consistency is to use event sourcing in conjunction with CQRS

Leave a comment