Browser docs

Aggregator Microservices

Intent

The user makes a single call to the aggregator service, and the aggregator then calls each relevant microservice.

Explanation

Real world example

Our web marketplace needs information about products and their current inventory. It makes a call to an aggregator service which in turn calls the product information microservice and product inventory microservice returning the combined information.

In plain words

Aggregator Microservice collects pieces of data from various microservices and returns an aggregate for processing.

Stack Overflow says

Aggregator Microservice invokes multiple services to achieve the functionality required by the application.

Programmatic Example

Let’s start from the data model. Here’s our Product.

1public class Product {
2  private String title;
3  private int productInventories;
4  // getters and setters ->
5  ...
6}

Next we can introduce our Aggregator microservice. It contains clients ProductInformationClient and ProductInventoryClient for calling respective microservices.

 1@RestController
 2public class Aggregator {
 3
 4  @Resource
 5  private ProductInformationClient informationClient;
 6
 7  @Resource
 8  private ProductInventoryClient inventoryClient;
 9
10  @RequestMapping(path = "/product", method = RequestMethod.GET)
11  public Product getProduct() {
12
13    var product = new Product();
14    var productTitle = informationClient.getProductTitle();
15    var productInventory = inventoryClient.getProductInventories();
16
17    //Fallback to error message
18    product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed"));
19
20    //Fallback to default error inventory
21    product.setProductInventories(requireNonNullElse(productInventory, -1));
22
23    return product;
24  }
25}

Here’s the essence of information microservice implementation. Inventory microservice is similar, it just returns inventory counts.

1@RestController
2public class InformationController {
3  @RequestMapping(value = "/information", method = RequestMethod.GET)
4  public String getProductTitle() {
5    return "The Product Title.";
6  }
7}

Now calling our Aggregator REST API returns the product information.

1curl http://localhost:50004/product
2{"title":"The Product Title.","productInventories":5}

Class diagram

alt text

Applicability

Use the Aggregator Microservices pattern when you need a unified API for various microservices, regardless the client device.

Credits