Python Circuit Breaker

2.1.3 · active · verified Thu Apr 09

A Python implementation of the Circuit Breaker pattern, designed to prevent applications from repeatedly trying to perform an operation that is likely to fail. It supports both synchronous and asynchronous functions and has been classified as a 'Critical Project' on PyPI. The current version is 2.1.3.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `@circuit` decorator to protect a potentially unreliable synchronous function. It configures the circuit to trip after 3 failures (`fail_max=3`) and attempt to reset after 5 seconds (`reset_timeout=5`). It also shows how to exclude certain exceptions from tripping the circuit and handling both the underlying service errors and `CircuitBreakerError` when the circuit is open.

import time
from circuitbreaker import circuit

# Define a service call that might fail
def unreliable_service():
    # Simulate failure 75% of the time
    if time.time() % 4 < 3:
        raise ConnectionError("Service is currently unavailable!")
    print("Service call successful!")
    return "Data from service"

# Decorate the unreliable service call with a circuit breaker
# Trips after 3 failures, resets after 5 seconds
@circuit(fail_max=3, reset_timeout=5, exclude=[ValueError])
def get_data():
    return unreliable_service()

print("--- Circuit Breaker Quickstart ---")
for i in range(10):
    print(f"Attempt {i+1}:")
    try:
        result = get_data()
        print(f"  Result: {result}")
    except ConnectionError as e: # Handle the underlying service error
        print(f"  Caught service error: {e}")
    except Exception as e: # Catch CircuitBreakerError or other unexpected errors
        print(f"  Caught general error from circuit: {e}")
    time.sleep(1)

view raw JSON →