Video in progress

Strong Middle 🧩 Microservices

What is the difference between a connect timeout and a read timeout, and what happens in prod if you set no timeout at all?

The connect timeout is how long you wait for the TCP connection to be established; the read (response) timeout is how long you wait for a response after connecting. Without timeouts, a hung downstream holds your threads forever and the service stops completely.

📖 Answer

In many HTTP clients the read timeout is infinite or very large by default. If you create a RestTemplate with a plain new RestTemplate(), it runs on the JDK HttpURLConnection and the default timeouts are 0, meaning wait forever.

In prod it looks like this: the downstream stops responding but doesn't drop the connection either. Every incoming request takes one Tomcat thread and sits waiting for a response. All 200 threads get used up, the service stops answering even the health check, and Kubernetes restarts it. The problem was in the downstream.

Setting the timeouts explicitly for RestClient in Boot 3.x:

@Bean
RestClient inventoryClient(RestClient.Builder builder) {
    var settings = ClientHttpRequestFactorySettings.defaults()   // org.springframework.boot.http.client
        .withConnectTimeout(Duration.ofMillis(500))
        .withReadTimeout(Duration.ofSeconds(2));
    return builder
        .baseUrl("http://inventory-service")
        .requestFactory(ClientHttpRequestFactoryBuilder.detect().build(settings))
        .build();
}

This is the Boot 3.4+ API. In Boot 3.0–3.3 the same thing was done with ClientHttpRequestFactories.get(ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(...).withReadTimeout(...)) (deprecated in 3.4). From Boot 3.4, the simple case needs no code at all: spring.http.client.connect-timeout and spring.http.client.read-timeout.

The connect timeout is usually short: 200–500 ms is enough inside a cluster. The read timeout is chosen from the downstream's p99 time, not as "about 30 seconds". One more thing: the time you wait to get a connection from the connection pool is a separate timeout too. In Apache HttpClient it is connectionRequestTimeout.