Cogs and Levers A blog full of technical stuff

CQRS

CQRS stands for Command Query Responsibility Segregation and is a software pattern focused on separating code that reads a data model’s state from code that updates a data model’s state. Ultimately, the implementation of this pattern leads to performance gains, scalability and headroom to support changes to the system down the line.

Separating out your reads and your writes can also give you an increased level of security.

Models

The query model is in charge of all of your retrieves. The whole premise of having a query model is that a query will only read information and not change anything on the way through. Making this part of the process pure in the interest of the model.

The command model are all of the items of work that we’re going to perform against our model (our update model) that changes state.

Tie it all together

This is an event sourcing system, so update messages will be routed through a command layer. Where the join back to the data store that retrieves come out of is an implementation detail.

Having this separation directly at the data layer may incur eventual consistency scenarios; desirable in some settings, unacceptable in others. An event bus manages the marshaling of commands from the user interface through to the data layer. This is also an opportunity to put these commands into an event stream.

Final notes

This pattern isn’t for every situation. It should be used/applied the same way as you’d apply any other pattern; with a great measure of study and common sense. Scenarios where you have a very high contention rate for data writers would be a very good fit.