API / Microservices Design Patterns Interview Questions
How does the Circuit Breaker pattern work and what are its three states?
The Circuit Breaker pattern prevents cascading failures by detecting when a downstream service is unavailable and fast-failing subsequent calls instead of letting them queue up and exhaust threads. It is named after the electrical circuit breaker that trips when current exceeds a safe threshold.
The pattern has three states:
- Closed (normal) — calls pass through to the downstream service. The breaker counts failures. When the failure rate (or failure count) exceeds a configured threshold within a time window, the breaker trips to Open.
- Open — all calls are immediately rejected with an error (or the Fallback is invoked) without contacting the downstream service. A timer starts. This gives the failing service time to recover without being bombarded with traffic.
- Half-Open — after the timer expires, the breaker allows a limited number of probe requests through. If they succeed, the breaker transitions back to Closed. If they fail, it returns to Open.
// Resilience4j Circuit Breaker (Java) CircuitBreakerConfig config = CircuitBreakerConfig.custom() .failureRateThreshold(50) // open if >50% fail .waitDurationInOpenState(Duration.ofSeconds(30)) .permittedNumberOfCallsInHalfOpenState(5) .slidingWindowSize(10) .build(); CircuitBreaker cb = CircuitBreakerRegistry.of(config) .circuitBreaker("inventoryService"); Supplier<Stock> decorated = CircuitBreaker .decorateSupplier(cb, () -> inventoryClient.getStock(sku)); Try<Stock> result = Try.ofSupplier(decorated) .recover(CallNotPermittedException.class, e -> defaultStock());
The circuit breaker is most effective when combined with a Fallback (Q31) — when the circuit is Open, the fallback returns a cached or degraded response so the caller can still serve the request in a degraded mode rather than propagating a hard error to the user.
More Related questions...