CQRS standing for command query responsibility segregation. it divides a system actions into commands ( writing ) and queries ( reading ), seeks an even more aggressive separation of concerns splitting the model in two:
- the write model: also known as the command model, it performs the writes and takes responsibility for the true domain behavior.
- the read model: it takes responsibility of the reads within the application and treats them as something that should be out of the domain model.
every time someone triggers a command to the write model, this performs the write to the desired data store. additionally, it triggers the read model update, in order to display the latest changes on the read model.
this strict separation causes another problem "eventual consistency".
the consistency of the read model is now subject to the commands performed by the write model. in other words, the read model is eventually consistent. that is, every time the write model performs a command, it will pull up a process that will be responsible for updating the read model according to the last updates on the write model.
think about a caching system in front of a web application. every time the database is updated with new information, the data on the cache layer may potentially be invalid, so every time it gets updated, there should be a process that updates the cache system. cache systems are eventually consistent.
- separating write activity from ready activities allows you to use the best database technology for the task at hand, for example, sql database for writing and a nosql database for reading.
- read activity tends to be more frequent than writing, thus you can reduce response latency by placing read data sources in strategic geolocations for better performance.
- supporting the CQRS pattern requires expertise in a variety of database technologies.
- using the CQRS patterns means that more database technologies are required hence there is more inherent cost either in terms of hardware or if a cloud provider is used.
- ensuring data consistency requires special consideration.
- using a large number of databases means more points of failure.