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)
Control System Packer is a lightweight, low-level program to transform energy equations into the compact libraries for control systems.

Control System Packer is a lightweight, low-level program to transform energy equations into the compact libraries for control systems. Packer supports Python 🐍 , C 💻 and C++ 💻 libraries.

mirnanoukari 31 Sep 15, 2022
Bitflip Fault Simulation Platform by Daniele Rizzieri (2021)

BFSP [v1.05] Bitflip Fault Simulation Platform by Daniele Rizzieri (2021) The platform injects a random bitflip in each of N copies of a binary file.

Daniele Rizzieri 2 Nov 05, 2022
LinuxHelper - A collection of utilities for non-technical Linux users accessible via a GUI

Linux Helper A collection of utilities for non-technical Linux users accessible via a GUI This app is still in very early development, expect bugs and

Seth 7 Oct 03, 2022
Pulse sequence builder and compiler for q1asm

q1pulse Pulse sequence builder and compiler for q1asm. q1pulse is a simple library to compile pulse sequence to q1asm, the assembly language of Qblox

Sander de Snoo 3 Dec 14, 2022
Emulate and Dissect MSF and *other* attacks

Need help in analyzing Windows shellcode or attack coming from Metasploit Framework or Cobalt Strike (or may be also other malicious or obfuscated code)? Do you need to automate tasks with simple scr

123 Dec 16, 2022
A python package that adds "docs" command to disnake

About This extension's purpose is of adding a "docs" command, its purpose is to help documenting in chat. How To Load It from disnake.ext import comma

7 Jan 03, 2023
A pure-Python codified rant aspiring to a world where numbers and types can work together.

Copyright and other protections apply. Please see the accompanying LICENSE file for rights and restrictions governing use of this software. All rights

Matt Bogosian 28 Sep 04, 2022
A project to explore and provide useful code for Mango Markets

🥭 Mango Explorer A project to explore and provide useful code for Mango Markets

Blockworks Foundation 160 Dec 19, 2022
Resizing using nnedi3/znedi3/nnedi3cl with center alignment and correct chroma placement

nnedi3_resample A VapourSynth script for easy resizing using nnedi3/znedi3/nnedi3cl with center alignment and correct chroma placement. Requirements n

Home Of VapourSynth Evolution 12 Sep 08, 2022
Python 3 script for installing kali tools on your linux machine

Python 3 script for installing kali tools on your linux machine

gh0st 2 Apr 20, 2022
The calculator on Python.

Calculator Contributors: Delitanast An official website. Information Hello! I am Damir. It`s my first Python project. I think you want see this. I imp

3 Mar 13, 2022
Python library for the Unmand APIs.

Unmand Python SDK This is a simple package to aid in consuming the Unmand APIs. For more help, see our docs. Getting Started Create virtual environmen

Unmand 4 Jul 22, 2022
Utility/Raiding selfbot made by Shell and Roover.

Utility/Raiding selfbot made by Shell and Roover. We are open to suggestions and ideas.

Shell 2 Dec 08, 2021
Shell scripts made simple 🐚

zxpy Shell scripts made simple 🐚 Inspired by Google's zx, but made much simpler and more accessible using Python. Rationale Bash is cool, and it's ex

Tushar Sadhwani 492 Dec 27, 2022
A middle-to-high level algorithm book designed with coding interview at heart!

Hands-on Algorithmic Problem Solving A one-stop coding interview prep book! About this book In short, this is a middle-to-high level algorithm book de

Li Yin 1.8k Jan 02, 2023
HPomb Is Socail Engineering Tool , Used For Bombing , Spoofing and Anonymity Available For Linux And Android(Termux)

HPomb v2020.02 Coming Soon Created By Secanonm HPomb Is Socail Engineering Tool , Used For Bombing , Spoofing and Anonymity Available For Linux And An

Secanonm 10 Jul 25, 2022
msgqywx 使用企业微信的应用消息推送实时信息

msgqywx 使用企业微信的应用消息推送实时信息

Demon Finch 8 Dec 18, 2022
A plugin for managing mod installers in Mod Organizer 2

Reinstaller v1.0.* Introduction Reinstaller allows you to conveninetly backup mod installers to re-run later, without risk of them cluttering up your

Alex Ashmore 2 Jun 27, 2022
Collection of functions for working with interlaced content in VapourSynth.

vsfieldkit Collection of functions for working with interlaced content in VapourSynth. It does not have any hard dependencies outside of VapourSynth.

Justin Turner Arthur 11 May 27, 2022
A program to generate random numbers b/w 0 to 10 using time

random-num-using-time A program to generate random numbers b/w 0 to 10 using time it uses python's in-built module datetime and an equation which retu

Atul Kushwaha 1 Oct 01, 2022