Command Query Responsibility Segregation (CQRS)

Command Query Responsibility Segregation (abbreviated as CQRS) is an architecture pattern that promotes the divide into read and write operations of your datastore.

In traditional systems where both reads and updates use a single set of database tables you either model and design for speed of read or speed of write. As your application grows, you may need to produce different representations of the same data (e.g daily reports, listing, etc…​) and these eventually become either very slow to produce or happen in a transaction during a write operation slowing the operation down.

In CQRS, the write-side, responsible for handling Commands, stores data using a database form with the least impedance mismatch in order to increase the throughput. As incremental changes in the state happen, a mechanism processes these increments asynchronously and produces a new database representation tailored for the read-side. The read-side, responsible for handling Queries, processes read operations and accesses the information on the read datastore.

The terms data and information should not be used interchangeably:

  • data refers to the source of truth

  • information refers to derived representations of the data

It is safe to lose some information as long as the loss doesn’t affect the data that produced that information.

You can start refactoring an application towards a CQRS architecture by identifying the operations that produce a change in the state (the Commands) and the operations that only read from the state (the Queries).

CQRS and Event Sourcing

As described above, CQRS doesn’t require the write-side handling the commands to be implemented using Event Sourcing. Using Event Sourcing, though, is a perfect fit for CQRS.

In CQRS, in order to build the read-side representations we want a stream of data changes to build projections from, and that is exactly what Event Sourcing provides. In Event Sourcing, state is stored as an append-only, ordered list of changes (referred to as events).

Summing up, in a CQRS application, the write-side and the read-side operate autonomously new tab. Generally, the write-side provides strong consistency new tab while the read-side provides eventual consistency.

Learn more