Command Query Responsibility Segregation (CQRS) Pattern

Example for CQRS Pattern

Posted by Mr.Humorous 🥘 on March 15, 2019

Context

You have applied the Microservices architecture pattern and the Database per service pattern. As a result, it is no longer straightforward to implement queries that join data from multiple services. Also, if you have applied the Event sourcing pattern then the data is no longer easily queried.

Problem

How to implement a query that retrieves data from multiple services in a microservice architecture?

Solution

Define a view database, which is a read-only replica that is designed to support that query. The application keeps the replica up to data by subscribing to Domain events published by the service that own the data. CQRS Example

Examples

My book’s FTGO example application has the Order History Service, which implements this pattern.

There are several Eventuate-based example applications that illustrate how to use this pattern.

Resulting context

This pattern has the following benefits:

  • Supports multiple denormalized views that are scalable and performant
  • Improved separation of concerns = simpler command and query models
  • Necessary in an event sourced architecture

This pattern has the following drawbacks:

  • Increased complexity
  • Potential code duplication
  • Replication lag/eventually consistent views

See also

  • Eventuate, which is a platform for developing transactional business applications.
  • The book Microservices patterns describes this pattern in a lot more detail.