CQRS
Command-Query Responsibility Segregation
- Definition
- This pattern holds that the reading of a database can be handled by a different model (and its tables) than that is used to write to the database. There can even be multiple read-models for the same data.
How does it work?
A CQRS system separates a Command Model from a Query Model. Whenever the system executes an action, an Action object is created and this is stored in the command model. A signal is then sent to the Query Model and all models that depend on this command are updated, asynchronously.
Data entering the system is written only to the Command Model. When an application needs to show data, it is read from the Query model.
The Query Models are "throw away" and may be recreated from the Command Model. However, it may take (considerable) time to recreate the Query Models.
Examples
- Banking. Bank account transactions are stored in one store. Bank account views are stored in a different model and updated infrequently (once a day).
Where does it come from?
CQRS was created by Greg Young.
When should you use it?
Problems
Common implementation techniques
- CQRS is normally used in conjection with Event sourcing to store its Commands.
- In theory it is possible to use CQRS with just a plain database that only stores the current state as a Command Model, but this is not much different from plain caching.