What is CQRS and why do you need it as a developer?

CQRS is deciphered as Command and Query Responsibility Segregation. It is an architectural design pattern which states that we must separate the operations for reading the data from the operations for writing or updating the data.

 

CQRS is not a pattern that encompasses the whole application. It is a concept that builds on Domain-Driven Design (DDD).

An important strategic concept of DDD is the so-called Bounded Context. In a typical application, there are multiple bounded contexts, any of which can be implemented the way it makes sense.

For instance:

  • User Management -> CRUD
  • Invoicing -> CRUD
  • Insurance Policy Management (the Core Domain) -> CQRS

Pros

  • Separating write from read activities allows the use of the best database technology (a SQL database for writing and a non-SQL database for reading).
  • Reducing response latency by placing read data sources in strategic geolocations for better performance.
  • Provides more efficient scaling of storage capacity based on real-world usage.

Cons

  • Requires expertise in a variety of database technologies.
  • Higher costs in terms of hardware or if a cloud provider is used.
  • Requires special consideration in terms of Service Level Agreements.
  • More points of failure, which implies comprehensive monitoring and fail-safety mechanisms.

When to use

  • Large team
    One can split development tasks between people easily. The top people can work on domain logic leaving the usual stuff to less skilled developers.
  • Difficult business logic
    CQRS helps avoid mixing domain logic and infrastructural operations.
  • Scalability matters
    Helps achieve great read and write performance (because queries can be optimized to do fast read operations).

What about the implementation?

Queries are a key element used for reading data. How are they helpful in the implementation process of CQRS?

  1. They offer the possibility of having one table for each view. Thus, the client can simply SELECT * FROM MyViewTable.
  2. There is no need for a relational database.
  3. They can be scaled horizontally.

What about the commands used for mutating data?

Here are some tips:

  1. Use the main data store for commands.
  2. Queue commands and have notifications about their execution statuses.
  3. Remember there’s no need to keep the server always on since queues can hold requests.
  4. After the command was executed, update the main database and query the data store concurrently.

Summary

  • CQRS is used for data reading and mutating separation.
  • CQRS is not a pattern that encompasses the whole application.
  • CQRS is a concept that builds on Domain Driven Design (DDD).
  • CQRS improves performance but is harder and more time consuming to implement.
  • CQRS has huge scalability.