In microservices retreving can be a challenge because the data is present in different databases owned by different microservices. API Composition , CQRS are commonly used query patterns in microservices architecture.
API Composition pattern
This pattern uses an API composer, or aggregator, to handling a query by invoking individual microservices that own the data. It then combines the results (sometimes by performing an in-memory join).
- API Gateway/backend for frontend can provide api composition capability . This makes sense when the query operation is part of exetranal API.
- Web application can do api composition.
- API composer can be separate microservice. Typically this should be done if query is called by multiple services.
Key points to remember
- As far as possible API compser should invoke individual microservices in parallel for performance reasons.(not seqentially).
- API composer often use reactive programming .
- Typicall api composer should be within lan. API composition should not be done by native/hybrid apps as request response cycles would be slow becuase of slow network.
Disadvantages of API Composition
- Since there is depedency on multiple services, the avalaibility decreases.Note that to mitigate avalaibility impact, using previously cached response, or omitting response data from composed response are two stategies which can be used.
- Since the api composer is returning data by querying multiple services, the data could be inconsistent as the response is not generated by single acid transaction.
- Creating in memory join can be expensive.(CQRS may be better option here). Developers should focus on logic , not creating in memory joins. Also when records may have to feched in bulk increasing network traffic.
CQRS(command query responsibility seggregation)
CQRS separates the data model into a read data model and write data model(create/update/delete). CQRS can be used as alternative api composition. Read more here.