aiobreaker: Circuit Breaker for asyncio

1.2.0 · active · verified Thu Apr 16

aiobreaker is a Python implementation of the Circuit Breaker pattern, specifically designed for asynchronous applications using `asyncio`. It helps improve the resilience of microservices by preventing an application from repeatedly trying to execute an operation that is likely to fail, such as calling a service that is temporarily down. The current version is 1.2.0, with a stable, infrequent release cadence reflecting its focused scope.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to apply a `CircuitBreaker` to an `async` function that simulates failures. It shows how the breaker opens after `fail_max` attempts and how to catch `CircuitBreakerError` to implement fallback logic or notify users of service unavailability.

import asyncio
from aiobreaker import CircuitBreaker, CircuitBreakerError

# Configure a Circuit Breaker: open after 3 failures, stay open for 5 seconds
breaker = CircuitBreaker(fail_max=3, timeout_duration=5)

# Simulate an unreliable asynchronous service
failure_count = 0

@breaker
async def unreliable_service():
    global failure_count
    if failure_count < 4: # Intentionally fail 4 times to trip the breaker (fail_max=3)
        failure_count += 1
        print(f"Service attempt failed ({failure_count}/{breaker.fail_max})")
        raise ConnectionError("Simulated network issue")
    print("Service successful (after breaker resets/trips)")
    return "Data retrieved"

async def main():
    print("\n--- Starting service calls ---")
    for i in range(12):
        print(f"\nCall {i+1}:")
        try:
            result = await unreliable_service()
            print(f"Call successful: {result}")
        except CircuitBreakerError:
            print("CircuitBreaker is OPEN! Blocking service calls to prevent further load.")
        except ConnectionError as e:
            print(f"Call failed with transient error: {e}")
        await asyncio.sleep(1)

    print("\n--- All calls attempted ---")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →