Quick revision
The short answer
We add retryWhen(Retry.backoff(3, Duration.ofMillis(200)).jitter(0.5).filter(this::isTransient)) to the WebClient chain, and make isTransient recognise only connection errors (WebClientRequestException) and a dedicated exception that we raise for 503 in onStatus. We put a timeout() before retryWhen so each attempt has its own limit, and another timeout after it for the total. onRetryExhaustedThrow turns the final failure into a clear exception, and doBeforeRetry logs or counts every retry.
What to remember
In this answer, we built a WebClient call that retries only on connection errors and 503. We mapped 503 to its own exception in onStatus so the filter can recognise it alongside WebClientRequestException, used Retry.backoff(3, 200 ms) with jitter and a maximum backoff, placed one timeout above retryWhen so each attempt has its own limit and another below it for the total, turned exhausted retries into a clear exception, and made every retry visible with doBeforeRetry. A MockWebServer test then confirmed both the result and the number of requests.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We add retryWhen(Retry.backoff(3, Duration.ofMillis(200)).jitter(0.5).filter(this::isTransient)) to the WebClient chain, and make isTransient recognise only connection errors (WebClientRequestException) and a dedicated exception that we raise for 503 in onStatus. We put a timeout() before retryWhen so each attempt has its own limit, and another timeout after it for the total. onRetryExhaustedThrow turns the final failure into a clear exception, and doBeforeRetry logs or counts every retry.
Why this question is asked
Reactor's retry operators are powerful but easy to misuse: retry everything, retry forever, or put the timeout in the wrong place so one slow attempt eats the whole budget. Interviewers ask for this in code because the order of operators in a reactive chain changes the behaviour completely, and a correct answer shows we understand what retryWhen actually does. In this answer, we will recap how retrying a Mono works, write the full call, then look closely at the filter, the two timeouts, the exhausted case and observability, and finish with a test.
1A Quick Recap: What Retrying a Mono Means
A WebClient Mono is cold: each subscription performs the HTTP request again. retryWhen uses that. When the Mono fails, retryWhen decides, based on a Retry specification, whether to resubscribe to everything above it in the chain, which sends the request again. Retry.backoff(maxRetries, minBackoff) is a ready-made specification: it waits minBackoff before the first retry and doubles the wait each time, and allows maxRetries retries, so Retry.backoff(3, ...) means up to 4 attempts in total.
Because retryWhen resubscribes to the operators above it, the position of each operator matters. Anything above retryWhen runs once per attempt; anything below runs once for the whole sequence.
2The Full Call
Here is the complete method, followed by an explanation of each part.
- Send the request
timeout(500 ms)per attempt - Succeeded?YesEmit StockNoCheck the failure
- Connection error or 503?YesCheck retries leftNoFail at once, e.g. 404
- Fewer than 3 retries so far?YesLog, wait with jittered backoff, resendNoonRetryExhaustedThrow
- Outer timeout(3 s)cuts everything off at 3 s
5 steps in order. Play them, or step through them one at a time.
Only the two transient failures are retried, and the total is capped.
3Mapping 503 to Its Own Exception
By default, retrieve() turns every 4xx or 5xx response into a WebClientResponseException. We could filter on its status code, but a dedicated exception makes the rule explicit and easy to test. onStatus(predicate, function) lets us replace the default error for the statuses we choose: for 503 we return a Mono.error with ServiceUnavailableException, and every other error status keeps its default exception, which isTransient rejects.
Connection problems never produce a response at all. WebClient reports them as WebClientRequestException, which wraps the underlying cause such as a ConnectException. That is the second thing isTransient accepts. Note what is not accepted: 500, 404 and 400 fail immediately, and so does the TimeoutException from our per-attempt timeout. The question asks for connection errors and 503 only; if we decided a slow read of an idempotent GET is also worth retrying, we would add TimeoutException to the filter deliberately.
4Why the Two Timeouts Sit Where They Do
The first timeout(500 ms) is above retryWhen, so it is part of what gets resubscribed. Each attempt therefore gets a fresh 500 ms. If we had put it below retryWhen, there would be one 500 ms limit for the whole sequence, and the first slow attempt would leave no time for retries.
The second timeout(3000 ms) is below retryWhen and wraps everything: all attempts and all backoff waits. Let us check the arithmetic. Four attempts that each answer 503 just before their 500 ms limit take about 2,000 ms, and backoffs of about 200, 400 and 800 ms add 1,400 ms, so the worst case is 3,400 ms, above our 3 second budget. That is fine, and it is exactly what the outer timeout is for: it cuts the last attempt short so the caller always gets an answer within 3 seconds. If we wanted every attempt to complete, we would reduce the per-attempt timeout or the number of retries until the sum fits.
| Time (ms) | Event |
|---|---|
| 0 - 500 | attempt 1 answers 503 just before 500 ms |
| 500 - 700 | backoff about 200 ms |
| 700 - 1,200 | attempt 2 |
| 1,200 - 1,600 | backoff about 400 ms |
| 1,600 - 2,100 | attempt 3 |
| 2,100 - 2,900 | backoff about 800 ms |
| 2,900 - 3,000 | attempt 4 starts, outer timeout fires at 3,000 |
5Exhausted Retries and Observability
When all retries fail, Retry.backoff by default throws an exception that says retries were exhausted and wraps the last failure. That message is not very helpful to callers. onRetryExhaustedThrow lets us throw our own InventoryUnavailableException, carrying the sku, the retry count and the last cause, which our error handler can map to a 503 with a clear message.
Retries hide problems if we cannot see them. A dependency that needs two retries on every call looks healthy from the outside, while it is actually failing two thirds of the time. doBeforeRetry runs before each resubscription, so it is the right place to log the attempt and increment a Micrometer counter tagged with the dependency name. An alert on retry rate often warns us of trouble before errors appear.
6Testing the Retry Behaviour
We can test the policy against a stub server that fails a set number of times. MockWebServer from OkHttp, or WireMock with scenarios, can queue responses in order.
Notice that we assert the request count, not just the result. A test that only checks the final Stock would also pass if the client retried ten times or not at all.
7Follow-up questions
What is the difference between retry(3) and retryWhen(Retry.backoff(...))?
retry(3) resubscribes immediately, up to 3 times, for any error. That hammers a struggling service and retries errors like 404 that can never succeed. retryWhen with Retry.backoff adds growing waits, jitter, a filter on which errors to retry, hooks for logging, and a custom exhausted exception.
Is it safe to put this retry on a POST?
Only if the operation is idempotent or carries an idempotency key, because retryWhen re-sends the whole request. For a 503 the server usually did nothing, but a connection reset after sending can happen after the server acted. For a POST, I would add an Idempotency-Key header generated once outside the Mono, so every attempt reuses it.
What does jitter(0.5) do exactly?
It randomises each computed backoff by up to 50 percent in either direction, so a 400 ms backoff becomes somewhere between about 200 and 600 ms. This spreads out retries from many clients that failed at the same time, so they do not hit the recovering service in synchronised waves.
8Conclusion
In this answer, we built a WebClient call that retries only on connection errors and 503. We mapped 503 to its own exception in onStatus so the filter can recognise it alongside WebClientRequestException, used Retry.backoff(3, 200 ms) with jitter and a maximum backoff, placed one timeout above retryWhen so each attempt has its own limit and another below it for the total, turned exhausted retries into a clear exception, and made every retry visible with doBeforeRetry. A MockWebServer test then confirmed both the result and the number of requests.
Open with
I would build the chain as get, uri, retrieve, then onStatus for 503 returning Mono.error with a dedicated ServiceUnavailableException, then bodyToMono. After that a timeout of, say, 500 milliseconds, then retryWhen with Retry.backoff(3, Duration.ofMillis(200)), a maxBackoff, jitter(0.5) and filter(this::isTransient), where isTransient accepts only WebClientRequestException, which is how WebClient reports connection failures, and my 503 exception.
Then, if they want more
So 404 or 500 fail immediately. The order matters because retryWhen resubscribes to everything above it, and since WebClient's Mono is cold that re-sends the request. The timeout above retryWhen therefore applies per attempt, and I put a second timeout below it, say 3 seconds, as the total budget including backoff. Retry.backoff(3) means three retries, four attempts in total.
I would use onRetryExhaustedThrow to throw my own InventoryUnavailableException with the sku and the last cause instead of Reactor's generic exhausted exception, and doBeforeRetry to log each retry and increment a Micrometer counter, because retries hide failures otherwise.
Then I would test it with MockWebServer: two 503s then a 200 should give the result with exactly three requests, and a 404 should fail without retrying. And I would only use this on a POST with an idempotency key.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How would you add retries with exponential backoff to a WebClient call that should only...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/affe1fe6f7/