Video in progress

Strong Middle 🌱 Spring

What happens if you don't set timeouts on external HTTP calls, and how do you configure them in RestClient?

A service that isn't responding holds your threads forever: Tomcat runs out of threads, and even though the problem is in one external API, the whole app freezes. Set connect and read timeouts explicitly on every client.

📖 Answer

Here's how it plays out in prod: the payment provider slows down and starts answering in 2 minutes. Every checkout request holds a Tomcat thread for 2 minutes. All 200 threads are gone in a few seconds — now even the home page won't load. That's a cascading failure.

@Bean
RestClient paymentClient(RestClient.Builder builder) {
    var settings = ClientHttpRequestFactorySettings.defaults()
            .withConnectTimeout(Duration.ofSeconds(2))
            .withReadTimeout(Duration.ofSeconds(5));
    return builder
            .baseUrl("https://api.pay.uz")
            .requestFactory(ClientHttpRequestFactoryBuilder.detect().build(settings))
            .build();
}

(The API differs a bit depending on the Boot version; Boot 3.4+ also has the spring.http.client.connect-timeout/read-timeout properties.)

How to pick the values:

  • connect — short (1–3 s): a connection is usually established in milliseconds;
  • read — a bit above the external service's p99 response time;
  • the total time for the whole operation (including retries) shouldn't exceed what the user is willing to wait.

You can add two more protections on top: a circuit breaker (Resilience4j) temporarily stops sending requests to a service that keeps failing and returns a fallback right away; a bulkhead limits the number of parallel calls going to one external service.