How a circuit breaker cycles through closed, open and half-open
1 / 4Closed
Step 1 of 4
Closed
Normal state: requests pass through and the breaker counts consecutive failures. A success resets the count to zero.
Step 2 of 4
Threshold hit
The failure count reaches the threshold, for example five in a row, and the circuit opens. A fallback response or model is used from now on.
Step 3 of 4
Open
Calls fail immediately without touching the service, so requests do not hang and the struggling service is not hammered. This lasts for the cooldown period.
Step 4 of 4
Half-open
After the cooldown, one probe request is let through. If it succeeds the circuit closes again; if it fails the circuit re-opens and the cooldown restarts.
Failing fast during the cooldown gives the downstream service room to recover.
Problem
When a downstream service fails, retrying every request keeps hammering it and slows everything down. The system never recovers.
Pattern
Track failures per downstream. When failures exceed a threshold, open the circuit and fail fast for a cooldown period, then half-open to test recovery.
Implementation
circuit_breaker.py
~249 tokens
import time
class CircuitBreaker:
def __init__(self, threshold=5, cooldown=30.0):
self.failures = 0
self.threshold = threshold
self.cooldown = cooldown
self.opened_at = None
def allow(self):
if self.opened_at is None:
return True
if time.time() - self.opened_at > self.cooldown:
# Half-open: allow one probe
return True
return False
def record_success(self):
self.failures = 0
self.opened_at = None
def record_failure(self):
self.failures += 1
if self.failures >= self.threshold:
self.opened_at = time.time()
breaker = CircuitBreaker()
def call_protected(fn, *args):
if not breaker.allow():
raise CircuitOpenError()
try:
result = fn(*args)
breaker.record_success()
return result
except Exception:
breaker.record_failure()
raise
Trade-offs
Prevents cascade failures
Fails fast instead of hanging
Can block traffic during transient blips if cooldown too long