Ch. 8 · Spring Boot

Spring Boot RestClient and WebClient Timeouts: How to Set Them

Set connect and read timeouts on Spring RestClient and WebClient, size them from a latency budget, and stop slow calls exhausting threads.

~7 min readadvancedupdated Nov 1, 2026

When a downstream API becomes slow, an outbound HTTP call without a timeout can block a request thread indefinitely, and enough blocked threads take your whole service down. Preventing that means knowing which timeout settings exist, what each one actually limits, and how to derive the values from a latency budget rather than picking “30 seconds” because it looks safe. The examples use RestClient (Spring Framework 6.1, Boot 3.2+) and WebClient, and the arithmetic assumes Tomcat’s default pool of 200 request threads.

Three timeouts every outbound call needs

Every outbound call needs at least a connect timeout and a read (response) timeout, and pooled clients also need a timeout for acquiring a connection from the pool. Connect timeout limits establishing the TCP (and TLS) connection; read timeout limits how long the client waits for data on an established socket. A socket read timeout resets whenever bytes arrive, so it does not cap total duration. Pick values from the caller’s budget: if your endpoint promises a 2-second p99 and calls two dependencies in sequence, each gets well under a second, including retries.

Where RestClient timeouts live, and what each one limits

RestClient delegates I/O to a ClientHttpRequestFactory. Timeouts live on that factory, not on RestClient itself.

@Configuration
class InventoryClientConfig {

    @Bean
    RestClient inventoryClient(RestClient.Builder builder) {
        HttpClient jdk = HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(500))      // TCP + TLS handshake
                .build();
        JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(jdk);
        factory.setReadTimeout(Duration.ofMillis(800));       // waiting for the response

        return builder
                .baseUrl("https://inventory.internal.example.com")
                .requestFactory(factory)
                .build();
    }
}
java

Injecting RestClient.Builder keeps Boot’s customizations: message converters, observation (metrics and tracing) and any RestClientCustomizer beans.

Here is what each timeout protects against:

Setting Fires when Typical cause
Connect timeout No TCP/TLS connection within the limit Host down, firewall dropping packets, wrong DNS
Read / response timeout No response data within the limit Slow query downstream, overloaded service
Pool acquisition timeout No free pooled connection Too many concurrent calls for the pool size

With Apache HttpClient 5 (HttpComponentsClientHttpRequestFactory), the pool acquisition timeout is connectionRequestTimeout. HttpClient 5 defaults it to three minutes, far longer than any request budget, so threads can queue for a connection long after every other timeout would have fired.

Without any configuration, the JDK client has no connect timeout, and the classic SimpleClientHttpRequestFactory uses HttpURLConnection defaults of infinite connect and read time. Spring Boot 3.4 added spring.http.client.connect-timeout and spring.http.client.read-timeout, which apply to the auto-configured RestClient.Builder and RestTemplateBuilder. Nothing is set until you configure them, and a request factory you build yourself, as above, ignores those properties.

Sizing timeouts from a 1.5-second checkout budget

Step 1: Write down the budget

Start from what your endpoint promises. Say GET /checkout/summary has a 1.5 s p99 target and calls pricing, then inventory, sequentially. Reserve 300 ms for your own work. That leaves 1.2 s, so roughly 600 ms each, including any retry.

Step 2: Choose connect and read timeouts

Connections inside a data centre establish in single-digit milliseconds; 200 to 500 ms is generous. If inventory’s own p99 is 250 ms, a 400 ms read timeout catches pathological calls while letting normal slow ones through.

inventory:
  connect-timeout: 300ms
  read-timeout: 400ms
yaml

Bind these into a @ConfigurationProperties record so they are typed Duration values and can be tuned per environment (see configuration properties).

Step 3: Bound the total duration

With socket-level read timeouts (SimpleClientHttpRequestFactory, Apache HttpClient’s response timeout), the timer resets on each received chunk, so a server that trickles one byte every 300 ms never trips a 400 ms read timeout. The JDK factory passes its read timeout to the JDK client as the request timeout, which in the JDK covers the wait for response headers; whether a slow body is also cut off depends on the Spring Framework version, so do not treat it as a total cap. For a hard cap that includes the body, use WebClient’s .timeout() operator:

Mono<Stock> stock = webClient.get()
        .uri("/stock/{sku}", sku)
        .retrieve()
        .bodyToMono(Stock.class)
        .timeout(Duration.ofMillis(600));   // whole operation, including body
java

With RestClient, a Resilience4j TimeLimiter or running the call on a bounded executor achieves the same.

Step 4: Budget retries and fail fast

One retry with a 400 ms read timeout means a worst case of about 800 ms plus backoff. Retry only idempotent calls, only on connect failures or 502, 503 and 504 responses, and with jittered backoff. Add a circuit breaker so that once inventory is clearly down, calls fail immediately instead of each waiting 400 ms.

