Async Python Circuit Breaker implementation

Overview

aiocircuitbreaker

This is an async Python implementation of the circuitbreaker library.

Installation

The project is available on PyPI. Simply run:

$ pip install aiocircuitbreaker

Usage

This is the simplest example. Just decorate a async function with the @circuit decorator:

from aiocircuitbreaker import circuit

@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 failures
  • resets the failure count after every successful execution (while it is closed)
  • opens and prevents further executions after 5 subsequent failures
  • switches to half-open and allows one test-execution after 30 seconds recovery timeout
  • closes if the test-execution succeeded
  • considers all raised exceptions (based on class Exception) as an expected failure
  • is named "external_call" - the name of the function it decorates

What does failure mean?

A failure is a raised exception, which was not caught during the function call. By default, the circuit breaker listens for all exceptions based on the class Exception. 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 failure

It is important, to be as 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 an ConnectionError or a request Timeout.

If you are e.g. using the requests library (http://docs.python-requests.org/) for making HTTP calls, its RequestException class would be a great choice for the expected_exception parameter.

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.

Configuration

The following configuration options can be adjusted via decorator parameters. For example:

from aiocircuitbreaker import circuit

@circuit(failure_threshold=10, expected_exception=ConnectionError)
async def external_call():
    ...

failure threshold

By default, the circuit breaker opens after 5 subsequent failures. You can adjust this value with the failure_threshold parameter.

recovery timeout

By default, the circuit breaker stays open for 30 seconds to allow the integration point to recover. You can adjust this value with the recovery_timeout parameter.

expected exception

By default, the circuit breaker listens for all exceptions which are based on the Exception class. You can adjust this with the expected_exception parameter. It can be either an exception class or a tuple of exception classes.

name

By default, the circuit breaker name is empty string. You can adjust the name with parameter name.

fallback function

By default, the circuit breaker will raise a CircuitBreaker exception when the circuit is opened. You can instead specify a function (async function) to be called when the circuit is opened. This function can be specified with the fallback_function parameter and will be called with the same parameters as the decorated function would be.

Advanced Usage

If you apply circuit breakers to a couple of functions and you always set specific options other than the default values, you can extend the CircuitBreaker class and create your own circuit breaker subclass instead:

from aiocircuitbreaker import CircuitBreaker

class MyCircuitBreaker(CircuitBreaker):
    FAILURE_THRESHOLD = 10
    RECOVERY_TIMEOUT = 60
    EXPECTED_EXCEPTION = RequestException

Now you have two options to apply your circuit breaker to a function. As an Object directly:

@MyCircuitBreaker()
async 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)
async def external_call():
    ...
You might also like...
Reference python implementation of Chia pool operations for pool operators
Reference python implementation of Chia pool operations for pool operators

This repository provides a sample server written in python, which is meant to server as a basis for a Chia Pool. While this is a fully functional implementation, it requires some work in scalability and security to run in production.

A fast python implementation of DTU MVS 2014 evaluation

DTUeval-python A python implementation of DTU MVS 2014 evaluation. It only takes 1min for each mesh evaluation. And the gap between the two implementa

Double Pendulum implementation in Python, now with added pendulums and trails :D
Double Pendulum implementation in Python, now with added pendulums and trails :D

Double Pendulum Using Curses in Python. A nice relaxing double pendulum simulation using ASCII, able to simulate multiple pendulums at once, and provi

Demo of a WAM Prolog implementation in Python

Prol: WAM demo This is a simplified Warren Abstract Machine (WAM) implementation for Prolog, that showcases the main instructions, compiling, register

Python implementation of Newton's Fractal

Newton's Fractal Animates Newton's fractal between two polynomials of the same order. Inspired by this video by 3Blue1Brown. Example fractals can be f

Python implementation for Active Directory certificate abuse

Certipy is a Python tool to enumerate and abuse misconfigurations in Active Directory Certificate Services (AD CS). Based on the C# variant Ce

