NashTech Blog

Table of Contents
dart pins on electric dartboard

CQRS stands for Command Query Responsibility Segregation, a software architectural pattern that separates reads (queries) from writes (commands) into two separate models or services.

When to use CQRS pattern?

  • CQRS is valuable in collaborative environments where multiple users simultaneously access shared data. It provides the ability to finely define commands, reducing the likelihood of domain-level merge conflicts.
  • Task-based user interfaces where users are guided through a complex process as a series of steps or with complex domain models. The write model has a full command-processing stack with business logic, input validation, and business validation. The write model may treat a set of associated objects as a single unit for data changes (an aggregate, in DDD terminology) and ensure that these objects are always in a consistent state. The read model has no business logic or validation stack, and just returns a DTO for use in a view model. The read model is eventually consistent with the write model.
  • Scenarios where performance of data reads must be fine-tuned separately from performance of data writes, especially when the number of reads is much greater than the number of writes. In this scenario, you can scale out the read model, but run the write model on just a few instances. A small number of write model instances also helps to minimize the occurrence of merge conflicts.
  • In some instances, the data model used for writing to the database might not be appropriate for querying. Through CQRS, multiple data models can be established for each operation by separating the read and write models.
  • Scenarios where the system is expected to evolve over time and might contain multiple versions of the model, or where business rules change regularly.

What is MediatR?

MediatR is a NuGet package for .NET applications that helps to implement the Mediator pattern and MediatR can be used as a useful tool to implement CQRS in a .NET application. MediatR pattern helps to reduce direct dependency between multiple objects and make them collaborative through MediatR.

Main features of the Mediator pattern:

  • Centralized Communication: In the Mediator pattern, interactions between components are channeled through a mediator object, which serves as a central hub. This setup allows components to send messages to the mediator, which then handles the routing and processing of those messages.
  • Decoupling: The Mediator pattern promotes decoupling by ensuring that components do not interact directly with one another. Instead, they rely on the mediator for communication, thereby reducing dependencies between components and making the system more maintainable and extensible.
  • Flexibility: Due to the loose coupling facilitated by the Mediator pattern, components can be easily replaced or modified without affecting other parts of the system. This enhances the system’s flexibility and adaptability to change.
  • Complexity Management: In systems with numerous components, direct interactions between them can lead to complexity. The Mediator pattern helps manage this complexity by centralizing communication and simplifying the interactions between components.
  • Encapsulation: By encapsulating interactions within a single mediator object, the Mediator pattern promotes encapsulation. This makes the system easier to understand and manage, as the interactions between components are contained within a specific mediator object.

CQRS Using MediatR

 

    Query Handler

 

Output

   Command Handler

 

Output

Benefits of CQRS include

  • Independent scaling: CQRS allows the read and write workloads to scale independently and may result in fewer lock contentions.
  • Optimized data schemas: The read side can use a schema that is optimized for queries, while the write side uses a schema that is optimized for updates.
  • The read database includes denormalized data that reduce to complex and long-running join queries. Complex business logic goes in to write database. Improve application performance for all aspects.
  • Flexibility of system that is better evolve over time and not affected to update commands and schema changes by separating read and write concerns in different databases.
  • Security: It’s easier to ensure that only the right domain entities are performing writes on the data.
  • Separation of concerns: Segregating the read and write sides can result in models that are more maintainable and flexible. Most of the complex business logic goes into the write model. The read model can be relatively simple.
  • Simpler queries: By storing a materialized view in the read database, the application can avoid complex joins when querying.

Drawbacks of CQRS

  • Complexity: Although it introduces a new layer of abstraction to manage data, the increased complexity poses a risk of errors due to additional logic for handling commands, dispatching, and logging.
  • Messaging: Although not mandatory, CQRS commonly employs messaging for command processing and event broadcasting. Consequently, the system must manage potential issues like message failures or duplicates.
  • Migration: Organizations with established systems may find transitioning to CQRS challenging, especially if the existing system lacks complex logs or employs batch updates.
  • Eventual Consistency: With separate read and write databases, the read data may lag behind, potentially leading to inconsistencies. Ensuring timely updates in the reading database can be challenging.
  • Delayed Synchronization: As the write and read models are independent, changes in the write mode may not immediately reflect in the read mode, potentially causing issues for users accessing outdated data.
  • Costs: Adopting CQRS patterns often incurs higher hardware and cloud service costs, mainly due to the need for additional database technologies.

Conclusion

In conclusion, CQRS is an architectural pattern that separates read and write concerns, offering benefits like improved scalability, performance optimization, and simplified business logic. While it introduces complexity and messaging challenges, organizations seeking enhanced flexibility and maintenance in their systems can benefit from its adoption, provided proper planning and consideration of costs.

Picture of anshurawate48e9c921e

anshurawate48e9c921e

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top