Core Concept and Purpose
A circuit breaker is a design pattern that prevents an application from performing operations that are likely to fail, functioning analogously to an electrical circuit breaker that trips when current exceeds safe levels. In microservices architectures, circuit breakers protect systems from cascading failures by monitoring the health of service calls and stopping requests to failing services before resources are exhausted.
The fundamental purpose is threefold: prevent resource exhaustion through repeated calls to failing services, reduce latency by failing fast rather than waiting for timeouts, and enable graceful degradation by allowing systems to operate in a reduced-capacity state rather than complete failure.
The Three States of Circuit Breakers
Circuit breakers operate in three distinct states, each with specific behaviors and transition criteria:
Closed State represents normal operation. In this state, all requests pass through to the target service without interference. The circuit breaker monitors the success and failure rates of these requests. When the failure rate remains below a configured threshold, the circuit remains closed. This state is the default and desired operational mode for healthy services. Metrics are continuously collected but do not impede request flow.
Open State is triggered when failure metrics exceed thresholds. Once opened, the circuit breaker immediately rejects all incoming requests without attempting to call the target service. This rejection happens synchronously and rapidly, returning an error or executing fallback logic. No requests reach the failing service, preventing resource waste and cascading effects. The circuit breaker records the timestamp of the state transition to enable eventual recovery attempts.
Half-Open State serves as a controlled recovery mechanism. After a configurable timeout period in the open state, the circuit breaker transitions to half-open, allowing a limited number of test requests through to the target service. These probe requests determine whether the service has recovered. If these test requests succeed, the circuit transitions back to closed. If they fail, the circuit returns to open and the timeout period resets.
Failure Detection Mechanisms
Failure detection in circuit breakers relies on multiple signals that indicate service degradation:
Response-based detection monitors HTTP status codes, exception types, and response timeouts. A service returning 5xx status codes or timing out indicates failure. The circuit breaker counts consecutive failures or failures within a rolling time window. For example, if five consecutive requests fail or ten failures occur within a one-minute window, the failure threshold is exceeded.
Latency-based detection tracks response times and identifies when services slow significantly. A service responding in 5 seconds instead of 50 milliseconds indicates degradation even if responses eventually succeed. Slow responses consume resources and degrade user experience, warranting circuit breaker intervention.
Custom health metrics allow domain-specific failure detection. In an agent swarm context, an agent might report its own health status, queue depth, or CPU utilization. The circuit breaker can open based on these custom signals rather than just observing request failures.
State Transitions and Timing
Transitions between states follow strict rules designed to prevent oscillation and enable recovery:
Closed to Open transition occurs when failure metrics exceed thresholds. Configuration parameters specify these thresholds—for instance, "open after 5 consecutive failures" or "open after 50% failure rate in the last 100 requests." The transition is immediate upon threshold breach.
Open to Half-Open transition happens after a configurable timeout, typically ranging from 30 seconds to several minutes. This timeout prevents the circuit from immediately retrying a service that just failed, allowing time for the service to recover and clear any backlog.
Half-Open to Closed transition occurs when test requests succeed, indicating recovery. Configuration specifies how many successful test requests are needed—often just one or two to confirm stability.
Half-Open to Open transition occurs immediately when test requests fail, resetting the timeout counter and preventing premature recovery attempts.
Real-World Example: Payment Processing Service
Consider a microservices system where an order service depends on a payment processing service. Initially, the circuit breaker is closed and requests flow normally. The payment service experiences a database connection pool exhaustion, causing timeouts on all requests.
The circuit breaker detects this failure pattern—perhaps 10 consecutive timeouts—and transitions to open. Subsequent order requests immediately receive a rejection from the circuit breaker rather than waiting 30 seconds for a timeout. This prevents resource exhaustion in the order service.
After two minutes, the circuit breaker transitions to half-open and allows a single test request through. If the payment service has recovered and responds successfully, the circuit closes and normal operation resumes. If the test fails, the circuit reopens for another two minutes.