Load Balancing
Spring Cloud LoadBalancer, client-side load balancing, round-robin, custom strategy
- Enable client-side load balancing with @LoadBalanced RestTemplate
- Configure Spring Cloud LoadBalancer with a custom strategy
- Understand the difference between client-side and server-side load balancing
RestTemplate, RestClient, and FeignClient, how to configure per-service and global algorithms, and how to write a fully custom load balancer.Table of Contents
- What Is Load Balancing?
- Server-Side vs Client-Side Load Balancing
- Prerequisite — Service Discovery Recap
- Spring Cloud Load Balancer Overview
- Adding Load Balancing to RestTemplate
- Internal Flow — How the Load Balancer Interceptor Works
- The Service ID Concept — Critical Understanding
- Default Algorithm — Round Robin
- Overriding the Algorithm for a Specific Service
- Global + Per-Service Configuration Combined
- Writing a Custom Load Balancer
- Load Balancing with FeignClient
- Load Balancing with RestClient
- Load Balancer Configuration — Lazy Loading at Runtime
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Revision Bullets
1. What Is Load Balancing?
Overview
Load balancing is the process of distributing incoming network traffic across multiple instances of a server or service. Its primary purpose is to prevent any single server from being overwhelmed by too many requests.
Why It Exists
When traffic to a service increases, one common solution is to run multiple instances of that service. But then a new question arises: which instance should handle each incoming request? Load balancing answers this question.
Benefits
| Benefit | Description |
|---|---|
| Prevents overload | No single instance receives all traffic |
| High availability | If one instance fails, others handle the load |
| Scalability | Add more instances as traffic grows |
| Improved latency | Requests can be routed to the fastest/least-busy instance |
2. Server-Side vs Client-Side Load Balancing
These are the two fundamental architectures for load balancing. Understanding the difference is essential because Spring Cloud uses the client-side model.
2.1 Server-Side Load Balancing
- A dedicated, centralized server sits between the client and the service instances
- The client knows nothing about load balancing — it just calls the load balancer's address
- The load balancer decides which instance to forward to
- Examples: NGINX, AWS Application Load Balancer, HAProxy
- Covered when: API Gateway topic
2.2 Client-Side Load Balancing
- The caller itself contains the load-balancing logic
- The client first queries Service Discovery to get all available instances
- The client then applies a load-balancing algorithm to pick one
- The load balancing logic lives as a library inside the client application
- Examples: Spring Cloud Load Balancer, Netflix Ribbon (deprecated), Istio (service mesh)
Comparison Table
| Aspect | Server-Side | Client-Side |
|---|---|---|
| Load balancing location | Dedicated external server | Inside the calling service |
| Client awareness | None | Knows about instances |
| Service Discovery needed | No | Yes |
| Single point of failure risk | Yes (the LB server) | No (distributed) |
| Flexibility | Fixed by LB server | Configurable per client |
| Examples | NGINX, AWS ALB | Spring Cloud LB, Ribbon |
3. Prerequisite Service Discovery Recap
Why Service Discovery Comes First
Client-side load balancing depends on Service Discovery. Before the client can choose between instances, it must first know what instances exist. Service Discovery (Eureka) provides this list.
What We Had Before (Manual, Without Load Balancer Library)
In the Service Discovery video, we fetched instances manually and picked one ourselves:
1@RestController2public class OrderController {3
4 @Autowired5 private DiscoveryClient discoveryClient; // Spring's service discovery client6
7 @Autowired8 private RestTemplate restTemplate;9
10 @GetMapping("/order/{id}")11 public String getOrder(@PathVariable String id) {12
13 // Step 1: Ask Eureka for all instances of "product-service"14 List<ServiceInstance> instances =15 discoveryClient.getInstances("product-service");16
17 // Step 2: Pick one — but this is a BAD algorithm (always picks index 0)18 ServiceInstance instance = instances.get(0);19
20 // Step 3: Build the URL manually using the instance's host and port21 String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + id;22
23 // Step 4: Call it24 return restTemplate.getForObject(url, String.class);25 }26}Problems With This Approach
| Problem | Description |
|---|---|
| Manual instance fetching | Developer must call discoveryClient.getInstances() every time |
| No real algorithm | get(0) always picks the first instance — not load balancing |
| Tight coupling | Business logic mixed with infrastructure concerns |
| Hard to change algorithm | Must modify controller code |
Spring Cloud Load Balancer automates all of this.
4. Spring Cloud Load Balancer Overview
What It Is
Spring Cloud Load Balancer is a client-side load balancing library provided by the Spring Cloud project. It integrates with Spring's HTTP clients (RestTemplate, RestClient, FeignClient) and automatically:
- Queries Service Discovery for available instances
- Applies a load-balancing algorithm to select one
- Routes the request to the selected instance
Available Client-Side Load Balancers
| Library | Status | Notes |
|---|---|---|
| Spring Cloud Load Balancer | ✅ Active | Default choice in modern Spring Cloud |
| Netflix Ribbon | ❌ Deprecated | Do not use for new projects |
| Istio (Service Mesh) | ✅ Active | Wide variety of algorithms; operates as a sidecar |
Required Dependency
1<dependency>2 <groupId>org.springframework.cloud</groupId>3 <artifactId>spring-cloud-starter-loadbalancer</artifactId>4</dependency>This single dependency brings in all the Spring Cloud Load Balancer infrastructure.
5. Adding Load Balancing to RestTemplate
The Two Changes Required
To add Spring Cloud Load Balancer to an existing RestTemplate setup, only two changes are needed:
- Add the
@LoadBalancedannotation to theRestTemplatebean - Use the service name (not a hardcoded host/port) in the URL
Before Manual Discovery, Hardcoded URL
1@Configuration2public class AppConfig {3
4 @Bean5 public RestTemplate restTemplate() {6 return new RestTemplate(); // plain, no load balancing7 }8}9
10// In controller:11String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + id;12String response = restTemplate.getForObject(url, String.class);After Spring Cloud Load Balancer
1@Configuration2public class AppConfig {3
4 @Bean5 @LoadBalanced // ← THE ONLY CHANGE to the bean definition6 public RestTemplate restTemplate() {7 return new RestTemplate();8 }9}1@RestController2public class OrderController {3
4 @Autowired5 private RestTemplate restTemplate;6
7 @GetMapping("/order/{id}")8 public String getOrder(@PathVariable String id) {9
10 // Use service NAME instead of hardcoded host:port11 // "product-service" is the spring.application.name of the Product Service12 String response = restTemplate.getForObject(13 "http://product-service/product/" + id,14 String.class15 );16
17 return "Order placed. " + response;18 }19}`application.properties` for Order Service
1spring.application.name=order-service2server.port=80813
4# The base URL for product service — uses service name, not IP5product.service.url=http://product-servicehttp://product-service/... is not a real hostname. The @LoadBalanced annotation installs an interceptor that intercepts this URL, resolves product-service via Service Discovery, picks an instance, and replaces the URL with the actual host:port before the request is sent.What Changed Side by Side
| Aspect | Before (Manual) | After (Load Balanced) |
|---|---|---|
DiscoveryClient needed? | ✅ Yes | ❌ No |
| URL format | http://192.168.1.5:8082/product/1 | http://product-service/product/1 |
| Instance selection logic | Written by developer | Handled by framework |
| Load balancing algorithm | None (always get(0)) | Round robin (default) |
| Code changes required | Many | Just @LoadBalanced |
6. Internal Flow How the Load Balancer Interceptor Works
The `@LoadBalanced` Annotation
When you annotate RestTemplate with @LoadBalanced, Spring installs a LoadBalancerInterceptor into the RestTemplate's interceptor chain. This interceptor runs before the actual HTTP request is executed.
Step-by-Step Internal Execution
Key Internal Classes
| Class | Role |
|---|---|
LoadBalancerInterceptor | Intercepts all requests made by @LoadBalanced RestTemplate |
LoadBalancerClientFactory | Factory that selects and returns the correct load balancer for a given service ID |
ServiceInstanceListSupplier | Calls Service Discovery to retrieve all available instances |
ReactorServiceInstanceLoadBalancer | Interface that all load balancing algorithms implement |
RoundRobinLoadBalancer | Default algorithm — distributes requests evenly in rotation |
RandomLoadBalancer | Alternative built-in algorithm — picks randomly |
Inside `LoadBalancerInterceptor` (Simplified)
1// Simplified view of what LoadBalancerInterceptor does internally2public ClientHttpResponse intercept(HttpRequest request, byte[] body,3 ClientHttpRequestExecution execution) {4
5 String serviceId = request.getURI().getHost(); // extracts "product-service"6
7 // Step 1: Get the load balancer for this specific service ID8 ReactorLoadBalancer<ServiceInstance> loadBalancer =9 loadBalancerClientFactory.getInstance(serviceId);10
11 // Step 2: Choose one instance using the load balancing algorithm12 // (internally calls Service Discovery to get the list of instances)13 ServiceInstance instance = loadBalancer.choose(request).block().getServer();14
15 // Step 3: Reconstruct the request with the real host:port16 URI resolvedUri = URI.create("http://" + instance.getHost() + ":" + instance.getPort()17 + request.getURI().getPath());18
19 // Step 4: Execute the actual HTTP request20 return execution.execute(new ResolvedRequest(request, resolvedUri), body);21}7. The Service ID Concept Critical Understanding
What Is a Service ID?
A Service ID is the identifier for a microservice — it is the value of spring.application.name in that service's application.properties.
1# In Product Service's application.properties2spring.application.name=product-serviceThe value product-service is the Service ID (also called client name). It is:
- Used to register the service with Eureka
- Used to look up instances from Eureka
- Used to identify which load-balancing algorithm applies to which service
The Key Rule Algorithm Is Attached to Service ID
Why This Matters in Practice
When you create a RoundRobinLoadBalancer or RandomLoadBalancer, the constructor requires a Service ID:
1// Each load balancer instance is created for ONE specific service2new RoundRobinLoadBalancer(serviceInstanceListSupplier, "product-service");3new RandomLoadBalancer(serviceInstanceListSupplier, "sales-service");This ties the algorithm to the service. When LoadBalancerClientFactory.getInstance("product-service") is called, it retrieves the load balancer registered for product-service only.
8. Default Algorithm Round Robin
What Round Robin Does
Round Robin distributes requests evenly across all available instances in a rotating sequence:
1Request 1 → Instance A (:8082)2Request 2 → Instance B (:8083)3Request 3 → Instance C (:8084)4Request 4 → Instance A (:8082) ← wraps around5Request 5 → Instance B (:8083)6...Default Behavior
By default, Spring Cloud Load Balancer uses Round Robin for every service — no configuration needed.
Built-In Algorithms
Spring Cloud Load Balancer ships with only two built-in algorithms:
| Algorithm | Class | Description |
|---|---|---|
| Round Robin | RoundRobinLoadBalancer | Cycles through instances in order (default) |
| Random | RandomLoadBalancer | Picks a random instance each time |
9. Overriding the Algorithm for a Specific Service
Goal
Change the load-balancing algorithm for one specific service (e.g., use RandomLoadBalancer for product-service only) while keeping Round Robin for everything else.
Step 1 Annotate the Application Class
In Order Service (the calling service), add @LoadBalancerClient:
1@SpringBootApplication2@LoadBalancerClient(3 name = "product-service", // Service ID this config applies to4 configuration = LoadBalancerProductConfig.class // Configuration class to use5)6public class OrderServiceApplication {7 public static void main(String[] args) {8 SpringApplication.run(OrderServiceApplication.class, args);9 }10}@LoadBalancerClient is placed on the calling service (Order Service), not the called service (Product Service). You are configuring how the caller handles load balancing for requests to product-service.Step 2 Write the Load Balancer Configuration Class
1// NOTE: Do NOT annotate this with @Configuration at the class level2// It must NOT be in the component scan path — it is loaded by Spring Cloud specifically3public class LoadBalancerProductConfig {4
5 @Bean6 public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(7 Environment environment,8 LoadBalancerClientFactory loadBalancerClientFactory) {9
10 // Get the service ID this config is running for11 String serviceId = environment.getProperty(12 LoadBalancerClientFactory.PROPERTY_NAME // = "loadbalancer.client.name"13 );14 // At runtime, serviceId = "product-service"15
16 // Create the ServiceInstanceListSupplier (handles Eureka calls)17 ObjectProvider<ServiceInstanceListSupplier> supplier =18 loadBalancerClientFactory.getLazyProvider(serviceId, ServiceInstanceListSupplier.class);19
20 // Return RandomLoadBalancer tied to "product-service"21 return new RandomLoadBalancer(supplier, serviceId);22 }23}Why This Config Class Is Different
@Configuration and scan it normally. It must be referenced only through @LoadBalancerClient(configuration = ...). If Spring scans it as a normal @Configuration, it will be applied globally to all services, not just product-service.| Aspect | Normal @Configuration | Load Balancer Config |
|---|---|---|
| When beans are created | At application startup | At runtime (when service is first called) |
| Scope | Application-wide | Per service ID |
| Scanning | Auto-scanned | Only via @LoadBalancerClient |
Step 3 Use the Service Name in the URL (No Change Needed)
1// No change to the calling code — it still uses the service name2String response = restTemplate.getForObject(3 "http://product-service/product/" + id,4 String.class5);6// But now RandomLoadBalancer is used when selecting among product-service instances10. Global + Per-Service Configuration Combined
Scenario
You have many services. For some you want specific algorithms, for the rest you want a common default:
1product-service → Random (specific)2sales-service → Round Robin (default)3inventory-service → Round Robin (default)4xyz-service → Round Robin (default)Step 1 Use `@LoadBalancerClients` (Plural)
1@SpringBootApplication2@LoadBalancerClients(3 // Specific configuration for product-service4 value = {5 @LoadBalancerClient(6 name = "product-service",7 configuration = LoadBalancerProductConfig.class8 )9 // Add more @LoadBalancerClient entries for other specific services10 },11 // Default configuration for ALL other services12 defaultConfiguration = LoadBalancerGlobalConfig.class13)14public class OrderServiceApplication {15 public static void main(String[] args) {16 SpringApplication.run(OrderServiceApplication.class, args);17 }18}Step 2 Write the Global (Default) Configuration
The global config is trickier because it applies to any service — and we don't know the service name at compile time. The service ID must be resolved dynamically at runtime.
1public class LoadBalancerGlobalConfig {2
3 @Bean4 @ConditionalOnMissingBean // ← CRITICAL — explained below5 public ReactorLoadBalancer<ServiceInstance> roundRobinLoadBalancer(6 Environment environment,7 LoadBalancerClientFactory loadBalancerClientFactory) {8
9 // Dynamically get the service ID at runtime10 // (NOT hardcoded — different service = different value)11 String serviceId = environment.getProperty(12 LoadBalancerClientFactory.PROPERTY_NAME13 );14 // When invoked for "sales-service", serviceId = "sales-service"15 // When invoked for "inventory-service", serviceId = "inventory-service"16
17 ObjectProvider<ServiceInstanceListSupplier> supplier =18 loadBalancerClientFactory.getLazyProvider(serviceId, ServiceInstanceListSupplier.class);19
20 // Round Robin tied to whatever service is being called right now21 return new RoundRobinLoadBalancer(supplier, serviceId);22 }23}Why `@ConditionalOnMissingBean` Is Critical
@ConditionalOnMissingBean, when product-service is called:
1. Spring first runs LoadBalancerProductConfig → creates RandomLoadBalancer for product-service
2. Spring then runs LoadBalancerGlobalConfig → tries to create another RoundRobinLoadBalancer for product-service
3. Two load balancers for the same service ID → Runtime Exception
@ConditionalOnMissingBean says: "Only create this bean if no load balancer bean already exists for this service ID." This prevents the duplicate.Configuration Priority Order
When a service is called, Spring Cloud applies configurations in this order:
11. Specific @LoadBalancerClient config (highest priority)2 → e.g., LoadBalancerProductConfig for "product-service"3
42. Default @LoadBalancerClients(defaultConfiguration=...) config5 → e.g., LoadBalancerGlobalConfig for all other services6
73. Spring Cloud Load Balancer auto-configuration defaults8 → RoundRobin for everything (lowest priority)11. Writing a Custom Load Balancer
When You Need This
Spring Cloud Load Balancer only has two built-in algorithms (Round Robin and Random). If you need:
- Weighted distribution
- Least connections
- Least response time
- IP hash / sticky sessions
- Any custom logic
You must write a custom load balancer.
Step 1 Implement `ReactorServiceInstanceLoadBalancer`
1public class CustomLoadBalancer implements ReactorServiceInstanceLoadBalancer {2
3 private final ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;4 private final String serviceId;5
6 // Constructor — same signature as RoundRobinLoadBalancer and RandomLoadBalancer7 public CustomLoadBalancer(8 ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,9 String serviceId) {10 this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;11 this.serviceId = serviceId;12 }13
14 @Override15 public Mono<Response<ServiceInstance>> choose(Request request) {16
17 // Step 1: Get the ServiceInstanceListSupplier18 ServiceInstanceListSupplier supplier =19 serviceInstanceListSupplierProvider.getIfAvailable();20
21 // Step 2: Get all available instances from Service Discovery22 return supplier.get(request)23 .next()24 .map(instances -> pickInstance(instances, request));25 }26
27 private Response<ServiceInstance> pickInstance(28 List<ServiceInstance> instances, Request request) {29
30 // Step 3: Handle empty instance list31 if (instances == null || instances.isEmpty()) {32 return new EmptyResponse();33 }34
35 // Step 4: Apply your custom selection logic36 // Example: always pick the first instance (replace with real logic)37 ServiceInstance chosen = instances.get(0);38
39 // Examples of real custom logic you could implement:40 // - Weighted: pick based on instance metadata weights41 // - Least connections: track active connections per instance42 // - Response time: track average latency per instance43 // - Geographic: pick instance closest to client's region44
45 return new DefaultResponse(chosen);46 }47}Class Hierarchy
Step 2 Register It in Configuration
1public class LoadBalancerProductConfig {2
3 @Bean4 public ReactorLoadBalancer<ServiceInstance> customLoadBalancer(5 Environment environment,6 LoadBalancerClientFactory loadBalancerClientFactory) {7
8 String serviceId = environment.getProperty(9 LoadBalancerClientFactory.PROPERTY_NAME10 );11
12 ObjectProvider<ServiceInstanceListSupplier> supplier =13 loadBalancerClientFactory.getLazyProvider(serviceId, ServiceInstanceListSupplier.class);14
15 // Use custom load balancer instead of built-in ones16 return new CustomLoadBalancer(supplier, serviceId);17 }18}Step 3 Register via `@LoadBalancerClient`
1@SpringBootApplication2@LoadBalancerClient(3 name = "product-service",4 configuration = LoadBalancerProductConfig.class5)6public class OrderServiceApplication { ... }How `choose()` Works Internally (for reference)
| Algorithm | What choose() does |
|---|---|
RoundRobinLoadBalancer | Gets instances list → picks next using atomic counter (cycles through) |
RandomLoadBalancer | Gets instances list → calls Random.nextInt(instances.size()) |
CustomLoadBalancer | Gets instances list → applies your logic |
12. Load Balancing with FeignClient
How FeignClient Uses Load Balancing
When you use FeignClient with Service Discovery, load balancing is automatically applied — you don't need @LoadBalanced or manual configuration. FeignClient internally uses the same LoadBalancerInterceptor infrastructure.
Basic FeignClient Setup (With Service Discovery)
1@FeignClient(name = "product-service") // service name = service ID2public interface ProductClient {3
4 @GetMapping("/product/{id}")5 String getProduct(@PathVariable("id") String id);6}1@RestController2public class OrderController {3
4 @Autowired5 private ProductClient productClient; // Spring generates implementation6
7 @GetMapping("/order/{id}")8 public String getOrder(@PathVariable String id) {9 return "Order: " + productClient.getProduct(id);10 // ↑ Internally uses Round Robin to pick among product-service instances11 }12}Changing the Algorithm for FeignClient
The mechanism is identical to RestTemplate — use @LoadBalancerClient:
1@SpringBootApplication2@LoadBalancerClient(3 name = "product-service",4 configuration = LoadBalancerProductConfig.class // same config as before5)6@EnableFeignClients7public class OrderServiceApplication { ... }1// LoadBalancerProductConfig — same as written before2public class LoadBalancerProductConfig {3
4 @Bean5 public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(6 Environment environment,7 LoadBalancerClientFactory loadBalancerClientFactory) {8
9 String serviceId = environment.getProperty(10 LoadBalancerClientFactory.PROPERTY_NAME11 );12 ObjectProvider<ServiceInstanceListSupplier> supplier =13 loadBalancerClientFactory.getLazyProvider(serviceId, ServiceInstanceListSupplier.class);14
15 return new RandomLoadBalancer(supplier, serviceId);16 }17}RestTemplate, RestClient, or FeignClient). The same @LoadBalancerClient configuration applies equally to all of them.FeignClient Without Service Discovery
If you are NOT using Eureka, you must provide the URL explicitly:
1@FeignClient(name = "product-service", url = "http://localhost:8082")2public interface ProductClient { ... }3// No load balancing — URL is fixed13. Load Balancing with RestClient
Same Infrastructure, Different HTTP Client
RestClient (Spring 6.1+) uses the exact same LoadBalancerInterceptor as RestTemplate. The load balancing logic is completely identical.
1@Configuration2public class AppConfig {3
4 @Bean5 @LoadBalanced // Same annotation6 public RestClient.Builder restClientBuilder() {7 return RestClient.builder();8 }9}1@RestController2public class OrderController {3
4 @Autowired5 private RestClient.Builder restClientBuilder;6
7 @GetMapping("/order/{id}")8 public String getOrder(@PathVariable String id) {9
10 return restClientBuilder.build()11 .get()12 .uri("http://product-service/product/" + id) // Same service-name URL13 .retrieve()14 .body(String.class);15 }16}@LoadBalancerClient, custom load balancers, global configs) work identically for RestTemplate, RestClient, and FeignClient. You configure once, it applies regardless of which HTTP client is used.14. Load Balancer Configuration Lazy Loading at Runtime
Why Load Balancer Config Is Lazy
This is a critical behavioral difference between normal Spring beans and load balancer configuration beans.
| Bean Type | When Created |
|---|---|
Normal @Configuration beans | At application startup |
| Load Balancer configuration beans | At runtime, when the service is first called |
Why This Matters for the Global Config
1// Global config — serviceId is resolved at RUNTIME2String serviceId = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);During application startup, Order Service doesn't know which other services it will call. product-service, sales-service, etc. are not "invoked" yet — they're just names. So:
- At startup:
serviceIdwould benull(no service is being called yet) - At runtime (when
http://product-service/...is first invoked):serviceId="product-service" - At runtime (when
http://sales-service/...is first invoked):serviceId="sales-service"
Load Balancer Bean Lifecycle
15. Common Mistakes
Mistake 1 Scanning the Load Balancer Config Class
1// ❌ WRONG — do NOT annotate load balancer config with @Configuration2// at the package level where Spring scans3@Configuration4public class LoadBalancerProductConfig { ... }5// This applies the config GLOBALLY to ALL services, not just product-service6
7// ✅ CORRECT — reference it only via @LoadBalancerClient8// Do NOT put @Configuration on the class, or exclude it from component scan9public class LoadBalancerProductConfig { ... }10
11@LoadBalancerClient(name = "product-service", configuration = LoadBalancerProductConfig.class)Mistake 2 Forgetting `@ConditionalOnMissingBean` in Global Config
1// ❌ WRONG — global config without @ConditionalOnMissingBean2public class LoadBalancerGlobalConfig {3 @Bean4 public ReactorLoadBalancer<ServiceInstance> roundRobin(...) { ... }5}6// When product-service is called: RandomLoadBalancer (from specific config) +7// RoundRobinLoadBalancer (from global config) = RUNTIME EXCEPTION8
9// ✅ CORRECT10public class LoadBalancerGlobalConfig {11 @Bean12 @ConditionalOnMissingBean // ← Skip if a load balancer already exists for this serviceId13 public ReactorLoadBalancer<ServiceInstance> roundRobin(...) { ... }14}Mistake 3 Hardcoding Service ID in Global Config
1// ❌ WRONG — hardcoded service ID in global config2return new RoundRobinLoadBalancer(supplier, "product-service");3// This global config would only work for product-service, not for sales-service etc.4
5// ✅ CORRECT — resolve dynamically at runtime6String serviceId = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);7return new RoundRobinLoadBalancer(supplier, serviceId);Mistake 4 Using `@LoadBalanced` Without Service Discovery
1// ❌ WRONG — @LoadBalanced with hardcoded IP (no service registry)2// @LoadBalanced RestTemplate tries to resolve "192.168.1.5" as a service name3restTemplate.getForObject("http://192.168.1.5:8082/product/1", String.class);4// This will FAIL — the interceptor treats "192.168.1.5" as a service ID and5// looks it up in Service Discovery (Eureka), where it won't be found6
7// ✅ CORRECT — use service name, register with Eureka8restTemplate.getForObject("http://product-service/product/1", String.class);Mistake 5 Not Adding the Load Balancer Dependency
1// ❌ WRONG — @LoadBalanced does nothing without the dependency2// The annotation exists in Spring Cloud Commons, but the actual3// LoadBalancerInterceptor requires spring-cloud-starter-loadbalancer4
5// ✅ CORRECT — add to pom.xml6<dependency>7 <groupId>org.springframework.cloud</groupId>8 <artifactId>spring-cloud-starter-loadbalancer</artifactId>9</dependency>16. Best Practices
| Practice | Reason |
|---|---|
Always use spring.application.name consistently | Service ID must match exactly between the caller's config and the service's registration |
| Keep load balancer config classes outside the component scan | Prevents accidental global application |
Always add @ConditionalOnMissingBean in global configs | Prevents duplicate bean exception when specific configs exist |
Use environment.getProperty(PROPERTY_NAME) for service ID in global config | Enables dynamic per-service algorithm binding at runtime |
| Prefer FeignClient for new Spring Cloud projects | More declarative, cleaner code, same load balancing capability |
| Test load balancing by running multiple instances locally | Verify round-robin or random behavior with logs |
| Use Istio/service mesh for advanced algorithms | Weighted, least connections, circuit breaking at infrastructure level |
Don't mix @LoadBalanced RestTemplate with hardcoded IPs | Will fail — the interceptor treats hostname as a service ID |
17. Interview Notes
Q: What is the difference between server-side and client-side load balancing?
Server-side: a dedicated external load balancer (NGINX, AWS ALB) receives all requests and forwards them. The client knows nothing about individual instances. Client-side: the calling service itself contains the load-balancing logic, queries Service Discovery for instances, and picks one using an algorithm.
Q: What does `@LoadBalanced` do?
It instructs Spring to add a LoadBalancerInterceptor to the RestTemplate (or RestClient). This interceptor intercepts every request, resolves the service name in the URL via Service Discovery, applies the configured load-balancing algorithm, and replaces the URL with the selected instance's real host:port.
Q: What is a Service ID in Spring Cloud Load Balancer?
The Service ID (or client name) is the value of spring.application.name of the target service. It is the key used to: register with Eureka, look up instances from Eureka, and bind a specific load-balancing algorithm to a specific service.
Q: What algorithms does Spring Cloud Load Balancer support out of the box?
Only two: Round Robin (RoundRobinLoadBalancer) and Random (RandomLoadBalancer). For other algorithms (weighted, least connections, etc.), you must write a custom implementation or use a service mesh like Istio.
Q: Why do load balancer configuration beans load at runtime, not at startup?
Because at startup, no service calls have been made yet. The Service ID is only known when a call is actually in flight. The global config especially must resolve the service ID dynamically — at startup it would be null because no service is being invoked yet.
Q: What is `ServiceInstanceListSupplier`?
It is the component that calls Service Discovery (Eureka) to retrieve the list of available instances for a given service ID. It is injected into every load balancer algorithm and provides the instance list that the algorithm selects from.
Q: Why must the load balancer config class not be in the component scan path?
If it is scanned as a normal @Configuration, it becomes a global application-level bean and applies its algorithm to ALL services. It should only be activated for the specific service named in @LoadBalancerClient.
Q: How do you use a different load-balancing algorithm for just one service?
Use @LoadBalancerClient(name = "service-name", configuration = YourConfig.class) on the main application class. In YourConfig, return the desired ReactorLoadBalancer bean. This config loads lazily at runtime only when that service is called.
Q: How does load balancing work transparently with FeignClient?
FeignClient automatically integrates with Spring Cloud Load Balancer when Service Discovery is on the classpath. No extra annotation is needed. Algorithm customization uses the same @LoadBalancerClient mechanism as RestTemplate.
18. Practice Questions
Easy
- What is the purpose of load balancing? What problem does it solve?
- What is the difference between server-side and client-side load balancing? Give one example of each.
- What annotation enables load balancing in a
RestTemplatebean? - What are the two built-in algorithms in Spring Cloud Load Balancer?
- What is a Service ID? What property defines it?
Medium
- Trace what happens internally when
restTemplate.getForObject("http://product-service/product/1", String.class)is called with@LoadBalanced. - How do you configure
RandomLoadBalancerforproduct-servicewhile keeping Round Robin for all other services? - Why must the load balancer configuration class not be annotated with
@Configurationand placed in the component scan path? - Explain why
@ConditionalOnMissingBeanis required in the global load balancer config. - Why is the service ID resolved dynamically at runtime in the global config instead of being hardcoded?
Hard
- Implement a custom
WeightedLoadBalancerthat reads aweightmetadata value from eachServiceInstanceand selects instances proportionally to their weight. - Explain the full lifecycle of a load balancer bean: when is it created, when is it cached, and when would it be recreated?
- You have five downstream services. Three use Round Robin, one uses Random, and one uses a custom algorithm. Write the complete
@LoadBalancerClientsconfiguration for this setup. - What would happen if you called
http://192.168.1.5:8082/product/1with a@LoadBalancedRestTemplate? Why would it fail? - Compare Spring Cloud Load Balancer with Istio service mesh as client-side load balancing solutions. When would you choose each?
19. Summary Revision Bullets
- Load balancing = distributing traffic across multiple service instances to prevent overload
- Server-side = dedicated external LB server (NGINX, AWS ALB); client is unaware of instances
- Client-side = LB logic lives inside the caller; requires Service Discovery to get instance list
- Spring Cloud Load Balancer = Spring's client-side LB library; integrates with RestTemplate, RestClient, FeignClient
@LoadBalancedonRestTemplatebean → installsLoadBalancerInterceptor→ intercepts requests → resolves service name → picks instance → replaces URL- URL format with load balancing:
http://service-name/path(nothttp://host:port/path) - Service ID =
spring.application.namevalue = key that binds algorithm to service - Each algorithm is tied to exactly one Service ID — not global across all services
- Default algorithm = Round Robin for every service
- Built-in algorithms:
RoundRobinLoadBalancer,RandomLoadBalancer— that's it - Custom algorithm: implement
ReactorServiceInstanceLoadBalancer, overridechoose()method - Per-service config:
@LoadBalancerClient(name="product-service", configuration=Config.class) - Global + per-service:
@LoadBalancerClients(value={specific...}, defaultConfiguration=GlobalConfig.class) @ConditionalOnMissingBeanin global config = prevents duplicate algorithm for same service ID- Dynamic service ID in global config:
environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME)— null at startup, resolved at runtime - Load balancer config beans = lazy — created at runtime on first call to a service, not at startup
- FeignClient: load balancing is automatic with Service Discovery; customize with same
@LoadBalancerClient - RestClient: same
@LoadBalancedannotation, same interceptor, same config — identical behavior to RestTemplate - Istio: service mesh alternative for advanced algorithms (weighted, least connections); operates as sidecar
System.out.println statements inside your load balancer config beans and run multiple instances of Product Service locally. Call the Order Service repeatedly and observe which instance is selected each time — this makes the round-robin and random behaviors concrete.Mastery check
How well can you recall this?
Finished this lesson?