The Circuit Breaker pattern monitors calls to a service and temporarily stops sending requests to it once failures exceed a threshold, preventing cascading failures and giving the failing service time to recover.
Key Points: • In the closed state, calls pass through normally while the breaker tracks the failure rate. • Once failures exceed a configured threshold, the breaker trips to the open state and immediately fails calls without attempting the request, protecting both the caller and the struggling service. • After a timeout, the breaker moves to half-open and allows a limited number of test requests through to see if the service has recovered. • It prevents resource exhaustion in the caller — without a circuit breaker, threads or connections can pile up waiting on a slow or dead service. • Libraries like Resilience4j (Spring Boot) or Hystrix (legacy) implement this pattern, usually combined with fallback methods.
Example: If the Payment Service starts timing out on 60% of requests, the circuit breaker trips open so the Order Service immediately returns a fallback response ("payment temporarily unavailable") instead of piling up threads waiting on a dead dependency.
Code Example:
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResponse charge(PaymentRequest request) {
return paymentClient.charge(request);
}
public PaymentResponse paymentFallback(PaymentRequest request, Throwable t) {
return PaymentResponse.unavailable();
}Interview Tip: A concise interview answer is:
"A circuit breaker tracks failures on calls to a dependency and, once a threshold is crossed, trips open to stop sending requests to it, giving it time to recover instead of piling up failing calls. It improves resilience by containing a failure to one service instead of letting it cascade and exhaust resources across the whole system."