Video in progress

Strong Middle 🌱 Spring

How does a @LoadBalanced RestClient or WebClient work, and how does it differ from a Kubernetes Service?

@LoadBalanced adds an interceptor to the builder: the host in the URL (http://inventory) is treated as a service name, and Spring Cloud LoadBalancer gets the list of instances from discovery (Eureka, Consul or the Kubernetes API) and picks one. With a Kubernetes Service, the cluster network (kube-proxy) makes the choice.

📖 Answer

@Configuration
class ClientConfig {
    @Bean
    @LoadBalanced
    RestClient.Builder lbRestClientBuilder() {
        return RestClient.builder();
    }
}

@Service
class InventoryGateway {
    private final RestClient client;

    InventoryGateway(@LoadBalanced RestClient.Builder builder) {
        this.client = builder.baseUrl("http://inventory").build(); // a service name, not DNS
    }
}

What client-side balancing gives you: you control the choice yourself (round-robin, random, by zone), you route around a sick instance with retry (spring.cloud.loadbalancer.retry), and because the list is cached it keeps working even if discovery is down for a moment.

It has a cost too. Because of that cache, a new or removed pod shows up a few seconds late. And every service balances on its own, so settings and library versions have to be the same everywhere.

In Kubernetes, http://inventory:8080 works through a plain Service and you don't need @LoadBalanced at all. There's one trap: because of HTTP keep-alive, one connection stays tied to one pod, so the load spreads unevenly. In that case a service mesh, or limiting the maximum lifetime of connections, helps.

A common mistake: calling an external URL (https://api.payme.uz) from a @LoadBalanced builder. The host is looked up as a service name and isn't found. Use a separate, plain builder for external APIs.