CircuitBreaker¶
Circuit breaker pattern for preventing cascading failures.
Quick Example¶
from mamba_agents.errors import CircuitBreaker
breaker = CircuitBreaker(
name="model-api",
failure_threshold=5,
timeout=30.0,
)
# Use as context manager
async with breaker:
result = await call_api()
# Check state
if breaker.is_open:
print("Circuit is open")
# Get stats
stats = breaker.get_stats()
print(f"Failures: {stats.failure_count}")
# Manual reset
breaker.reset()
States¶
- Closed - Normal, requests pass through
- Open - Too many failures, requests rejected
- Half-Open - Testing if service recovered
Configuration¶
| Option | Type | Default | Description |
|---|---|---|---|
name |
str | Required | Unique identifier |
failure_threshold |
int | 5 | Failures to open |
timeout |
float | 30.0 | Seconds to stay open |
success_threshold |
int | 2 | Successes to close |
API Reference¶
CircuitBreaker
¶
Circuit breaker for protecting against cascading failures.
The circuit breaker monitors calls to a service and trips (opens) when failures exceed a threshold, preventing further calls until a timeout elapses.
States: - CLOSED: Normal operation, calls pass through - OPEN: Failures exceeded threshold, calls are rejected - HALF_OPEN: Testing recovery, limited calls allowed
Example
breaker = CircuitBreaker("model-api")
async def call_api(): async with breaker: return await api.call()
Or manually:¶
if breaker.allow_request(): try: result = await api.call() breaker.record_success() except Exception as e: breaker.record_failure(e)
Initialize the circuit breaker.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name for this circuit breaker.
TYPE:
|
config
|
Circuit breaker configuration.
TYPE:
|
Source code in src/mamba_agents/errors/circuit_breaker.py
allow_request
¶
Check if a request should be allowed.
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the request should proceed. |
Source code in src/mamba_agents/errors/circuit_breaker.py
record_success
¶
Record a successful call.
Source code in src/mamba_agents/errors/circuit_breaker.py
record_failure
¶
Record a failed call.
| PARAMETER | DESCRIPTION |
|---|---|
exception
|
The exception that occurred.
TYPE:
|
Source code in src/mamba_agents/errors/circuit_breaker.py
get_time_until_retry
¶
Get seconds until retry is allowed.
| RETURNS | DESCRIPTION |
|---|---|
float
|
Seconds until retry, 0 if allowed now. |
Source code in src/mamba_agents/errors/circuit_breaker.py
reset
¶
Force reset the circuit breaker to closed state.