Sub topic 12
Timeouts and retries
This chapter assumes you can build a WebClient call and chain operators on a Mono. A remote service can be slow or can fail briefly. Without limits, a slow call holds your response open indefinitely, and a failure surfaces to the user even when a second attempt would have worked. Reactor handles both with the timeout and retryWhen operators.
Setting a timeout
The timeout operator makes a pipeline fail if no element arrives within a given duration. The error is a java.util.concurrent.TimeoutException.
import java.time.Duration;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
@Service
public class UserClient {
private final WebClient client = WebClient.create("https://api.example.com");
public Mono<User> fetch(String id) {
return client.get()
.uri("/users/{id}", id)
.retrieve()
.bodyToMono(User.class)
.timeout(Duration.ofSeconds(2))
.retryWhen(Retry.backoff(3, Duration.ofMillis(200)));
}
}
record User(String id, String name) {}When the timeout fires, Reactor cancels the subscription. The underlying HTTP request is cancelled too, so the connection is released.
Retrying with backoff
Retry.backoff(3, Duration.ofMillis(200)) allows up to three retries. The delay roughly doubles each time (about 200 ms, 400 ms, 800 ms). Reactor adds random jitter of up to 50% by default. Jitter stops many clients from retrying at the same instant after a shared outage.
A retry works by resubscribing to the source. Because WebClient pipelines are lazy, each resubscription sends a new HTTP request.
Order matters
The position of timeout relative to retryWhen changes what the limit applies to.
| Order | Meaning |
|---|---|
| `.timeout(2s).retryWhen(...)` | Each attempt gets 2 seconds. A timeout is an error that can be retried. |
| `.retryWhen(...).timeout(2s)` | The whole operation, retries and delays included, gets 2 seconds. |
Use the first form to bound a single attempt. Use the second to promise a caller an overall deadline. You can combine both.
Retry only what is safe
By default, retryWhen retries every error, including a 404 or a validation failure. Those will fail again, so retrying them wastes time. Add a filter so only transient failures are retried.
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeoutException;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.util.retry.Retry;
public class RetryPolicies {
public static Retry transientOnly() {
return Retry.backoff(3, Duration.ofMillis(200))
.filter(ex -> ex instanceof TimeoutException
|| ex instanceof IOException
|| (ex instanceof WebClientResponseException wex
&& wex.getStatusCode().is5xxServerError()))
.onRetryExhaustedThrow((spec, signal) -> signal.failure());
}
}Use it with .retryWhen(RetryPolicies.transientOnly()).
onRetryExhaustedThrow is optional. Without it, Reactor wraps the last failure in a RetryExhaustedException. Your onErrorResume handlers and exception mappers would then need to unwrap it. Returning signal.failure() passes the original exception through.
Common errors
- Retrying non-idempotent calls. A retried
POSTthat created an order may create it twice. Retry onlyGET,PUT,DELETE, or calls that carry an idempotency key. - Putting
timeouton the wrong publisher.timeoutapplies to the pipeline it is chained on. If you call it inside aflatMap, it limits only that inner call. - Stacking retries. If service A retries three times and calls service B, which also retries three times, one failure can produce nine requests. Retry at one layer.
- No overall deadline. Three retries with backoff can take several seconds. Check that the total fits the caller's own timeout.
Exercise
Your pipeline is .retryWhen(Retry.backoff(3, Duration.ofMillis(200))).timeout(Duration.ofSeconds(1)). A downstream service takes 5 seconds on every call. Roughly how long until the caller sees an error, and which exception is it?
Show answer
About 1 second. The timeout is placed after the retry, so it covers the whole operation, retries included. The first attempt is still running at 1 second, so the pipeline emits a TimeoutException and cancels. Retries never get the chance to run.