Video in progress

Strong Middle 🌱 Spring

When does a Resilience4j circuit breaker kick in, and how do you configure it in Spring Boot?

Three states: CLOSED, requests pass and failures are counted; if the failure rate exceeds the threshold it goes OPEN, and requests are rejected immediately; after the wait time it goes HALF_OPEN, a few trial requests are let through, and depending on the result it closes or opens again.

📖 Answer

The goal is to stop hammering a dead service and to avoid losing your own threads waiting on timeouts.

resilience4j:
  circuitbreaker:
    instances:
      inventory:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 50
        minimum-number-of-calls: 20
        failure-rate-threshold: 50
        slow-call-duration-threshold: 2s
        slow-call-rate-threshold: 80
        wait-duration-in-open-state: 30s
        permitted-number-of-calls-in-half-open-state: 5
        ignore-exceptions:
          - uz.shop.inventory.SkuNotFoundException
@Service
class StockService {
    @CircuitBreaker(name = "inventory", fallbackMethod = "unknownStock")
    StockDto stock(String sku) {
        return inventoryClient.stock(sku);
    }

    private StockDto unknownStock(String sku, CallNotPermittedException e) {
        return StockDto.unknown(sku); // the UI shows "availability is being checked"
    }
}

What I look at when configuring:

  • Business errors shouldn't be counted. A 404 "no such product" means the service is healthy. Count only technical errors with ignore-exceptions or record-exceptions.
  • Slow calls are failures too. The slow-call-* settings also account for responses that are very slow but haven't reached the timeout.
  • minimum-number-of-calls. If 2 of 3 requests fail at night, the breaker shouldn't open.
  • Keep the fallback honest. An answer from a stale cache, yes; falsely saying "it's in stock", no.
  • Aspect order. If Retry is outside the breaker (the default), every attempt is counted separately; Resilience4j's default order is: Retry outermost, then CircuitBreaker, RateLimiter, TimeLimiter, Bulkhead.

Watch state changes through /actuator/circuitbreakers and the resilience4j_circuitbreaker_state metric. A breaker opening should be an alert.