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.