@Retry(name = "inventory")                 // Resilience4j annotations
@CircuitBreaker(name = "inventory", fallbackMethod = "unknownStock")
public Stock stock(String sku) {
    return inventoryClient.get().uri("/stock/{sku}", sku).retrieve().body(Stock.class);
}
java

A fraud-scoring outage that took checkout down

Picture a checkout service that calls a fraud-scoring API with a RestTemplate built as new RestTemplate(). Then the fraud service’s database locks up, and its API accepts connections but never responds.

Each checkout request thread blocks in a socket read with no timeout (NioSocketImpl.read in a Java 17 thread dump). Within two minutes, all 200 Tomcat threads are stuck. Health checks time out, Kubernetes restarts pods, the new pods fill up in seconds, and checkout is down even though fraud scoring is an optional signal. A thread dump shows 200 threads with the same stack ending in the fraud client.

The fix has three layers. First, configure timeouts: connect 300 ms, read 700 ms. Second, wrap the call in a circuit breaker with a fallback that marks the order “score pending” for asynchronous review. Third, emit a metric per outcome (success, timeout, open circuit) and alert on timeout rate. With these layers in place, the same fraud-service failure raises checkout’s p99 by about 700 ms only until the breaker opens, after which latency returns to normal while orders queue for later scoring.

Timeout assumptions that fail under load

  • “We set a read timeout, so calls can’t take longer than that.” Depending on the client, read timeout limits gaps between bytes or the wait for headers, not the total call.
  • Setting 30 or 60 seconds everywhere. A timeout longer than your caller’s own timeout means you keep working on requests nobody is waiting for.
  • Creating new RestTemplate() or a bare RestClient.create(). Neither goes through Boot’s builder, so neither picks up any timeout you configured for it.
  • Forgetting the connection pool timeout. Threads then wait up to Apache HttpClient’s three-minute default for a pooled connection.
  • Retrying non-idempotent POSTs after a read timeout. The first request may have succeeded; you may charge a card twice. Use idempotency keys.
  • Retrying at every layer. Three layers making three attempts each turn one slow call into 27.

Proving the client gives up on time with WireMock

Use a stub server that delays its response and assert the client gives up on time. With WireMock:

@WireMockTest(httpPort = 8089)
class InventoryTimeoutTest {

    @Test
    void readTimeoutFiresBeforeSlowResponse() {
        stubFor(get("/stock/abc").willReturn(ok("{\"qty\":1}").withFixedDelay(2_000)));

        HttpClient jdk = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(300)).build();
        JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(jdk);
        factory.setReadTimeout(Duration.ofMillis(400));
        RestClient client = RestClient.builder()
                .baseUrl("http://localhost:8089").requestFactory(factory).build();

        long start = System.nanoTime();
        assertThatThrownBy(() -> client.get().uri("/stock/abc").retrieve().body(String.class))
                .isInstanceOf(ResourceAccessException.class);
        assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofSeconds(1));
    }
}
java

ResourceAccessException wraps the underlying HttpTimeoutException or SocketTimeoutException. To test the connect timeout, point the client at a non-routable address such as 10.255.255.1.

Virtual threads, JDBC and deadlines: follow-ups

How do timeouts interact with virtual threads? Virtual threads make a blocked call cheap in memory, so thread exhaustion is less likely, but the user still waits and the downstream still gets load. Timeouts remain necessary.

Where else do you need timeouts? Every network call needs one: JDBC (spring.datasource.hikari.connection-timeout for the pool, plus query timeouts), Redis, message brokers and transactions.

Should timeouts be the same across environments? The logic should be; values can differ. Bind them from configuration.

What is a deadline and how is it propagated? A deadline is the remaining budget, passed downstream in a header or as a gRPC deadline, so each hop knows how long the original caller will still wait and can give up early instead of finishing work nobody will read.

Quiz yourself: a 1-second budget across two services

Your endpoint has a 1-second budget. It calls service A (p99 200 ms) and then service B (p99 300 ms), and you want one retry on B for connect failures only. Choose timeouts and justify them.

Worked answer

Reserve about 150 ms for local processing, leaving 850 ms. Give A a 100 ms connect timeout and a 250 ms read timeout (a little above its p99): worst case about 350 ms. That leaves about 500 ms for B. Give B a 75 ms connect timeout and a 350 ms read timeout (a little above its 300 ms p99). Since the retry is only on connect failure, worst case for B is two connect timeouts plus one read: 2 × 75 ms + 350 ms = 500 ms. Add a total-duration cap on each call so trickling responses cannot exceed the budget, and a circuit breaker so a dead dependency fails in microseconds. The reasoning to articulate: timeouts are derived from the budget and dependency latency, retries consume budget, and total time must be capped separately from read time.

Further reading on resilient Spring services

More in Spring Boot

esc