Video in progress
Why is the list page of `order-service` slow in this code, and how do you fix it?
public List<OrderView> list(Pageable page) {
return orderRepo.findAll(page).stream()
.map(o -> new OrderView(o, customerClient.get(o.getCustomerId())))
.toList();
}
A separate HTTP request goes to customer-service for every order, which is N+1 over the network. 50 orders means 50 calls. The fix: collect the IDs and fetch them through one batch endpoint, or keep the needed field as a local copy.
📖 Answer
You don't notice this locally: customer-service is right next to you, each call takes 2 ms. On prod each call takes 15-30 ms, and with 50 orders on a page the list alone takes over a second. On top of that, the load on customer-service grows with the number of orders, not with the number of page views.
This is the same disease as N+1 in Hibernate, just with HTTP instead of SQL.
The fix is to collect the IDs and make a single request:
public List<OrderView> list(Pageable page) {
List<Order> orders = orderRepo.findAll(page).getContent();
Set<Long> ids = orders.stream()
.map(Order::getCustomerId)
.collect(Collectors.toSet());
Map<Long, CustomerDto> customers = customerClient.getByIds(ids); // GET /customers?ids=1,2,3
return orders.stream()
.map(o -> new OrderView(o, customers.get(o.getCustomerId())))
.toList();
}
For this you need a batch endpoint in customer-service, which is usually easy to ask for. Put an upper limit on the number of IDs (say, 100), otherwise the URL gets too long.
If the page only needs the customer name, there's another way: keep the name as a copy in order-service itself and keep it updated with a CustomerRenamed event. Then the list never goes over the network at all.
Sign up to mark studied questions and save your progress.