Tuesday, May 10, 2022

Pattern: Command Query Responsibility Segregation (CQRS)

Problem

Once we implement database-per-service, there is a requirement to query, which requires joint data from multiple services — it's not possible. Then, how do we implement queries in microservice architecture?

Solution

CQRS suggests splitting the application into two parts — the command side and the query side. The command side handles the Create, Update, and Delete requests. The query side handles the query part by using the materialized views. 

The event sourcing pattern is generally used it to create events for any data change. Materialized views are kept updated by subscribing to the stream of events.



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

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS