spring-cloud-netflix icon indicating copy to clipboard operation
spring-cloud-netflix copied to clipboard

@LoadBalanced not working with RestClient spring boot 4, Java 21

Open Ali-thepro opened this issue 10 months ago • 6 comments

Hi, I have a simple consumer & provider setup and I am using eureka for service discovery. I'm just trying out all the RestClients and using @LoadBalanced annotation with them. RestTemplate and WebClient work fine but for RestClient I keep getting this error. I've pasted my code below for the consumer for restClient. Could I have some help please, I would really appreciate it.

2026-01-07T12:03:16.073Z  INFO 54010 --- [consumer] [reshExecutor-%d] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2026-01-07T12:03:16.075Z  WARN 54010 --- [consumer] [beatExecutor-%d] o.s.c.l.core.RoundRobinLoadBalancer      : No servers available for service: localhost
2026-01-07T12:03:16.076Z  INFO 54010 --- [consumer] [beatExecutor-%d] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://localhost:8761/eureka/}, exception=No instances available for localhost stacktrace=java.lang.IllegalStateException: No instances available for localhost
	at org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient.execute(BlockingLoadBalancerClient.java:78)
	at org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor.intercept(LoadBalancerInterceptor.java:55)
	at org.springframework.cloud.client.loadbalancer.DeferringLoadBalancerInterceptor.intercept(DeferringLoadBalancerInterceptor.java:54)
	at org.springframework.http.client.ClientHttpRequestInterceptor.lambda$andThen$0(ClientHttpRequestInterceptor.java:76)
	at org.springframework.http.client.ClientHttpRequestInterceptor.lambda$apply$0(ClientHttpRequestInterceptor.java:89)
	at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:73)
	at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:50)
	at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:80)
	at org.springframework.web.client.DefaultRestClient$DefaultRequestBodyUriSpec.exchangeInternal(DefaultRestClient.java:609)
	at org.springframework.web.client.DefaultRestClient$DefaultRequestBodyUriSpec.exchange(DefaultRestClient.java:567)
	at org.springframework.web.client.RestClient$RequestHeadersSpec.exchange(RestClient.java:750)
	at org.springframework.web.client.DefaultRestClient$DefaultResponseSpec.executeAndExtract(DefaultRestClient.java:896)
	at org.springframework.web.client.DefaultRestClient$DefaultResponseSpec.toEntityInternal(DefaultRestClient.java:842)
	at org.springframework.web.client.DefaultRestClient$DefaultResponseSpec.toEntity(DefaultRestClient.java:831)
	at org.springframework.cloud.netflix.eureka.http.RestClientEurekaHttpClient.sendHeartBeat(RestClientEurekaHttpClient.java:91)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
	at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.executeOnNewServer(RedirectingEurekaHttpClient.java:121)
	at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.execute(RedirectingEurekaHttpClient.java:80)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
	at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:120)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92)
	at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:76)
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89)
	at com.netflix.discovery.DiscoveryClient.renew(DiscoveryClient.java:845)
	at com.netflix.discovery.DiscoveryClient$HeartbeatThread.run(DiscoveryClient.java:1403)
	at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
	at java.base/java.lang.Thread.run(Thread.java:1583)

2026-01-07T12:03:16.076Z  WARN 54010 --- [consumer] [beatExecutor-%d] c.n.d.s.t.d.RetryableEurekaHttpClient    : Request execution failed with message: No instances available for localhost
2026-01-07T12:03:16.076Z ERROR 54010 --- [consumer] [beatExecutor-%d] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_CONSUMER/10.255.255.254:consumer:8080 - was unable to send heartbeat!

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
	at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112) ~[eureka-client-2.0.5.jar:2.0.5]
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) ~[eureka-client-2.0.5.jar:2.0.5]
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92) ~[eureka-client-2.0.5.jar:2.0.5]
	at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:76) ~[eureka-client-2.0.5.jar:2.0.5]
	at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) ~[eureka-client-2.0.5.jar:2.0.5]
	at com.netflix.discovery.DiscoveryClient.renew(DiscoveryClient.java:845) ~[eureka-client-2.0.5.jar:2.0.5]
	at com.netflix.discovery.DiscoveryClient$HeartbeatThread.run(DiscoveryClient.java:1403) ~[eureka-client-2.0.5.jar:2.0.5]
	at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572) ~[na:na]
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317) ~[na:na]
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) ~[na:na]
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) ~[na:na]
	at java.base/java.lang.Thread.run(Thread.java:1583) ~[na:na]