Yet another Python Implementation of the Elo rating system.

Python Implementation - Elo Rating System Yet another Python Implementation of the Elo rating system (how innovative am I right?). Only supports 1vs1

A Python software implementation of the Intel 4004 processor
A Python software implementation of the Intel 4004 processor

Pyntel4004 A Python software implementation of the Intel 4004 processor. General Information Two pass assembler using the original mnemonics, directiv

Python implementation of an automatic parallel parking system in a virtual environment, including path planning, path tracking, and parallel parking
Python implementation of an automatic parallel parking system in a virtual environment, including path planning, path tracking, and parallel parking

Automatic Parallel Parking: Path Planning, Path Tracking & Control This repository contains a python implementation of an automatic parallel parking s

Comments
  • [request] add aiocircuitbreaker to Conda-forge

    [request] add aiocircuitbreaker to Conda-forge

    Hi @sgenya, we'd like to use aiocircuitbreaker in https://github.com/RECETOX/MSMetaEnhancer. However, we distribute our library through Conda and that requires all the dependencies to be available via Conda. We'd appreciate if you could publish your library to Conda-forge. This will also increase its accessibility!

    Conda-forge have documented how to publish a package here: https://conda-forge.org/docs/maintainer/adding_pkgs.html#contributing-packages

    Also since your library is already on PyPi it should be easy to autogenerate a Conda recipe with grayskull: https://github.com/conda-incubator/grayskull

    You can check out our library for an example of a Conda recipe: https://github.com/RECETOX/MSMetaEnhancer/blob/main/conda/meta.yaml

    If you need assistance with any of that I'd be happy to help :)

    opened by maximskorik 2
Releases(2.0.0)
Owner
null
Python module for creating the circuit simulation definitions for Elmer FEM

elmer_circuitbuilder Python module for creating the circuit simulation definitions for Elmer FEM. The circuit definitions enable easy setup of coils (

null 5 Oct 3, 2022
Simple package to make requests throughout Tor with circuit renewal.

AutoTor Table of Contents About the Project Contents Dependencies Getting Started Installation Coding Contributing About the Project Simple package to

Salvador Belenguer 6 Jan 1, 2023
Plugin to manage site, circuit and device diagrams and documents in Netbox

Netbox Documents Plugin A plugin designed to faciliate the storage of site, circuit and device specific documents within NetBox Note: Netbox v3.2+ is

Jason Yates 38 Dec 24, 2022
An async API wrapper for Dress To Impress written in Python.

dti.py An async API wrapper for Dress To Impress written in Python. Some notes: For the time being, there are no front-facing docs for this beyond doc

Steve C 1 Dec 14, 2022
Async-first dependency injection library based on python type hints

Dependency Depression Async-first dependency injection library based on python type hints Quickstart First let's create a class we would be injecting:

Doctor 8 Oct 10, 2022
This is a survey of python's async concurrency features by example.

Survey of Python's Async Features This is a survey of python's async concurrency features by example. The purpose of this survey is to demonstrate tha

Tyler Lovely 4 Feb 10, 2022
Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns

Diffraction Simulations - Angular Spectrum Method Implementation of the Angular Spectrum method in Python to simulate Diffraction Patterns with arbitr

Rafael de la Fuente 276 Dec 30, 2022
Python implementation of the ASFLIP advection method

This is a python implementation of the ASFLIP advection method . We would like to hear from you if you appreciate this work.

Raymond Yun Fei 133 Nov 13, 2022
A Gura parser implementation for Python

Gura parser This repository contains the implementation of a Gura format parser in Python. Installation pip install gura-parser Usage import gura gur

JWare Solutions 19 Jan 25, 2022
A python implementation of differentiable quality diversity.

Differentiable Quality Diversity This repository is the official implementation of Differentiable Quality Diversity.

ICAROS 41 Nov 30, 2022