top of page
Writer's pictureCristian Duque

CQRS (Command and Query Responsibility Segregation) Pattern

Updated: Nov 17, 2023


CQRS is an architectural design pattern that divides the concerns of writing data (commands) from reading data (queries).

This separation allows applications to design them independently. For example, writing data can be optimized for making transactions, while reading models can be optimized for querying and displaying data.


CRUD-based applications can share the same data model for querying and updating data.

However, this approach may not be suitable for specific scenarios:

"On the read side, the application may perform many different queries, returning data transfer objects (DTOs) with different shapes. Object mapping can become complicated. On the write side, the model may implement complex validation and business logic. As a result, you can end up with an overly complex model that does too much."CQRS pattern - Azure Architecture Center | Microsoft Learn



The CQRS pattern consists of two models:

  • Command: Responsible for writing operations that modify the application's state. It is the single source of truth for data changes. This model can lead to a cascade of side effects in the same command action.

  • Query: It handles read operations to return data without altering the system's state. It represents a query to request information from the application.



When working with different databases for storing and retrieving data, the application must be synchronized. One possible solution is to apply an Event-driven architectural style where the command operation publishes an event to notify about database changes. Another option to implement CQRS is Event sourcing, which stores the application state changes in a sequence of events.



What are the benefits of CQRS:

  • Separation of concerns: The command/query independence can result in more maintainable and scalable models.

  • Flexibility: Querying operations can be simplified by using different storage mechanisms for writing and reading.

  • Performance: Reading operations can be optimised for querying data. The write side can guarantee consistency and transactional behaviour.


And the drawbacks:

  • Eventual Consistency: "The separation of models may lead to eventual consistency between the read and write sides, requiring developers to handle potential inconsistencies in the application." CQRS pattern – Cloudopian

  • Complexity: Separating commands and queries can lead to application design complexity, especially when integrating queues, publisher/subscriber events, asynchronous communication and event sourcing.


Check out my video:




6 views

Recent Posts

See All

コメント


bottom of page