v0.3.x · pyrogram_patch
Circuit Breaker
AsyncCircuitBreaker protects external calls (database, Redis, API) from cascading failures. When failures exceed a threshold the breaker opens and fast-fails subsequent calls for a cooldown period.
Basic Usage
from pyrogram_patch.circuit_breaker import AsyncCircuitBreaker
breaker = AsyncCircuitBreaker(
failure_threshold=5, # open after 5 consecutive failures
recovery_timeout=30, # try again after 30 seconds
)
async def fetch_user(user_id: int):
async with breaker:
return await db.get_user(user_id)protect() Decorator
async def send_notification(user_id, text):
await redis_client.publish(f"notify:{user_id}", text)
protected_notify = breaker.protect(send_notification)
# If the breaker is open, raises CircuitBreakerOpenError
await protected_notify(42, "Hello!")States
| State | Behaviour |
|---|---|
| Closed | Normal — all calls pass through |
| Open | Fast-fail — raises CircuitBreakerOpenError immediately |
| Half-open | One probe call allowed; closes on success, reopens on failure |
Configuration Reference
| Parameter | Default | Description |
|---|---|---|
failure_threshold | 5 | Consecutive failures before opening |
recovery_timeout | 60 | Seconds before half-open probe |
expected_exception | Exception | Which exception type counts as a failure |