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

StateBehaviour
ClosedNormal — all calls pass through
OpenFast-fail — raises CircuitBreakerOpenError immediately
Half-openOne probe call allowed; closes on success, reopens on failure

Configuration Reference

ParameterDefaultDescription
failure_threshold5Consecutive failures before opening
recovery_timeout60Seconds before half-open probe
expected_exceptionExceptionWhich exception type counts as a failure