package com.demo.consumer.restclient;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;

@Configuration
public class RestClientConfig {

    @Bean
    @LoadBalanced
    public RestClient.Builder loadbalancedRestClientBuilder() {
        return RestClient.builder();
    }

    @Bean
    public RestClient restClient(@LoadBalanced RestClient.Builder builder) {
        return builder.baseUrl("http://provider")
                .build();
    }
}
package com.demo.consumer.restclient;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

@Service
@RequiredArgsConstructor
public class ProviderRestClient {
    private final RestClient restClient;

    public String getInstanceInfo() {
        return restClient.get()
                .uri("/instance-info")
                .retrieve()
                .body(String.class);
    }
}
package com.demo.consumer.restclient;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/rest-client")
public class RestClientController {

    private final ProviderRestClient providerRestClient;

    public RestClientController(ProviderRestClient providerRestClient) {
        this.providerRestClient = providerRestClient;
    }

    @GetMapping("/instance")
    public String getInstance(){
//        RestClient restClient = RestClient.create();
//        String response = restClient.get()
//                .uri("http://localhost:8081/instance-info")
//                .retrieve()
//                .body(String.class);
        return providerRestClient.getInstanceInfo();
    }
}
spring:
  application:
    name: consumer

server:
  port: 8080

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
    register-with-eureka: true
    fetch-registry: true

Ali-thepro avatar Jan 07 '26 12:01 Ali-thepro

This code below allowed it to work

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

    @Bean
    @Primary
    public RestClient.Builder directRestClientBuilder() {
        return RestClient.builder();
    }

    @Bean
    @Primary
    public RestClient serviceRestClient(
            @Qualifier("lbRestClientBuilder") RestClient.Builder builder) {

        return builder.baseUrl("http://provider").build();
    }

    @Bean
    public RestClient directRestClient(
            @Qualifier("directRestClientBuilder") RestClient.Builder builder) {

        return builder.build();
    }
}

But I am not sure what is going on and why it is an issue in the first place. Can anyone care to explain please.

Ali-thepro avatar Jan 07 '26 12:01 Ali-thepro

Hi, I have same issue for restClient. Repair by @Ali-thepro solution.

Thanks

SzymonZasada avatar Jan 24 '26 17:01 SzymonZasada

I think I could help solve the problem, can I help?

marcelopinotti avatar Mar 06 '26 00:03 marcelopinotti

Having the same issue and the above workaround by @Ali-thepro works.

@marcelopinotti, I am not speaking on behalf of the spring-cloud team, but contributions are always welcome; please submit your pull request.

kvmw avatar Mar 25 '26 09:03 kvmw

@LoadBalanced with RestClient — the problem and the fix

Spring Boot 4.1.1 · Spring Cloud 2025.1.2 · Eureka

The problem

You add a @LoadBalanced RestClient.Builder, expecting it to work the way @LoadBalanced RestTemplate always did. Instead your application never registers with Eureka, and the log repeats:

java.lang.IllegalStateException: No instances available for localhost
WARN  ... DiscoveryClient : registration failed Cannot execute request on any known server
ERROR ... DiscoveryClient : was unable to send heartbeat!

The application still starts, which is what makes it confusing — it just silently never appears in the registry.

Why it happens

The Eureka client needs an HTTP client for its own calls to the registry, and it looks for a RestClient.Builder in your application context:

// DiscoveryClientOptionalArgsConfiguration.RestClientConfiguration
ObjectProvider<RestClient.Builder> restClientBuilderProvider
...
() -> restClientBuilderProvider.getIfAvailable(RestClient::builder);

If the only RestClient.Builder bean you have is the @LoadBalanced one, Eureka finds and uses it. Its calls to http://localhost:8761/eureka then go through the load balancer, which tries to resolve localhost as a service id and fails.

Two details make this easy to hit:

  • LoadBalancerRestClientBuilderBeanPostProcessor has already added the load balancer interceptor to that builder instance, so anything resolving the bean inherits the interceptor.
  • Declaring any RestClient.Builder bean suppresses Boot's auto-configured one (RestClientAutoConfiguration#restClientBuilder is @ConditionalOnMissingBean), which removes the plain fallback candidate and leaves the load-balanced builder as the only match.

The fix

Keep a second, plain @Primary builder so the Eureka transport has an ordinary candidate to find, and ask for the load-balanced one explicitly by qualifier:

