Circuit Breaker and Resilience4j

Difficulty: Advanced

Question

Your order service calls a payment service that is slow and starts timing out. How do you prevent a cascading failure using a circuit breaker?

Answer

Here is the failure story that motivates the pattern. Payment service becomes slow. Every order request now waits ten seconds for a response. Threads in the order service pile up waiting, the thread pool exhausts, and suddenly the order service cannot serve any request, even ones that do not need payments. Then the services calling order service fail the same way. One sick dependency has taken down the whole system. That is a cascading failure, and the circuit breaker is the mechanism that stops it.

The idea comes from the electrical fuse box. When a fault is detected, the breaker trips and cuts the circuit, so the damage cannot spread. A software circuit breaker sits around a remote call and tracks recent outcomes. It has three states. CLOSED is normal: calls pass through and results are recorded in a sliding window. When the failure rate, or the slow-call rate, crosses a threshold, for example 50 percent of the last 20 calls, it moves to OPEN. In OPEN, calls fail immediately without touching the remote service, typically for a configured wait duration such as 30 seconds. This gives the struggling service time to recover and frees your threads instantly. After the wait it moves to HALF_OPEN, letting a few trial calls through. If they succeed the breaker returns to CLOSED; if they fail it opens again.

Resilience4j is the standard Java library and the successor to Netflix Hystrix, which is in maintenance mode. It is lightweight, functional, and integrated with Spring Boot through resilience4j-spring-boot3 and Actuator metrics. You annotate a method with @CircuitBreaker(name = "payment", fallbackMethod = "paymentFallback") and configure thresholds in application.yml. The fallback method has the same signature plus an exception parameter, and returns something sensible: a cached value, a default, or a friendly failure like marking the order as pending payment and retrying later.

A circuit breaker is one of several resilience patterns that work together. Timeouts come first, because without a timeout you would wait forever, so configure connect and read timeouts on your HTTP client. Retry re-attempts transient failures, but use exponential backoff and jitter and limit attempts, and only retry idempotent operations; retrying a non-idempotent payment could charge a customer twice unless you use an idempotency key. A bulkhead limits concurrent calls to a dependency, isolating it, like watertight compartments in a ship. A rate limiter caps call frequency. The order of decoration matters: typically retry wraps circuit breaker, which wraps the timeout and bulkhead.

Interview follow-ups often ask what to return in the fallback. Be careful: a silent default for something critical, like pretending the payment succeeded, is dangerous. Fail explicitly for critical paths and degrade gracefully for non-critical ones such as recommendations. Also monitor the breaker state via Actuator's circuitbreakers endpoint and metrics, and alert when it opens, since an open breaker is a signal that a dependency needs attention.

Code examples

Resilience4j on a payment call

# application.yml
resilience4j:
  circuitbreaker:
    instances:
      payment:
        slidingWindowSize: 20
        failureRateThreshold: 50
        slowCallDurationThreshold: 2s
        slowCallRateThreshold: 60
        waitDurationInOpenState: 30s
        permittedNumberOfCallsInHalfOpenState: 3
  retry:
    instances:
      payment:
        maxAttempts: 3
        waitDuration: 500ms
        enableExponentialBackoff: true

@Service
@Slf4j
public class PaymentClientService {
    private final PaymentClient client;
    public PaymentClientService(PaymentClient client) { this.client = client; }

    @CircuitBreaker(name = "payment", fallbackMethod = "paymentFallback")
    @Retry(name = "payment")
    public PaymentResponse charge(PaymentRequest req) {
        return client.charge(req);
    }

    // same parameters + Throwable
    private PaymentResponse paymentFallback(PaymentRequest req, Throwable t) {
        log.warn("Payment unavailable for order {}: {}", req.orderId(), t.toString());
        return PaymentResponse.pending(req.orderId());     // degrade gracefully
    }
}

While OPEN, calls skip the network and go straight to the fallback, protecting threads and giving payment service room to recover.

Key points

Common follow-up questions

Interview tips

Concepts covered

Circuit Breaker, Resilience4j, Retry, Fallback

More Spring Boot questions