What is Command Query Responsibility Segregation (CQRS)?


What is Command Query Responsibility Segregation (CQRS)? It is a pattern formed by Greg Young, an independent software consultant who was the pioneer of CQRS and Event Sourcing. The pattern describes using a different model for updating information (write) than the modal used for reading data. For many complex situations this separation can be highly valuable, for simpler tasks it can be total overkill and a detriment to projects. It should be made clear CQRS is not an architecture – it is just a simple pattern that examples architecture that would otherwise not be possible.

What is Command Query Responsibility Segregation, Diagram

Greg provides a good explanation of what CQRS is which we will expand on.

Think in your mind what a command is and what a query is. Commands mutate the state of the domain – this can be in terms of CRUD which we all love and know so well. Commands are nothing more than self describing DTO’s, for example ‘RegisterMember’ or ‘CancelOrder’. Typically their class name is a verb, describing the intent of the action. Commands do not return any value, as they are write only actions. Queries are similar, in that their class name will describe their intent. However, they will not affect the data store, instead simply finding a set of information based on a given set of parameters. They are read only operations, and may look like FindMembersByRegistrationDate(DateTime registrationDate) : MemberCollection. This is the foundation of CQRS, and as you can see, it’s really, really simple.

Imagine the following code:

CQRS Example

interface MemberService
{
    registerMember(id,email,password):void
    findMember(id):Member
    findMemberByEmail(email):Member
    addMembersAddress(address,id):void
}

Applying simple CQRS you would get two separated services:

interface MemberWriteService
{
    registerMember(id,email,password):void
    addMembersAddress(address,id):void
}
interface MemberReadService
{
    findMember(id):Member
    findMemberByEmail(email):Member
}

And that is simply what Command Query Responsibility Segregation is, nothing really more, you keep your read and your writes systems segregated. This enables you to change the way your programming mind works, a refreshing break from the standard ORM CRUD methodology.

The biggest benefit is realising that you can architect your commands and queries differently, and host your services separately. You can have a couple of write servers and many read servers. The rate in which you need to scale read and write services are different and in many applications the queries are many orders of magnitude more frequency than commands, so applying CQRS enables more targeted and effective scaling.

We will cover the other benefits in other articles as next we will be talking about Event Sourcing.