पाठ 8 / 25

Circuit Breakers in Resilience4j and Polly

Configure production circuit breakers with common libraries.

Use a library, configure it deliberately

Writing your own breaker is a good exercise but production code should use a maintained library. In Java, Resilience4j (the successor to Netflix Hystrix, which is in maintenance mode) offers circuit breakers, retries, rate limiters, bulkheads and time limiters that can be composed, with Spring Boot integration through annotations and configuration. Its breaker supports count-based or time-based sliding windows, failure-rate and slow-call-rate thresholds, a minimum number of calls, wait duration in open state, and permitted calls in half-open state. In .NET, Polly (v8) builds resilience pipelines that combine retry, circuit breaker, timeout, rate limiter and hedging strategies, and Microsoft.Extensions.Http.Resilience adds a standard pipeline to HttpClient with one call. In Node.js, libraries such as opossum and cockatiel fill the same role. Whatever the library, export breaker state changes and metrics to your monitoring.

Resilience4j configuration in Spring Boot

A breaker and retry for the payments client, plus the annotated method.

resilience4j:
  circuitbreaker:
    instances:
      payments:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 50
        minimum-number-of-calls: 20
        failure-rate-threshold: 50
        slow-call-duration-threshold: 800ms
        slow-call-rate-threshold: 60
        wait-duration-in-open-state: 30s
        permitted-number-of-calls-in-half-open-state: 5
  retry:
    instances:
      payments:
        max-attempts: 3
        wait-duration: 100ms
        enable-exponential-backoff: true
        exponential-backoff-multiplier: 2
        retry-exceptions: [java.io.IOException, java.util.concurrent.TimeoutException]

# Java:
# @CircuitBreaker(name = "payments", fallbackMethod = "paymentPending")
# @Retry(name = "payments")
# public PaymentResult charge(Order order) { ... }

A shop shutter with a peephole

When trouble starts outside, the shopkeeper pulls the shutter down (open). After a while they lift it a little and let one or two customers in to check things have calmed (half-open) before opening fully.

त्वरित जाँच: Which Resilience4j setting makes very slow calls count against the breaker even if they eventually succeed?

  • permitted-number-of-calls-in-half-open-state
  • max-attempts
  • wait-duration
  • slow-call-duration-threshold with slow-call-rate-threshold
Answer

slow-call-duration-threshold with slow-call-rate-threshold — Slow-call thresholds let the breaker open when a dependency becomes too slow, not only when it errors.