Spring › Feature

Configuring Spring RestClient timeouts and connection pools

Configure connect, connection-request, and read timeouts in Spring RestClient with Apache HttpClient 5, tune pool limits, and test slow APIs locally.

Configuring Spring RestClient timeouts and connection pools

One slow external API once took down an entire student club service because every request thread ended up waiting on sockets. This post breaks down RestClient’s three timeout layers, how Apache HttpClient 5 manages its connection pool, and how I configure and test them in Spring Boot 3.5.

Tested with Spring Boot 3.5.3 (Spring Framework 6.2), Java 21, Kotlin 2.1.21, and Apache HttpClient 5 (managed by the Boot BOM).

The problem

Our club event registration service fetches event details from the university notice board API whenever a registration request arrives. Normally that API responds in about 100 ms. One day at the start of the semester, it began holding responses for tens of seconds. Almost immediately, completely unrelated endpoints like login and profile pages stopped responding too.

A thread dump showed the cause right away. Most Tomcat worker threads were blocked on socket reads, and the rest were queued up waiting to lease a connection from the HTTP client pool. Two misconfigurations lined up: I had set no read timeout, and Apache HttpClient 5 was running with its default pool limits (5 connections per route, 25 total). A single stalled upstream API starved the entire server thread pool.

The three timeout layers and how they work

A single outbound HTTP call passes through three distinct phases, and each phase has its own timeout.

flowchart TD
    A["RestClient request starts"] --> B["Lease from pool (connection-request)"]
    B -->|"No idle connection"| C["TCP handshake (connect)"]
    B -->|"Reused connection"| D["Send request & wait (read / socket)"]
    C --> D
    D --> E["Return response & release connection"]
TimeoutMeasured phaseSymptom when too longStarting point
connection-requestWaiting to lease a connection from the poolRequest threads pile up when the pool is exhausted0.5–1 s
connectCompleting the TCP 3-way handshakeThreads stall during SYN retransmissions when a host is dead1–2 s
read (socket)Gap between receiving consecutive packetsA stalled API holds threads indefinitelyAPI p99 × 2–3

One layer deeper, Spring Boot’s auto-configured HttpComponentsClientHttpRequestFactory applies the connect timeout via setConnectTimeout() on the factory and the read timeout via SocketConfig.soTimeout on the connection manager. However, Boot exposes no property for connection-request timeout, so Apache HttpClient 5 keeps its RequestConfig default of 3 minutes. Once the pool fills up, incoming request threads can sit blocked for up to three minutes before failing.

Another detail that trips people up: a read timeout does not bound total response duration. It bounds the idle gap between packets. If a misbehaving server dribbles one byte every second, a 3-second read timeout will never fire. When you need a hard cap on total call duration, enforce it at a higher layer such as a circuit breaker or an async time limiter. I covered why connection reuse matters at the TCP level in TCP handshake, TIME_WAIT, and connection reuse.

Choosing a ClientHttpRequestFactory implementation

Starting with Spring Boot 3.4, ClientHttpRequestFactoryBuilder inspects the classpath and picks an implementation in this order: Apache HttpClient 5 → Jetty → Reactor Netty → JDK HttpClient → SimpleClientHttpRequestFactory. You can also pin one explicitly with spring.http.client.factory.

ImplementationConnection pool controlconnection-request timeoutBest fit
Apache HttpClient 5Fine-grained per-route and total limitsYes (default 3 min)Synchronous MVC services calling multiple external APIs
JDK HttpClientNo max-connection cap (internal pool)NoLightweight setup with zero extra dependencies
Reactor NettyControlled via ConnectionProviderpendingAcquireTimeoutProjects already running WebFlux or WebClient
Simple (HttpURLConnection)Relies on JVM keep-alive cacheNoQuick tests or one-off scripts

Knowing when not to use each option matters just as much. JDK HttpClient offers no way to cap concurrent connections, making it a poor fit when you need to protect a fragile upstream server. Reactor Netty pulls in a Netty event loop on top of your servlet stack, which isn’t worth the overhead for purely synchronous MVC calls. SimpleClientHttpRequestFactory defaults to infinite timeouts, so I keep it out of production code altogether.

Configuring Apache HttpClient 5 in Spring Boot

Add httpclient5 to the project and let the Spring Boot BOM manage its version.

1
2
3
4
5
6
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.apache.httpcomponents.client5:httpclient5") // version managed by Boot BOM
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
}

Set the factory type along with the connect and read timeouts in application.yml.

1
2
3
4
5
6
7
# src/main/resources/application.yml
spring:
  http:
    client:
      factory: http-components
      connect-timeout: 2s
      read-timeout: 3s

