Manoj Majumdar
Manoj Majumdar

Reputation: 525

Decrease initial lag in webclient call

I am currently using Webclient of spring-webflux package to make synchronous REST calls.

But the time taken to mae the first request is longer than the time taken by RestTemplate.

I have observed that the successive calls take much lesser time and more or less same to that of RestTemplate.

Is there a solution to decrease the initial lag for Webclient?

Upvotes: 1

Views: 2025

Answers (2)

shenali
shenali

Reputation: 11

I followed the recommended method mentioned in the official documentation and tried using:

HttpClient client = HttpClient.create();
client.warmup().block();

However, this approach didn't result in a significant latency reduction. Then I used Jetty as a replacement for the default Netty dependency along with the WebClient.

To implement this, you need to add the following dependencies to your build.gradle or equivalent:

implementation 'org.eclipse.jetty:jetty-client'
implementation 'org.eclipse.jetty:jetty-reactive-httpclient'

Then, configure the WebClient bean with Jetty settings to call your external APIs:

@Bean
public WebClient webClient() throws Exception {
    SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
    HttpClient httpClient = new HttpClient(sslContextFactory);
    httpClient.setFollowRedirects(false);
    httpClient.setConnectTimeout(timeout); // ensure you've defined 'timeout'
    httpClient.start();

    final ClientHttpConnector connector = new JettyClientHttpConnector(httpClient);
    return WebClient.builder().clientConnector(connector).build();
}

By using Jetty with WebClient, I noticed an improvement in performance. Hope this would be helpful for anybody experiencing similar latency issues.

Upvotes: 1

Violeta Georgieva
Violeta Georgieva

Reputation: 2282

By default, the initialization of the HttpClient resources happens on demand. This means that the first request absorbs the extra time needed to initialize and load:

  • the event loop group
  • the host name resolver
  • the native transport libraries (when native transport is used)
  • the native libraries for the security (in case of OpenSsl)

You can preload these resources - check this documentation

Things that cannot be preloaded are:

  • host name resolution happens with the first request
  • in case a connection pool is used (the default) - with the first request, a connection to the URL is established, the subsequent requests to the same URL reuse the connections from the pool so they are faster.

Upvotes: 3

Related Questions