Error handling and retries

Mid-level Frequently asked 5 min

On this page

The question

What is the difference between onErrorResume and onErrorReturn?

30-second answer

Both catch an error signal and continue with a normal completion. onErrorReturn replaces the failure with one fixed value, chosen when the chain is assembled. onErrorResume takes a function that receives the error and returns a new Publisher, so it can branch on the exception and call a cache or another service. In both, the original stream is over: the elements it had left are lost.

Understand it

An error signal travels down the pipeline

Step by step

Element 1 travels down normally: map turns it into 10, and the subscriber receives it.

Step 1 of 8
View as text

Five rows, top to bottom: the source, a map that throws on 2, doOnNext, an error handler, and the subscriber. A badge shows which signal is at which row, and a line lists what the subscriber received.

Element 1 travels down normally: map turns it into 10, and the subscriber receives it.

Element 2 reaches map, which throws. Reactor catches the exception and turns it into an onError signal, so it does not escape to the caller.

map cancels upstream at once, so the source stops. Element 3 is never emitted: the original stream is over.

The error travels down, skipping every operator that only handles elements. doOnNext does not run. doOnError would see it without stopping it.

onErrorResume catches the signal and subscribes to a fallback publisher, which takes the place of the failed stream. Its elements continue downstream.

The subscriber got 10, -1 and -2, then onComplete. It never saw an error, and it never saw element 3.

Instead of a fallback, retryWhen subscribes again from the start, so 10 arrives a second time. Retry.backoff(3, 100 ms) waits 100, 200 and 400 ms, plus jitter.

After 3 retries, the subscriber gets RetryExhaustedException, "Retries exhausted: 3/3", with the last error as its cause. That is 4 attempts in total.

Five rows, top to bottom: the source, a map that throws on 2, doOnNext, an error handler, and the subscriber. A badge shows which signal is at which row, and a line lists what the subscriber received.

Element 1 travels down normally: map turns it into 10, and the subscriber receives it.

Element 2 reaches map, which throws. Reactor catches the exception and turns it into an onError signal, so it does not escape to the caller.

map cancels upstream at once, so the source stops. Element 3 is never emitted: the original stream is over.

The error travels down, skipping every operator that only handles elements. doOnNext does not run. doOnError would see it without stopping it.

onErrorResume catches the signal and subscribes to a fallback publisher, which takes the place of the failed stream. Its elements continue downstream.

The subscriber got 10, -1 and -2, then onComplete. It never saw an error, and it never saw element 3.

Instead of a fallback, retryWhen subscribes again from the start, so 10 arrives a second time. Retry.backoff(3, 100 ms) waits 100, 200 and 400 ms, plus jitter.

After 3 retries, the subscriber gets RetryExhaustedException, "Retries exhausted: 3/3", with the last error as its cause. That is 4 attempts in total.

Takeaway: An error ends the stream: upstream is cancelled and the signal skips down to the first handler, which replaces the stream with a fallback or subscribes again.

Which operator for which failure?To replace a failure with a fixed value, use onErrorReturn. To switch to another publisher, use onErrorResume. To change the exception type, use onErrorMap. To try again, use retryWhen. To only observe it, use doOnError.A stream failsFixed value:onErrorReturnAnother publisher:onErrorResumeAnother exception:onErrorMapTry again:retryWhenOnly observe it:doOnError
Which operator for which failure?To replace a failure with a fixed value, use onErrorReturn. To switch to another publisher, use onErrorResume. To change the exception type, use onErrorMap. To try again, use retryWhen. To only observe it, use doOnError.A stream failsFixed value:onErrorReturnAnother publisher:onErrorResumeAnother exception:onErrorMapTry again:retryWhenOnly observe it:doOnError
Which operator for which failure?

In code

Mono<Price> price = client.get().uri("/price/{id}", id)
        .retrieve()
        .bodyToMono(Price.class)
        .timeout(Duration.ofSeconds(2))                        // per attempt
        .retryWhen(Retry.backoff(3, Duration.ofMillis(100))
                .filter(error -> error instanceof TimeoutException))
        .onErrorResume(error -> cache.findPrice(id));          // after retries
Recover, and retry only what can succeed
Flux<Result> results = Flux.fromIterable(ids)
        .concatMap(id -> process(id)
                .onErrorResume(error -> Mono.just(Result.failed(id))));
Keep the stream alive past one bad element
Operator order changes what a timeout coversA timeout placed before a retry limits each attempt, so a slow call gets several tries. A timeout placed after a retry limits the whole thing, so a slow first attempt ends everything.timeout(100).retry(2)Per attempt: 3 tries,fails at 300 msretry(2).timeout(100)In total: 1 try,fails at 100 ms
Operator order changes what a timeout coversA timeout placed before a retry limits each attempt, so a slow call gets several tries. A timeout placed after a retry limits the whole thing, so a slow first attempt ends everything.timeout(100).retry(2)Per attempt: 3 tries,fails at 300 msretry(2).timeout(100)In total: 1 try,fails at 100 ms
Operator order changes what a timeout covers
client.fetch(id)
    .doOnError(e -> log.warn("fetch {} failed", id, e))     // a side effect only: the error keeps going
    .onErrorMap(WebClientResponseException.NotFound.class, e -> new ProductNotFoundException(id));
Log with doOnError, translate with onErrorMap

Solve it

Retries turned a slow database into an outage