Properties handle connect and read timeouts cleanly, but pool sizing and the connection-request timeout require registering a custom builder bean. When you declare an HttpComponentsClientHttpRequestFactoryBuilder bean, Boot replaces its default builder with yours while still applying the spring.http.client.* properties on top.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/main/kotlin/com/example/club/config/HttpClientConfig.kt
package com.example.club.config

import org.apache.hc.core5.util.TimeValue
import org.apache.hc.core5.util.Timeout
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder
import org.springframework.boot.http.client.HttpComponentsClientHttpRequestFactoryBuilder
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class HttpClientConfig {

    @Bean
    fun clientHttpRequestFactoryBuilder(): HttpComponentsClientHttpRequestFactoryBuilder =
        ClientHttpRequestFactoryBuilder.httpComponents()
            .withConnectionManagerCustomizer { manager ->
                manager.setMaxConnTotal(50)
                manager.setMaxConnPerRoute(20)
            }
            .withDefaultRequestConfigCustomizer { request ->
                request.setConnectionRequestTimeout(Timeout.ofSeconds(1))
            }
            .withHttpClientCustomizer { client ->
                client.evictExpiredConnections()
                client.evictIdleConnections(TimeValue.ofSeconds(30))
            }
}

Then inject Spring Boot’s auto-configured RestClient.Builder into your API client.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/main/kotlin/com/example/club/notice/NoticeApiClient.kt
package com.example.club.notice

import org.springframework.stereotype.Component
import org.springframework.web.client.RestClient
import org.springframework.web.client.body

data class NoticeResponse(val id: Long, val title: String)

@Component
class NoticeApiClient(builder: RestClient.Builder) {

    private val restClient = builder
        .baseUrl("https://notice.example.ac.kr")
        .build()

    fun fetchNotices(): List<NoticeResponse> =
        restClient.get()
            .uri("/api/notices?size=20")
            .retrieve()
            .body<List<NoticeResponse>>()
            .orEmpty()
}

Never instantiate clients with RestClient.create() in production services. That static factory bypasses Spring Boot auto-configuration completely, dropping every timeout and pool setting you configured above.

Reproducing and diagnosing slow upstream calls locally

You don’t need to wait for a production outage to verify your timeouts. go-httpbin exposes a /delay/{seconds} endpoint that makes reproducing slow responses trivial.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Run a mock server that delays responses (/delay/{seconds})
docker run --rm -p 8081:8080 mccutchen/go-httpbin

# Measure per-phase timing for a single request
curl -s -o /dev/null \
  -w "connect=%{time_connect}s ttfb=%{time_starttransfer}s total=%{time_total}s\n" \
  http://localhost:8081/delay/5

# Reproduce a connect timeout against an unreachable private IP
curl -s -o /dev/null --connect-timeout 2 -w "%{time_total}s\n" http://10.255.255.1/

# Reproduce pool exhaustion with 30 concurrent calls to your API
seq 30 | xargs -P 30 -I{} curl -s -o /dev/null \
  -w "%{http_code} %{time_total}s\n" http://localhost:8080/api/events/1

# Count threads waiting to acquire a connection from the pool
jcmd $(pgrep -f club-api) Thread.print | grep -c "PoolingHttpClientConnectionManager"

Point baseUrl at http://localhost:8081 and call /delay/5. Before applying the configuration, 30 concurrent requests finish in a 5-second staircase pattern because only 5 connections per route run at once while the rest wait in the pool. After configuring the timeouts and pool, requests that exceed the 3-second read timeout or the 1-second connection-request timeout fail fast.

When inspecting thread dumps during an incident, a high count of threads stuck in PoolingHttpClientConnectionManager points to pool exhaustion. A pile of threads parked inside NioSocketImpl.read (the default socket implementation since Java 13) points to a missing or overly generous read timeout.

Production caveats and checklist

Cranking up pool size is rarely the fix. Raising maxConnPerRoute to 200 while an upstream server is already struggling may unblock your local queue briefly, but it floods the upstream host and slows down its recovery. Also be careful when adding retries after a read timeout: non-idempotent requests like POST can execute twice if the server processed the first call before timing out on the response, so restrict retries by HTTP method.

Timeouts won’t prevent an external API from failing. What they do is shrink the blast radius from “the whole application hangs” to “only calls touching the slow API fail.” Once timeouts are in place, the next step is adding a circuit breaker to stop hammering an upstream service that is already down.

  • Are spring.http.client.connect-timeout and read-timeout explicitly set?
  • Did you lower the connection-request timeout from the 3-minute default to around 1 second?
  • Is maxConnPerRoute sized between your peak concurrency and what the upstream server can safely handle?
  • Do all HTTP clients inject Spring Boot’s auto-configured RestClient.Builder instead of calling RestClient.create()?
  • Have you tested concurrent requests against a delayed mock server to confirm failures happen within your expected time bounds?
This post is licensed under CC BY 4.0 by the author.