chapter thirteen

13 Using the CQRS pattern to implement system queries

 

This chapter covers

  • Why some queries can’t use the API Composition pattern
  • Implementing queries using the CQRS pattern
  • Understanding the benefits and drawbacks of CQRS
  • Designing a CQRS view: its database, schema, and repository

Some queries in a microservice architecture can’t be implemented efficiently by simply querying the service, or services, that own the data. While API Composition, the simplest way to implement a distributed query, works well for many queries, for some it’s too inefficient. An API composer might, for example, need to fetch large data sets from multiple services, possibly using many network round trips, and join them in memory. For other queries, API Composition is fragile. Because an API composer uses synchronous request/response, it’s runtime coupled to one or more provider services, which reduces availability and increases latency.

Nor is this only a problem for distributed queries: some queries are challenging to implement even when they’re local to a single service. A service’s database is chosen and structured for its commands, and it can’t always support the service’s queries efficiently as well. A query might need a different schema, a different type of database, or more capacity than the database can provide.

13.1 When API Composition isn’t the solution

13.1.1 Distributed queries that can’t use the API Composition pattern

13.1.2 Challenging single-service queries

13.2 Using the CQRS pattern

13.2.1 Overview of the CQRS pattern

13.2.2 The benefits of the CQRS pattern

13.2.3 The drawbacks of the CQRS pattern

13.3 Designing a CQRS view for a system query

13.3.1 Selecting the view database

13.3.2 Designing the view schema

13.3.3 Designing the view repository

13.3.4 Designing the provider events and their handlers

13.3.5 Deploying and updating the view service

13.4 Summary