System ArchitectureBackend developer

How to implement requests in a distributed architecture using the API composition pattern?

Pass interviews with Hintsage AI assistant

Answer.

API Composition pattern is used when the data for the frontend or external service needs to be aggregated from different microservices. This is implemented through a coordinating layer (API Composer), which collects the required data through individual requests to the necessary services and forms the final response.

Often, this layer is implemented as a separate service, Gateway, or BFF (Backend For Frontend), providing aggregation, transformation, and error handling. This solution reduces excessive network calls and isolates clients from changes to internal APIs.

Code example (in Node.js + Express):

const axios = require('axios'); app.get('/user-details/:id', async (req, res) => { const user = await axios.get(`http://usersvc/user/${req.params.id}`); const orders = await axios.get(`http://ordersvc/orders/user/${req.params.id}`); res.json({ user: user.data, orders: orders.data }); });

Key Features:

  • Transformation and aggregation of data from different services into a single API
  • Isolation of clients from the details of the internal microservices architecture
  • Scalability by offloading the burden to a separate layer

Trick Questions.

Is API composition always the best way to aggregate data from microservices?

No, with a large number of related entities and slow connections, performance may suffer. In some cases, it is better to use CQRS or Data Aggregator services.

Can the frontend directly call each microservice?

In small systems, this is possible, but as the system grows, issues of security, schema management, scalability, and overloading the frontend with aggregation logic arise. Therefore, a centralized aggregation layer is preferred.

Does API composition ensure transactional integrity between services?

No. This pattern only aggregates data for the request. Transactionality needs to be implemented through sagas or event mechanisms.