Circuit Breaker Pattern
IntermediateThe circuit breaker pattern prevents cascading failures by stopping calls to a failing downstream service. It transitions through Closed → Open → Half-Open states, giving the failing service time to recover.
Overview
In a distributed system, when a downstream service fails or responds slowly, the calling service can exhaust its thread pool waiting for timeouts, cascading the failure. The circuit breaker pattern wraps remote calls with a state machine. In the Closed state, requests pass through normally — failures are counted. When failures exceed a threshold, the circuit trips to Open — all requests fail immediately (fast-fail) without contacting the downstream service. After a configurable timeout, the circuit moves to Half-Open — a limited number of trial requests are allowed. If they succeed, the circuit closes; if they fail, it reopens. This pattern protects the calling service, gives the downstream service time to recover, and provides fallback responses. Popular implementations include Resilience4j (Java), Hystrix (deprecated), Envoy proxy (automatic circuit breaking), and Istio service mesh.
State Machine
The circuit breaker transitions between three states: Closed (normal), Open (fast-fail), and Half-Open (testing recovery). Thresholds, timeouts, and trial request counts are configurable.
// Circuit breaker states
//
// ┌────────────────────────────────────────┐
// │ CLOSED │
// │ (requests flow normally) │
// │ Failure counter incremented on error │
// └──────────────┬─────────────────────────┘
// │ failure threshold reached
// ▼
// ┌────────────────────────────────────────┐
// │ OPEN │
// │ (all requests fail immediately) │
// │ Return fallback / error │
// │ Timer starts (e.g. 30 seconds) │
// └──────────────┬─────────────────────────┘
// │ timeout expires
// ▼
// ┌────────────────────────────────────────┐
// │ HALF-OPEN │
// │ (allow N trial requests) │
// │ If trials succeed → CLOSED │
// │ If trials fail → OPEN │
// └────────────────────────────────────────┘Implementation with Resilience4j
Resilience4j is the standard circuit breaker library for Java/Spring Boot. It provides annotations, programmatic API, and integration with Spring Boot Actuator for monitoring.
// application.yml — Resilience4j circuit breaker config
resilience4j:
circuitbreaker:
instances:
paymentService:
slidingWindowSize: 10
failureRateThreshold: 50 # open after 50% failures
waitDurationInOpenState: 30s # stay open for 30s
permittedNumberOfCallsInHalfOpenState: 3
slowCallRateThreshold: 80
slowCallDurationThreshold: 2s
// Java service with circuit breaker
@Service
public class PaymentService {
private final PaymentClient client;
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
public PaymentResult charge(PaymentRequest req) {
return client.charge(req); // remote call
}
// Fallback when circuit is open or call fails
private PaymentResult paymentFallback(PaymentRequest req, Throwable t) {
log.warn("Payment circuit open, queuing for retry: {}", req.getOrderId());
retryQueue.enqueue(req);
return PaymentResult.pending(req.getOrderId());
}
}Service Mesh Circuit Breaking
Service meshes (Istio, Envoy) implement circuit breaking at the infrastructure level — no application code changes needed. They detect outlier pods and eject them from the load balancer pool.
// Istio DestinationRule — circuit breaking + outlier detection
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
name: payment-service
spec:
host: payment-service
trafficPolicy:
connectionPool:
tcp:
maxConnections: 100
http:
h2UpgradePolicy: DEFAULT
maxRequestsPerConnection: 10
outlierDetection:
consecutive5xxErrors: 5 # eject after 5 consecutive 5xx
interval: 10s # check every 10s
baseEjectionTime: 30s # eject for 30s
maxEjectionPercent: 50 # never eject more than 50% of pods
// No code changes — Envoy sidecar handles circuit breaking
// Metrics available in Prometheus/Grafana for monitoringKey Points to Remember
- 1Circuit breaker prevents cascading failures by fast-failing when a downstream service is unhealthy.
- 2Three states: Closed (normal), Open (fast-fail), Half-Open (testing recovery).
- 3Always implement fallback logic — return cached data, queue for retry, or return a degraded response.
- 4Resilience4j is the standard Java library; Istio/Envoy provide infrastructure-level circuit breaking.
- 5Monitor circuit breaker state transitions — an open circuit is a critical signal that something is wrong.
Interview Questions
Sign in to ask AriaWhat is the circuit breaker pattern and why is it needed?
Explain the three states of a circuit breaker.
How does Resilience4j implement circuit breaking in Spring Boot?
How would you configure circuit breaking in an Istio service mesh?
Design a fault-tolerant payment processing system with circuit breakers and retries.
Ask Aria about Circuit Breaker Pattern
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.