Sub topic 10
Configuring timeouts
A declarative client hides the HTTP call behind an interface method, so it is easy to forget that the call can hang. Without timeouts, a slow or unreachable server can hold a request thread for a long time. Under load, those blocked threads exhaust your pool and one slow dependency takes down your whole service. This chapter assumes you have already built a TodoClient proxy from a RestClient, as in the earlier chapters.
What a timeout covers
A timeout limits one phase of the exchange. Different phases have different settings.
| Setting | Phase it limits | Typical value |
|---|---|---|
| Connect timeout | Opening the TCP connection (and TLS handshake, in most clients) | 1 to 3 seconds |
| Read timeout | Waiting for response data after the request is sent | Depends on the endpoint, often 2 to 10 seconds |
| Connection request timeout | Waiting to borrow a connection from a pool (Apache HttpClient and similar) | Short, a few seconds |
The read timeout is not a limit on the whole call. In most clients it limits the gap between reads. A server that sends one byte every few seconds can keep a call alive far longer than the read timeout. If you need a hard limit on total duration, enforce it at a higher level, for example with a circuit breaker or a time limiter.
Where the settings live
HttpServiceProxyFactory does not own any timeout settings. The generated proxy delegates to an adapter, the adapter delegates to a RestClient, and the RestClient delegates to a ClientHttpRequestFactory. That last object is the one that applies timeouts. So the rule is simple: configure timeouts on the request factory behind the RestClient, not on the interface or the proxy factory.
The timeout setters differ by factory. The JDK-based JdkClientHttpRequestFactory takes the connect timeout from the java.net.http.HttpClient and has its own setReadTimeout. SimpleClientHttpRequestFactory has setConnectTimeout and setReadTimeout. HttpComponentsClientHttpRequestFactory has those two and also setConnectionRequestTimeout.
Option 1: Spring Boot properties
Since Spring Boot 3.4, the auto-configured RestClient.Builder reads shared HTTP client properties. This is the least code and works for every client built from the injected builder.
spring.http.client.connect-timeout=2s
spring.http.client.read-timeout=5sBoot also chooses the request factory for you. It detects what is on the classpath, such as Apache HttpClient, Jetty, Reactor Netty, or the JDK client. You can force a choice with spring.http.client.factory, but you rarely need to.
Two details cause most surprises here:
- The properties apply only to a builder that Boot created. If your code calls the static
RestClient.builder(), none of these settings are applied. - If you call
builder.requestFactory(...)yourself, you replace the factory Boot configured, including its timeouts. From then on you own the timeouts.
On Spring Boot 4, you can also set timeouts per group with spring.http.serviceclient.<group>.connect-timeout and spring.http.serviceclient.<group>.read-timeout, next to the base-url property you saw earlier. Check the property names against your exact Boot version, because this area changed between 3.4 and 4.0.
Option 2: Configure the request factory in code
Use code when different clients need different timeouts, or when you want the timeouts visible next to the client definition. The RestClient.Builder bean has prototype scope, so each injection point gets its own independent builder. Changing it in one configuration method does not leak into another client.
import java.net.http.HttpClient;
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
@Configuration
class TodoClientConfig {
@Bean
TodoClient todoClient(RestClient.Builder builder) {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
JdkClientHttpRequestFactory requestFactory =
new JdkClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(Duration.ofSeconds(5));
RestClient restClient = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.requestFactory(requestFactory)
.build();
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(restClient))
.build()
.createClient(TodoClient.class);
}
}The connect timeout is set on the JDK HttpClient, and the read timeout is set on the Spring wrapper. Mixing the two up is a common mistake. The JDK client has no read-timeout setting of its own. Spring applies it per request through HttpRequest.Builder.timeout.
If your project uses Apache HttpClient 5, the equivalent is:
import java.time.Duration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
class ApacheFactories {
static HttpComponentsClientHttpRequestFactory create() {
HttpComponentsClientHttpRequestFactory factory =
new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(2));
factory.setReadTimeout(Duration.ofSeconds(5));
return factory;
}
}Pass the result to builder.requestFactory(...) in the same way.
What happens when a timeout fires
A timeout is an I/O failure, not an HTTP response, so there is no status code to inspect. RestClient wraps the underlying IOException in a ResourceAccessException. The original exception is available through getCause(). Depending on the request factory and the phase, the cause is a SocketTimeoutException, a java.net.http.HttpTimeoutException, or a java.net.http.HttpConnectTimeoutException.
This matters for error handling. The HttpClientErrorException subclasses you caught in the previous chapter, such as NotFound, are never thrown for a timeout. A catch block for them will not see it.
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
@Service
class TodoLookup {
private final TodoClient todoClient;
TodoLookup(TodoClient todoClient) {
this.todoClient = todoClient;
}
Todo findOrFallback(long id) {
try {
return todoClient.getTodo(id);
} catch (ResourceAccessException e) {
// Covers connect and read timeouts, and other network failures.
return new Todo(id, null, "unavailable", false);
}
}
}ResourceAccessException also covers other network failures, such as a refused connection or an unknown host. If you must tell a timeout apart from those, inspect the cause with instanceof. Do this only when the behavior really differs, because the exact exception type varies between request factories.
Testing the failure path
You can test timeout handling without a slow server. MockRestServiceServer can answer a request by throwing an IOException, which RestClient then converts the same way it converts a real timeout.
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withException;
import java.net.SocketTimeoutException;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
class TodoClientTimeoutTest {
@Test
void timeoutSurfacesAsResourceAccessException() {
RestClient.Builder builder = RestClient.builder().baseUrl("http://localhost");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
server.expect(requestTo("http://localhost/todos/1"))
.andRespond(withException(new SocketTimeoutException("Read timed out")));
TodoClient client = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(builder.build()))
.build()
.createClient(TodoClient.class);
assertThrows(ResourceAccessException.class, () -> client.getTodo(1));
server.verify();
}
}This test checks your handling code. It does not prove the real timeout values are applied. To check that, run an integration test against a stub server that delays its response, such as WireMock with a fixed delay.
Choosing values and avoiding pitfalls
- Set both timeouts explicitly. Defaults vary by request factory. Some factories wait indefinitely, so a missing setting is a hidden risk.
- Keep connect timeouts short. A server that is reachable answers the TCP handshake quickly. Waiting longer than a few seconds rarely helps.
- Size the read timeout per endpoint. A report-generating endpoint may need 30 seconds while a lookup needs 2. If the values differ a lot, create separate clients. The same interface can be registered twice with different request factories.
- Be careful when retrying. A read timeout on a
POSTdoes not tell you whether the server processed the request. Retry only idempotent calls, or send an idempotency key. - Do not confuse client and server timeouts. The server may have its own limit, and a gateway in between may cut the call first. The shortest limit in the chain wins.
- Watch the thread budget. The worst-case blocking time of a call is roughly connect timeout plus read timeout. Multiply it by your concurrency to see what a failing dependency can cost you.
Exercise
A client built from the static RestClient.builder() ignores the spring.http.client.read-timeout=5s property in application.properties, and a hung server blocks calls forever. Why does this happen, and what are two ways to fix it?
Show answer
The property is applied only to the RestClient.Builder bean that Spring Boot auto-configures. The static RestClient.builder() creates a plain builder that Boot never touches, so no timeout is set. Fix it by injecting RestClient.Builder into the configuration method instead of calling the static method, or by setting a request factory with explicit timeouts, for example JdkClientHttpRequestFactory with setReadTimeout(Duration.ofSeconds(5)) and an HttpClient that has connectTimeout set, and passing it to builder.requestFactory(...).
Exercise
A call to todoClient.getTodo(1) times out. Which exception type should your code catch, and why does catch (HttpClientErrorException e) miss it?
Show answer
Catch ResourceAccessException. A timeout is an I/O failure with no HTTP response, so RestClient wraps the IOException instead of creating an HttpClientErrorException, which is only thrown when the server returns a 4xx status.