Video tayyorlanmoqda

Strong Junior 🧩 Microservices

Bu kodda `order-service`'ning ro'yxat sahifasi nega sekin ishlaydi va uni qanday tuzatasiz?

public List<OrderView> list(Pageable page) {
    return orderRepo.findAll(page).stream()
        .map(o -> new OrderView(o, customerClient.get(o.getCustomerId())))
        .toList();
}

Har bir buyurtma uchun customer-service'ga alohida HTTP so'rov ketadi — bu tarmoq ustidagi N+1. 50 ta buyurtma — 50 ta chaqiruv. Yechim: ID'larni yig'ib, bitta batch endpoint orqali olish yoki kerakli maydonni lokal nusxada saqlash.

📖 Javob

Lokal muhitda bu sezilmaydi: customer-service yonida, har chaqiruv 2 ms. Prodda esa har chaqiruv 15–30 ms, sahifada 50 ta buyurtma — faqat shu ro'yxat uchun 1 soniyadan oshadi. Ustiga-ustak customer-service'ga yuk sahifa ochilishlar soniga emas, buyurtmalar soniga qarab o'sadi.

Bu Hibernate'dagi N+1 bilan bir xil kasallik, faqat SQL o'rniga HTTP.

Tuzatish — ID'larni yig'ib, bitta so'rov:

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();
}

Buning uchun customer-service'da batch endpoint kerak — uni so'rab olish odatda oson. ID'lar soniga yuqori chegara qo'ying (masalan, 100 ta), aks holda URL juda uzun bo'lib ketadi.

Agar sahifaga faqat mijoz ismi kerak bo'lsa, boshqa yo'l ham bor: ismni order-service'ning o'zida nusxa sifatida saqlab, CustomerRenamed event'i bilan yangilab turish. Shunda ro'yxat umuman tarmoqqa chiqmaydi.