...

/

Command Query Responsibility Segregation (CQRS)

Command Query Responsibility Segregation (CQRS)

Learn about how the command query responsibility segregation pattern works.

In this last lesson of the chapter, we will discuss a popular architectural pattern for distributed systems: the command query responsibility segregation (CQRS) pattern.

What is CQRS?

The name pretty much gives away the meaning.

In CQRS, read and write paths are separated, and possibly there are separate databases that handle read and write requests.

Command means requests like create, insert, update or delete. On the other hand, query means read requests. In read requests, no data is changed in any way. Data is served to clients as a response to queries. In CQRS, the read and the write path are segregated. Written data is made available for reading using some sort of special mechanism.

Press + to interact
In CQRS, write and read paths are segregated
In CQRS, write and read paths are segregated

In the diagram above, we can see a high level overview of the CQRS pattern. Here:

  • Write-requests from the clients follow the blue path. Each write request ends up in a write handler server, which writes the data in a write database.

  • Queries from the clients follow the red path. Each query goes to a query handler server which reads data from a query database.

As we can see, the data has to be synced to the query database from the write database. How can we achieve that?

A common technique is to use events. Every time there is a write-request, an event is sent to a message queue from the write servers. This event is picked up by some worker that updates the query database.

There are many more complexities in the syncing ...