Package: circuitbreaker
CircuitBreakerThis is a Python implementation of the “Circuit Breaker” Pattern (https://martinfowler.com/bliki/CircuitBreaker.html).
Inspired by Michael T. Nygard’s highly recommendable bookRelease It!(https://pragprog.com/titles/mnee2/release-it-second-edition/).InstallationThe project is available on PyPI. Simply run:$ pip install circuitbreakerUsageThis is the simplest example. Just decorate a function with the@circuitdecorator:from circuitbreaker import circuit

@circuit
def external_call():
    ...Async functions are also supported:@circuit
async def external_call():
    ...This decorator sets up a circuit breaker with the default settings. The circuit breaker:monitors the function execution and counts failuresresets the failure count after every successful execution (while it is closed)opens and prevents further executions after 5 subsequent failuresswitches to half-open and allows one test-execution after 30 seconds recovery timeoutcloses if the test-execution succeededconsiders all raised exceptions (based on classException) as an expected failureis named “external_call” - the name of the function it decoratesWhat doesfailuremean?Afailureis a raised exception, which was not caught during the function call.
By default, the circuit breaker listens for all exceptions based on the classException.
That means, that all exceptions raised during the function call are considered as an
“expected failure” and will increase the failure count.Get specific about the expected failureIt is important, to beas specific as possible, when defining the expected exception.
The main purpose of a circuit breaker is to protect your distributed system from a cascading failure.
That means, you probably want to open the circuit breaker only, if the integration point on the other
end is unavailable. So e.g. if there is anConnectionErroror a requestTimeout.If you are e.g. using the requests library (https://docs.python-requests.org/) for making HTTP calls,
itsRequestExceptionclass would be a great choice for theexpected_exceptionparameter.The logic for treating thrown exceptions as failures can also be customized by passing a callable. The
callable will be passed the exception type and value, and should return True if the exception should be
treated as a failure.All recognized exceptions will be re-raised anyway, but the goal is, to let the circuit breaker only
recognize those exceptions which are related to the communication to your integration point.When it comes to monitoring (seeMonitoring), it may lead to falsy conclusions, if a
circuit breaker opened, due to a localOSErrororKeyError, etc.ConfigurationThe following configuration options can be adjusted via decorator parameters. For example:from circuitbreaker import circuit

@circuit(failure_threshold=10, expected_exception=ConnectionError)
def external_call():
    ...failure thresholdBy default, the circuit breaker opens after 5 subsequent failures. You can adjust this value with thefailure_thresholdparameter.recovery timeoutBy default, the circuit breaker stays open for 30 seconds to allow the integration point to recover.
You can adjust this value with therecovery_timeoutparameter.expected exceptionBy default, the circuit breaker listens for all exceptions which are based on theExceptionclass.
You can adjust this with theexpected_exceptionparameter. It can be either an exception class, an iterable of an exception classes,
or a callable.Use a callable if the logic to flag exceptions as failures is more complex than a type check. For example:# Assume we are using the requests library
def is_not_http_error(thrown_type, thrown_value):
    return issubclass(thrown_type, RequestException) and not issubclass(thrown_type, HTTPError)

def is_rate_limited(thrown_type, thrown_value):
    return issubclass(thrown_type, HTTPError) and thrown_value.status_code == 429

@circuit(expected_exception=is_not_http_error)
def call_flaky_api(...):
    rsp = requests.get(...)
    rsp.raise_for_status()
    return rsp

@circuit(expected_exception=is_rate_limited)
def call_slow_server(...):
    rsp = requests.get(...)
    rsp.raise_for_status()
    return rsp
    ```nameBy default, the circuit breaker name is the name of the function it decorates. You can adjust the name with parametername.fallback functionBy default, the circuit breaker will raise aCircuitBreakerexception when the circuit is opened.
You can instead specify a function to be called when the circuit is opened. This function can be specified with thefallback_functionparameter and will be called with the same parameters as the decorated function would be.The fallback type of call must also match the decorated function. For instance, if the decorated function is an
async generator, thefallback_functionmust be an async generator as well.Advanced UsageIf you apply circuit breakers to a couple of functions and you always set specific options other than the default values,
you can extend theCircuitBreakerclass and create your own circuit breaker subclass instead:from circuitbreaker import CircuitBreaker

class MyCircuitBreaker(CircuitBreaker):
    FAILURE_THRESHOLD = 10
    RECOVERY_TIMEOUT = 60
    EXPECTED_EXCEPTION = RequestExceptionNow you have two options to apply your circuit breaker to a function. As an Object directly:@MyCircuitBreaker()
def external_call():
    ...Please note, that the circuit breaker class has to be initialized, you have to use a class instance as decorator (@MyCircuitBreaker()), not the class itself (@MyCircuitBreaker).Or via the decorator proxy:@circuit(cls=MyCircuitBreaker)
def external_call():
    ...MonitoringTo keep track of the health of your application and the state of your circuit breakers, every circuit breaker registers itself at theCircuitBreakerMonitor. You can receive all registered circuit breakers viaCircuitBreakerMonitor.get_circuits().To get an aggregated health status, you can ask the Monitor viaCircuitBreakerMonitor.all_closed(). Or you can retrieve the currently open circuits viaCircuitBreakerMonitor.get_open()and the closed circuits viaCircuitBreakerMonitor.get_closed().