The gateway retries 3 times, the order service retries 3 times, and the inventory service retries 3 times, all at once. When the inventory database slows down, it receives up to 64 times the normal load and stops answering.

  1. Multiply the layers. Each layer makes up to 4 attempts, so three layers make up to 4 x 4 x 4 = 64 calls for one user request.
  2. Retry in one place. Keep retries at the layer closest to the failing dependency, and let the others fail fast.
  3. Retry only what can succeed. Timeouts and 503s are transient; a 400 or a 404 will fail the same way again. Filter on the error type.
  4. Space the attempts. Exponential backoff with jitter spreads retries out, so clients do not all return at the same instant.
  5. Bound the total and check. Put a timeout per attempt before the retry, then a fallback. In virtual time, count the attempts with StepVerifier.
Mono<Stock> stock(String sku) {
    return inventory.get(sku)
        .timeout(Duration.ofSeconds(1))                                  // per attempt: it sits before the retry
        .retryWhen(Retry.backoff(3, Duration.ofMillis(200))
            .jitter(0.5)
            .filter(e -> e instanceof TimeoutException || e instanceof ServiceUnavailableException))
        .onErrorResume(e -> Mono.just(Stock.unknown(sku)));             // degrade instead of failing the page
}
One retrying layer: per-attempt timeout, filtered backoff with jitter, then a fallback

How to answer

  • An error is terminal, so upstream is cancelled when it occurs.
  • onErrorMap changes the exception, and doOnError only observes it.
  • To keep a Flux going, handle the error inside flatMap or concatMap.
  • Both accept a type or predicate, so you can catch only some errors.

Common mistakes

  • Expecting a Flux to continue with the next element after onErrorResume. The fallback replaces the stream.
  • Using try/catch around a chain, which only sees errors thrown while assembling it.

Follow-up questions

How do you retry with backoff in Reactor?

Use retryWhen(Retry.backoff(3, Duration.ofMillis(100))). It subscribes again up to 3 times, doubling the wait to 100, 200 and 400 ms, with 50 percent jitter by default so clients do not retry in step. When it gives up, it fails with RetryExhaustedException, with the last error as its cause. Add filter so you only retry errors that can succeed.

  • By default it retries every error, including a 400, so add a filter.
  • maxBackoff caps the wait, and it has no cap by default.
  • Only retry idempotent operations, because the first attempt may have worked.
  • A retried Flux starts again, so its subscriber receives earlier elements twice.
  • onRetryExhaustedThrow rethrows the original error instead.
Retry.backoff(3, Duration.ofMillis(100))
     .maxBackoff(Duration.ofSeconds(2))
     .filter(e -> e instanceof TimeoutException)
     .onRetryExhaustedThrow((spec, signal) -> signal.failure());

See it in the infographic: An error signal travels down the pipeline

How do timeouts work, and does their position relative to a retry matter?

timeout(d) fails with TimeoutException if no element or terminal signal arrives within d, and it cancels upstream. Position matters. timeout(100).retry(2) limits each attempt, so a stuck call gets 3 tries and fails at 300 ms. retry(2).timeout(100) limits the whole thing, so it fails at 100 ms after one attempt. Usually you want both limits.

  • timeout(d, fallback) switches to a fallback instead of failing.
  • On a Flux, the limit applies to each gap between elements, not the total.
  • Cancelling stops waiting, and the remote side may still finish its work.

See it in the infographic: An error signal travels down the pipeline

Mono.just(call()).retry(2) does not call the service again when it fails. Why not?

Because Java ran call() once, while assembling the chain, and retry only subscribes again. If call() throws, the exception escapes before any Mono exists. If it returns, the value is fixed. Wrap it in Mono.fromCallable(() -> call()) or Mono.defer, so each subscription runs it again; a failing call then ran three times.

  • A retry re-subscribes, so it needs a source that does its work on subscribe.
  • WebClient is already lazy, so each retry sends a new request.

See it in the infographic: An error signal travels down the pipeline

What does onErrorContinue do, and why do people warn against it?

It drops the failing element and keeps going, so 1, 2, 3 failing on 2 gives 10 and 30. But only some operators support it, and it changes how operators upstream behave, which surprises people. Prefer onErrorResume inside flatMap, whose scope is plain to see.

What happens to an error nobody handles?

With no error consumer on subscribe, it does not throw to the caller. Reactor passes ErrorCallbackNotImplemented to onErrorDropped, which logs it. In WebFlux, the framework is the subscriber and turns the error into an error response, a 500 by default.

Check yourself

1. What does the subscriber receive?
Flux.just(1, 2, 3)
    .map(n -> { if (n == 2) throw new IllegalStateException(); return n; })
    .onErrorResume(e -> Flux.just(0))
    .subscribe(System.out::println);
Show answers
  • 1, 0: Correct. The error cancels upstream, and the fallback replaces what is left, so 3 never arrives.
  • 1, 0, 3: Incorrect. That would need the handler inside a flatMap, per element.
  • 1, then an error: Incorrect. onErrorResume handled it, so the subscriber sees a normal completion.
2. A call never answers. The chain is call.timeout(100 ms).retry(2). When does the subscriber see the failure?
Show answers
  • At about 300 ms, after 3 attempts: Correct. The timeout is upstream of the retry, so each attempt gets its own 100 ms.
  • At about 100 ms, after 1 attempt: Incorrect. That is retry(2).timeout(100), where the limit covers everything.
  • Never, because retry hides the timeout: Incorrect. Retries run out, and then the last error reaches the subscriber.