Video in progress

Strong Junior 🧩 Microservices

If `@Retry` and `@CircuitBreaker` are put on the same method in Resilience4j, in what order do they run, and what does that affect?

In the default order, Retry is on the outside and CircuitBreaker on the inside. So each retry passes through the breaker and is counted separately; once the breaker opens, later attempts immediately get a CallNotPermittedException.

📖 Answer

The Resilience4j Spring Boot module wraps the aspects in this order (from outside in):

Retry ( CircuitBreaker ( RateLimiter ( TimeLimiter ( Bulkhead ( method ) ) ) ) )
@Retry(name = "payment")
@CircuitBreaker(name = "payment", fallbackMethod = "fallback")
public PaymentDto get(long id) {
    return paymentClient.get(id);
}

What this means:

  • if one user request makes 3 attempts, 3 failures are counted in the breaker's sliding window, so the breaker opens sooner;
  • if the breaker is open, the retry may also retry on CallNotPermittedException, wasting time. So it helps to add this exception to ignore-exceptions.
resilience4j:
  retry:
    instances:
      payment:
        ignore-exceptions:
          - io.github.resilience4j.circuitbreaker.CallNotPermittedException

You can change the order too (resilience4j.retry.retry-aspect-order and resilience4j.circuitbreaker.circuit-breaker-aspect-order). But don't do it without a reason: the default order is right for most cases.

Watch the fallback too: it runs at the layer of whichever annotation it's on. If a fallback on the breaker returns a value on every attempt, the retry never kicks in.