Spring
RestTemplate
Timeout
Exception Handling
Error Detection

Using sping's restTemplate with a timeout, how do I detect a timeout?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

RestTemplate is synchronous, so a timeout shows up as an exception on the calling thread. To detect it correctly, you need two things: a client configured with explicit timeout values and exception handling that distinguishes timeout failures from other I/O problems.

Configure connection and read timeouts

There are usually two timeout categories to care about. The connection timeout limits how long the client waits to establish the TCP connection. The read timeout limits how long it waits for data after the connection has been made.

If you never configure them, a request can block much longer than you expect. A common setup uses HttpComponentsClientHttpRequestFactory.

java
1import java.net.SocketTimeoutException;
2import org.apache.hc.client5.http.ConnectTimeoutException;
3import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
4import org.springframework.web.client.ResourceAccessException;
5import org.springframework.web.client.RestTemplate;
6
7public class ExampleClient {
8    private final RestTemplate restTemplate;
9
10    public ExampleClient() {
11        HttpComponentsClientHttpRequestFactory factory =
12            new HttpComponentsClientHttpRequestFactory();
13        factory.setConnectTimeout(2000);
14        factory.setReadTimeout(3000);
15
16        this.restTemplate = new RestTemplate(factory);
17    }
18
19    public String fetch() {
20        try {
21            return restTemplate.getForObject(
22                "https://example.com/api/data",
23                String.class
24            );
25        } catch (ResourceAccessException ex) {
26            Throwable cause = ex.getCause();
27
28            if (cause instanceof SocketTimeoutException ||
29                cause instanceof ConnectTimeoutException) {
30                return "Request timed out";
31            }
32
33            throw ex;
34        }
35    }
36}

The key point is that RestTemplate often wraps low-level timeout exceptions in ResourceAccessException. In other words, the timeout may not be the top-level exception type you catch first.

Detect the specific timeout reason

In practice, timeout detection is usually a matter of inspecting the cause chain. A connect timeout means the remote host could not be reached quickly enough. A read timeout means the connection was established, but the server did not send data before the deadline.

That distinction matters operationally. Connect timeouts often suggest network reachability, DNS, or load balancer issues. Read timeouts often point to a slow downstream service. Logging them separately makes troubleshooting much easier.

Some teams centralize this logic in one client wrapper so every outgoing call gets consistent timeout settings, metrics, and exception mapping. That is better than repeating try and catch blocks across the codebase.

Prefer a clear fallback strategy

Detecting the timeout is only half the job. Decide what the caller should do next. A user-facing request may return a friendly error. A background integration may retry with backoff. A non-critical dependency may fall back to cached data. The important part is to make the timeout an explicit branch in the client behavior rather than an accidental generic failure.

It is also worth noting that RestTemplate is in maintenance mode. For new Spring applications, WebClient is usually the better long-term choice. Still, if you are maintaining existing synchronous code, RestTemplate remains common and the timeout handling pattern above is the right mental model.

Common Pitfalls

  • Configuring only one timeout and assuming it covers both connection setup and response waiting.
  • Catching only SocketTimeoutException and forgetting that RestTemplate may wrap it in ResourceAccessException.
  • Treating all I/O failures as identical, which hides whether the downstream issue is connectivity or slowness.
  • Scattering timeout handling across many call sites instead of centralizing the client policy.
  • Leaving timeout values at defaults, which can lead to unexpectedly long blocking requests.

Summary

  • Set both connection and read timeouts on the underlying RestTemplate request factory.
  • Catch ResourceAccessException and inspect the cause chain for timeout-specific exceptions.
  • Distinguish connect timeouts from read timeouts because they usually point to different problems.
  • Decide on a clear fallback path such as retry, cached data, or a user-visible error.
  • For new Spring code, prefer WebClient, but this pattern remains correct for RestTemplate.

Course illustration
Course illustration

All Rights Reserved.