Sub topic 12
Timeouts and retries
This chapter assumes you can build a WebClient call that returns a Mono, and that you know map, flatMap, and onErrorResume. It also assumes you know that a reactive pipeline runs only when something subscribes to it.
A remote service can be slow, or it can fail for a moment and then recover. A reactive service has no thread blocked on each call, so a slow call does not obviously hurt. It still holds a connection, memory, and the caller's patience, and the caller may be waiting on your response. Timeouts limit how long you wait. Retries recover from short failures. Used carelessly, both can make an outage worse.
Timeouts with the timeout operator
Mono.timeout(Duration) watches the time between subscription and the first signal. If no element arrives in time, the operator cancels the upstream subscription and emits a java.util.concurrent.TimeoutException as an error. Cancelling a WebClient pipeline closes the in-flight request, so the connection is released.
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2));You can also give timeout a fallback publisher. On timeout, the pipeline switches to the fallback instead of failing.
Mono<User> userOrGuest = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2), Mono.just(new User("0", "guest")));On a Flux, the duration applies to the gap before each element, including the first one. It is not a limit on the whole stream. A stream that emits one item every second never times out under timeout(Duration.ofSeconds(2)), however long it runs.
The timeout operator and Retry.backoff schedule their timers on Schedulers.parallel(). Your downstream operators may therefore run on a parallel-scheduler thread after a retry or a timeout. This matters if you do blocking work later in the chain (see the threading chapter).
Timeouts at the HTTP client level
The timeout operator measures the whole pipeline. Reactor Netty can also enforce limits at the connection level. A connect timeout fails fast when a host is unreachable. A response timeout bounds the wait for the response.
import io.netty.channel.ChannelOption;
import java.time.Duration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
public class ClientFactory {
public static WebClient create() {
HttpClient httpClient = HttpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
.responseTimeout(Duration.ofSeconds(2));
return WebClient.builder()
.baseUrl("https://api.example.com")
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
}Use both layers. Client-level timeouts apply to every request made with this client. The timeout operator is per call, so it can be tighter for one endpoint. It can also cover work that is not an HTTP call, such as a repository lookup.
| Mechanism | Scope | Error type |
|---|---|---|
| `CONNECT_TIMEOUT_MILLIS` | Opening the TCP connection | `WebClientRequestException` wrapping a connect exception |
| `responseTimeout` | Waiting for the response | `WebClientRequestException` wrapping a read timeout |
| `.timeout(Duration)` | Any `Mono` or `Flux` | `TimeoutException` |
Retrying with retryWhen
retryWhen(Retry) resubscribes to the upstream publisher each time it fails. Because WebClient pipelines are cold, each resubscription sends a new HTTP request. The usual strategy is Retry.backoff, which waits longer before each attempt.
WebClient client = WebClient.create("https://api.example.com");
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2))
.retryWhen(Retry.backoff(3, Duration.ofMillis(200)));Here 3 is the maximum number of retries, so there are up to four attempts in total. The first delay is about 200 ms and the delay doubles each time. By default, Reactor adds random jitter of up to 50% to each delay, so many clients that fail together do not all retry at the same instant.
When retries run out, Reactor does not rethrow your original error. It throws a RetryExhaustedException whose cause is the last failure. That hides the real exception from any onErrorMap that expects a TimeoutException or WebClientResponseException. You can restore the original with onRetryExhaustedThrow.
Retry only what is worth retrying
By default, retryWhen retries every error. That is wrong for a 404 or a 400, which fail the same way every time. Use filter to retry only transient failures.
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
record User(String id, String name) {}
@Service
public class UserClient {
private final WebClient client;
public UserClient(WebClient.Builder builder) {
this.client = builder.baseUrl("https://api.example.com").build();
}
public Mono<User> findUser(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2))
.retryWhen(Retry.backoff(3, Duration.ofMillis(200))
.maxBackoff(Duration.ofSeconds(2))
.filter(UserClient::isTransient)
.onRetryExhaustedThrow((spec, signal) -> signal.failure()));
}
private static boolean isTransient(Throwable ex) {
if (ex instanceof WebClientResponseException wre) {
return wre.getStatusCode().is5xxServerError();
}
return ex instanceof TimeoutException
|| ex instanceof WebClientRequestException;
}
}The filter retries 5xx responses, timeouts, and connection-level failures. A 4xx response passes through immediately as a WebClientResponseException. maxBackoff caps the delay so a long retry sequence cannot wait for minutes.
Where you place the operators
The order of timeout and retryWhen changes what the timeout covers.
| Order | Meaning |
|---|---|
| `.timeout(2s).retryWhen(...)` | Each attempt gets 2 seconds. A timeout is an error, so it can trigger a retry. |
| `.retryWhen(...).timeout(5s)` | The whole operation, including all retries and delays, gets 5 seconds. |
You often want both: a short per-attempt timeout before the retry, and an overall deadline after it.
Mono<User> user = client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2)) // per attempt
.retryWhen(Retry.backoff(3, Duration.ofMillis(200)))
.timeout(Duration.ofSeconds(5)); // overall deadlineWithout the overall deadline, the worst case is four attempts of 2 seconds each plus the backoff delays, which is more than 9 seconds. A caller that is itself waiting on you may have given up long before that.
Mapping timeouts to HTTP responses
When a downstream call times out, your own API should answer with a meaningful status instead of a generic 500. Map the error close to the controller. 504 Gateway Timeout fits a timeout when your service acts as a gateway to another one.
@GetMapping("/{id}")
public Mono<User> get(@PathVariable String id) {
return userClient.findUser(id)
.onErrorMap(TimeoutException.class,
ex -> new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT));
}Because findUser uses onRetryExhaustedThrow to rethrow the original failure, this mapping sees the TimeoutException and not a RetryExhaustedException.
Common mistakes
- Retrying without a timeout. A hung call never errors, so
retryWhennever fires. The request simply waits. - Retrying every error. Always add a
filter. Retrying a400or404wastes time and load. - Retries that are not idempotent. See the warning above.
- Putting the timeout on the wrong side of a retry. Check the table above and pick the scope you intend.
- Retrying a pipeline that is not repeatable. Resubscribing re-runs the pipeline, but a value computed outside it is computed once. In
Mono.just(expensiveCall()), the call runs when the pipeline is assembled, so retries reuse the same value. Wrap the work inMono.fromCallableorMono.defer. - Many clients retrying together. Keep jitter on, and keep the retry count small, so a struggling service is not flooded with retries.
Testing time-based behavior
A test that waits two real seconds for a timeout is slow. StepVerifier.withVirtualTime replaces Reactor's clock, so the test advances time without waiting. The publisher must be created inside the supplier, so that its timers use the virtual clock. This needs the reactor-test dependency.
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
public class TimeoutCheck {
public static void main(String[] args) {
StepVerifier.withVirtualTime(() ->
Mono.never().timeout(Duration.ofSeconds(2)))
.expectSubscription()
.thenAwait(Duration.ofSeconds(2))
.expectError(TimeoutException.class)
.verify();
System.out.println("timeout verified");
}
}Mono.never() never emits, so the pipeline can only end through the timeout. The test finishes in milliseconds.
Exercise
A service calls a payment API with .retryWhen(Retry.backoff(3, Duration.ofMillis(200))) and no timeout. During an incident, the payment API accepts connections but never answers. What does the caller observe, and what two changes would you make?
Show answer
The caller sees no error and no result. A hung call never fails, so retryWhen never triggers, and the request waits until some outer limit such as a client or load balancer timeout fires. Add .timeout(Duration.ofSeconds(2)) before retryWhen so each attempt has a limit and a timeout becomes a retryable error. Then add an overall .timeout(...) after retryWhen, plus a filter so only transient errors are retried. If the call creates a payment, also send an idempotency key, because a timed-out attempt may have succeeded on the server.