CQRS stands for Command Query Responsibility Segregation. As the name suggests, we split the application in two parts: Command-Side and Query-Side. Now one will ask what this command and query means? Okay, so –
- Commands are the ones that change the state of the object or entity, also called modifiers or mutators.
- Queries are those that returns the state of the entity, and do not change anything. The another term for that will be accessors.
Why is it required?
In traditional data management systems, both commands and queries are executed against the same set of entities, having a single reprsentation or view. The CRUD operations are applied to a single datastore, the same entity or object is accessed to handle both read and write operations.
Issues with having single view for both read and write side –
- Introduces the risks of data contention.
- Managing permissions and security become complex as same objects are exposed to both read and write operations.
How CQRS solves this problem?
The CQRS pattern holds the idea that the method should either change the state of the entity, or returns the result, but not both. Segregating models for read and write side reduces the complexity that comes with having single view for both of them.
Benefits of CQRS –
- Separate command and query models, results in simplified design and implementation of the system and overall reduction of complexity.
- One can easily optimise the read side of the system separately from the write side, allows scaling each differently as per the load on the side. For example – Read datastores often encounters greater load, and hence can be scaled without affecting the write datastores.
- You can provide multiple views of your data for querying purpose depending on the use cases.
How CQRS works?
CQRS is mainly used in conjuction with Event Sourcing. The write side model of the CQRS-based system handles the events persistence, acting as a source of information for the read side. The read model of the system provides materialized views of the data, typically as highly denormalized views.
Example Implementation in C#
References & additional resources: