What is the Circuit Breaker pattern?

The Circuit Breaker pattern protects a system from repeated calls to a failing service by temporarily stopping those calls and giving the failing service time to recover.

Key Points: • The circuit breaker wraps calls to a dependency and tracks the failure rate over a rolling window. • When failures exceed a threshold, the circuit "opens," and further calls fail immediately without hitting the struggling service. • After a configured wait period, the breaker moves to a "half-open" state and allows a limited number of test requests through to check if the dependency has recovered. • If the test requests succeed, the circuit "closes" again and normal traffic resumes; if they fail, it reopens and waits longer. • Libraries like Resilience4j (or historically Netflix Hystrix) implement this pattern in Spring Boot applications with minimal code.

Example: If a downstream Recommendations service starts timing out, a circuit breaker around calls to it opens after, say, five consecutive failures, so the caller immediately falls back to a default recommendation list instead of waiting on every request for a timeout.

Code Example:

CircuitBreakerConfig config = CircuitBreakerConfig.custom()
    .failureRateThreshold(50)
    .waitDurationInOpenState(Duration.ofSeconds(10))
    .slidingWindowSize(20)
    .build();

CircuitBreaker breaker = CircuitBreaker.of("recommendations", config);

Supplier<List<Item>> decorated = CircuitBreaker
    .decorateSupplier(breaker, recommendationsClient::fetch);

Interview Tip: A concise interview answer is:

"A circuit breaker monitors failures on calls to a dependency and, once they cross a threshold, opens and stops sending further requests, failing fast instead of piling up timeouts. After a cooldown it lets a few test requests through to check recovery before fully closing again. It's a key resilience pattern I'd implement with something like Resilience4j."