CQRS Introduction

Introduction - Command Query Responsibility Segregation (CQRS)

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

A: 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.

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

适用场景

  1. 当在业务逻辑层有很多操作需要相同的实体或者对象进行操作的时候。CQRS使得我们可以对读和写定义不同的实体和方法,从而可以减少或者避免对某一方面的更改造成冲突;

Reference