@Configuration
public class RestClientConfig {

    /** Plain and @Primary — this is the one the Eureka transport picks up. */
    @Bean
    @Primary
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RestClient.Builder restClientBuilder(RestClientBuilderConfigurer configurer) {
        return configurer.configure(RestClient.builder());
    }

    /** Load-balanced — gets the interceptor from the bean post processor. */
    @Bean
    @LoadBalanced
    public RestClient.Builder loadBalancedRestClientBuilder(RestClientBuilderConfigurer configurer) {
        return configurer.configure(RestClient.builder());
    }

    /** Note the @LoadBalanced on the parameter — see rule 2 below. */
    @Bean
    public RestClient serviceARestClient(@LoadBalanced RestClient.Builder builder) {
        return builder.baseUrl("http://SERVICE-A").build();
    }
}

With this in place, registration succeeds and requests round-robin correctly across instances.

Two rules to remember

1. Don't delete the plain builder. It looks like dead code. It is the entire fix — it exists so the Eureka transport has something non-load-balanced to resolve.

2. @LoadBalanced must also be on the injection point.

// WRONG — compiles, runs, quietly does no load balancing
public RestClient serviceARestClient(RestClient.Builder loadBalancedRestClientBuilder) { ... }

// RIGHT
public RestClient serviceARestClient(@LoadBalanced RestClient.Builder builder) { ... }

Naming the parameter after the bean does not select it. DefaultListableBeanFactory#determineAutowireCandidate checks for a @Primary candidate first and only falls back to parameter-name matching afterwards, so the plain builder wins. @LoadBalanced is itself a @Qualifier, which is why putting it on the parameter works.

Why RestTemplate never had this problem

@LoadBalanced RestTemplate @LoadBalanced RestClient.Builder
Load balancing works yes yes
Eureka registration affected no yes — needs the extra plain builder
Why Eureka's transport doesn't consume RestTemplate beans Eureka's transport resolves RestClient.Builder by type

WebClient.Builder is resolved the same way as RestClient.Builder, but only when eureka.client.webclient.enabled=true, so a default setup never reaches that path.

Dependency note

RestClientBuilderConfigurer is org.springframework.boot.restclient.autoconfigure.RestClientBuilderConfigurer and comes from the spring-boot-restclient module. On Boot 4, spring-boot-starter-webmvc does not bring it in, so add:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-restclient</artifactId>
</dependency>

Without it there is no auto-configured RestClient.Builder at all, and the snippet above won't compile.

Upstream

Reported in spring-cloud-netflix#4524 and spring-cloud-commons#1633. Both open at the time of writing — check them before assuming this workaround is still needed.

hayattarique avatar Aug 27 '26 13:08 hayattarique

I looked into this and can confirm the root cause in DiscoveryClientOptionalArgsConfiguration (both the RestClientConfiguration and WebClientConfiguration inner classes):

public RestClientDiscoveryClientOptionalArgs restClientDiscoveryClientOptionalArgs(
        TlsProperties tlsProperties,
        EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier,
        ObjectProvider<RestClient.Builder> restClientBuilderProvider) {
    ...
    () -> restClientBuilderProvider.getIfAvailable(RestClient::builder)
    ...
}

ObjectProvider<RestClient.Builder>.getIfAvailable(...) resolves by type only, so when the only RestClient.Builder bean in the context is the @LoadBalanced one, Eureka's own transport picks it up and its calls to the registry get routed through the load balancer, which can't resolve localhost/the registry host as a service id. The WebClient path (WebClientConfiguration#webClientDiscoveryClientOptionalArgs) has the same shape and is reachable whenever eureka.client.webclient.enabled=true.

Since spring-cloud-netflix-eureka-client already depends on spring-cloud-commons (which declares @LoadBalanced), one fix that doesn't require any config from the user is to resolve the builder while explicitly excluding beans annotated @LoadBalanced, e.g. by looking up bean names for RestClient.Builder/WebClient.Builder via the ListableBeanFactory and filtering out ones carrying @LoadBalanced, falling back to RestClient.Builder::new / WebClient.Builder::new if none remain.

Before I put together a PR: does that approach match what you'd want here, or would you rather see a dedicated qualifier/property that users set explicitly instead of Eureka auto-detecting a non-load-balanced builder? Happy to send a PR for the first approach if there's no objection — want to check before spending time on an approach that might not fit the intended design.

jejes323 avatar Aug 31 '26 05:08 jejes323