Sub topic 8
Choosing a request factory and setting timeouts
This chapter assumes you can already build a RestClient with a base URL and send a GET request. It also assumes Java 17 or later and basic Spring Boot configuration. Here you will learn how RestClient decides which HTTP library to use, how to choose one on purpose, and how to set connect and read timeouts so a slow server cannot hang your threads.
What a request factory is
RestClient does not open sockets itself. It builds a request through a ClientHttpRequestFactory, which is a Spring abstraction that wraps one concrete HTTP library. The factory creates a ClientHttpRequest for each call, and that request runs on the underlying library.
RestClient is a fluent API (a chain of method calls) on top of this abstraction. Swapping the factory changes the networking behavior without touching your call sites, such as restClient.get().uri(...).retrieve().
The factory is also where timeouts, connection pooling, proxies, redirects and TLS settings live. RestClient has no timeout() method on its fluent API, so you configure all of these on the factory or on the library behind it.
Which factory you get by default
If you don't set a factory, RestClient picks one by checking the classpath. The check runs in this order, and the first match wins:
- Apache HttpClient 5 (
HttpComponentsClientHttpRequestFactory) - Jetty HttpClient (
JettyClientHttpRequestFactory) - The JDK
java.net.http.HttpClient(JdkClientHttpRequestFactory) HttpURLConnection(SimpleClientHttpRequestFactory) as the last resort
Newer Spring Framework versions add Reactor Netty to this list, so check the Javadoc of RestClient.Builder for your version.
| Factory | Underlying library | Dependency needed | Notes |
|---|---|---|---|
| `JdkClientHttpRequestFactory` | `java.net.http.HttpClient` | None (JDK 11+) | Good default. HTTP/2 support. Reuse one `HttpClient`. |
| `HttpComponentsClientHttpRequestFactory` | Apache HttpClient 5 | `org.apache.httpcomponents.client5:httpclient5` | Most tuning options: pool sizes, retries, proxies, per-route limits. |
| `JettyClientHttpRequestFactory` | Jetty HttpClient | `org.eclipse.jetty:jetty-client` | Useful if the app already depends on Jetty. |
| `SimpleClientHttpRequestFactory` | `HttpURLConnection` | None | Basic. No pooling control, and some methods such as PATCH are limited. |
Detection by classpath has a side effect. Adding a dependency that happens to pull in Apache HttpClient 5 transitively can silently change which library your client uses. If a client behaves differently after a dependency upgrade, check the factory first.
Two kinds of timeout
A connect timeout limits how long the client waits to establish a TCP connection (and TLS, depending on the library). It protects you from hosts that are down or unreachable, where packets are dropped and nothing answers.
A read timeout limits how long the client waits for data from the server after the request is sent. It protects you from a server that accepts the connection but is slow to respond.
Most libraries have defaults that are infinite or very long. The JDK HttpClient has no connect timeout and no request timeout unless you set one. An unset timeout is a common production bug, because one slow dependency can tie up every thread in your pool.
Pick values from what the downstream service promises. A connect timeout of 1 to 3 seconds is typical for services in the same region. A read timeout should be slightly above the service's worst expected response time, not far above it.
Setting timeouts on the JDK factory
The JDK client splits the two settings. The connect timeout belongs to the HttpClient, and the read timeout belongs to the Spring factory:
import java.net.http.HttpClient;
import java.time.Duration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
RestClient timeoutClient(RestClient.Builder builder) {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(Duration.ofSeconds(5));
return builder
.baseUrl("https://api.example.com")
.requestFactory(requestFactory)
.build();
}Two details matter here:
- The JDK
HttpClientdoes not follow redirects by default.followRedirects(NORMAL)turns that on for same-protocol redirects and for HTTPS to HTTPS. Without it, a 301 or 302 comes back as an ordinary response. - Build the
HttpClientonce and reuse it. It owns its connection pool and selector thread, so creating one per request wastes resources.
In the JDK factory, the read timeout covers the wait for the response status and headers. Treat it as a "time to first response" limit rather than a cap on how long a large body may take to stream. If you need a hard limit on total duration, enforce it outside the client, for example with a circuit breaker or by running the call in a task with its own deadline.
Setting timeouts on the simple factory
SimpleClientHttpRequestFactory has both setters directly. This is the quickest option when you have no extra dependencies and no special needs:
import java.time.Duration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
RestClient simpleClient() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(2));
factory.setReadTimeout(Duration.ofSeconds(5));
return RestClient.builder()
.baseUrl("https://api.example.com")
.requestFactory(factory)
.build();
}For Apache HttpClient 5, timeouts and pool limits are configured on the Apache client objects (RequestConfig, ConnectionConfig, the connection manager), and you then hand the finished HttpClient to HttpComponentsClientHttpRequestFactory. The setter names on the Spring wrapper have changed between Spring versions, so prefer the Apache API for anything beyond the basics.
Letting Spring Boot configure it
Spring Boot 3.4 and later build the factory for the auto-configured RestClient.Builder from properties. You can set timeouts without writing any factory code:
spring.http.client.connect-timeout=2s
spring.http.client.read-timeout=5s
# optional: force a library instead of classpath detection
spring.http.client.factory=jdkAccepted values for spring.http.client.factory include http-components, jetty, jdk and simple, plus reactor when Reactor Netty is on the classpath. Boot 3.2 and 3.3 do not have these properties. On those versions, build the factory yourself as shown above, or use Boot's ClientHttpRequestFactories helper with ClientHttpRequestFactorySettings.
The auto-configured RestClient.Builder is a prototype bean. Each injection gives you a fresh builder, so configuring one builder does not change another. You can therefore give each downstream service its own factory and timeouts:
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;
@Configuration
class DownstreamClients {
@Bean
RestClient fastCatalogClient(RestClient.Builder builder) {
return builder
.baseUrl("https://catalog.example.com")
.requestFactory(factory(Duration.ofSeconds(1), Duration.ofSeconds(2)))
.build();
}
@Bean
RestClient slowReportClient(RestClient.Builder builder) {
return builder
.baseUrl("https://reports.example.com")
.requestFactory(factory(Duration.ofSeconds(2), Duration.ofSeconds(30)))
.build();
}
private static JdkClientHttpRequestFactory factory(Duration connect, Duration read) {
HttpClient httpClient = HttpClient.newBuilder().connectTimeout(connect).build();
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient);
factory.setReadTimeout(read);
return factory;
}
}With two RestClient beans of the same type, inject them by name or with @Qualifier. Constructor parameter names such as fastCatalogClient match the bean names when you compile with -parameters, which Spring Boot's build plugins enable by default.
Seeing a timeout happen
This program starts a local server that answers after three seconds, then calls it with a one-second read timeout. It needs only spring-web on the classpath, so you can run it from a plain Java project.
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
public class ReadTimeoutDemo {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext("/slow", exchange -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
byte[] body = "done".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
try {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2))
.build();
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient);
factory.setReadTimeout(Duration.ofSeconds(1));
RestClient client = RestClient.builder()
.baseUrl("http://localhost:" + server.getAddress().getPort())
.requestFactory(factory)
.build();
long start = System.nanoTime();
try {
client.get().uri("/slow").retrieve().body(String.class);
} catch (ResourceAccessException e) {
long millis = Duration.ofNanos(System.nanoTime() - start).toMillis();
System.out.println("Timed out after about " + millis + " ms");
System.out.println("Cause: " + e.getCause());
}
} finally {
server.stop(0);
}
}
}The program should report a time close to 1000 ms, not 3000 ms. The exact text of the cause depends on the JDK version.
How timeouts surface in your code
A timeout is not an HTTP response, so onStatus handlers never see it and no RestClientResponseException is thrown. Connect failures, read timeouts, DNS errors and dropped connections all arrive as ResourceAccessException, which wraps the original IOException as its cause.
This split affects your error handling:
RestClientResponseException(and its subclasses) means the server answered with a 4xx or 5xx status. The request reached the server.ResourceAccessExceptionmeans there was no usable response. After a read timeout, you cannot know whether the server processed the request.
The second point matters for retries. Retrying a GET after a timeout is usually safe. Retrying a POST can create a duplicate unless the API supports an idempotency key. Decide per operation, and avoid wrapping every call in a blanket retry.
Gotchas
- Mock servers bypass the factory.
MockRestServiceServer.bindTo(builder)installs its own request factory, so tests never exercise your timeout settings. Test timeouts with a local server, as in the demo above, or with a tool such as WireMock that can delay responses. - Order of builder calls.
requestFactory(...)on a builder replaces the factory. If you useMockRestServiceServerin a test, bind it to the builder after your configuration and beforebuild(). - Timeouts are per call, not per workflow. A method that makes three sequential calls with a 5-second read timeout can block for 15 seconds. Budget the total.
- Pool exhaustion looks like a timeout. With Apache HttpClient, a request waiting for a free pooled connection is governed by a separate connection-request timeout. If you see delays with a healthy server, check the pool limits.
- Share the underlying client. Each factory wraps a library client with its own threads and connections. Create it once per downstream service, not per request.
Exercise
A teammate sets spring.http.client.read-timeout=3s in Spring Boot 3.4, but the RestClient bean still waits 30 seconds on a slow server. The bean is built with builder.requestFactory(new JdkClientHttpRequestFactory(HttpClient.newHttpClient())).build(). What is wrong, and what should be changed?
Show answer
Calling requestFactory(...) replaces the factory Boot would have built from the properties, so the property is ignored. The hand-built factory has no read timeout set. Either remove the requestFactory call so Boot applies the properties, or call setReadTimeout(Duration.ofSeconds(3)) on the factory (and set a connect timeout on the HttpClient).
Exercise
Your service calls a payment API with POST and gets a ResourceAccessException caused by a read timeout. Why is it unsafe to retry the call automatically, and which exception type would you expect if the API had instead answered with HTTP 503?
Show answer
After a read timeout you don't know whether the server already processed the payment, so a blind retry may charge twice unless the API accepts an idempotency key. An HTTP 503 is a real response, so it would surface as a RestClientResponseException (specifically a server-error subclass), which you can handle with onStatus or a catch block.