Circuit breaker stops calling failing services after N failures — prevents cascading failures across services.
Circuit Breaker Pattern
# States: CLOSED -> OPEN -> HALF-OPEN -> CLOSED
# CLOSED: requests pass through normally
# OPEN: service failing, reject immediately (fast fail)
# HALF-OPEN: send one request to test recovery
import pybreaker
breaker = pybreaker.CircuitBreaker(
fail_max=5, # open after 5 consecutive failures
reset_timeout=30 # try half-open after 30 seconds
)
@breaker
def call_payment(order_id: int) -> dict:
return httpx.post("http://payment-svc/charge",
json={"order_id":order_id},
timeout=5.0).json()
try:
result = call_payment(order_id)
except pybreaker.CircuitBreakerError:
# Circuit OPEN -- fail fast, use fallback
return {"status":"queued","message":"Retry shortly"}