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)
📜Generate poetry with gcc diagnostics

gado (gcc awesome diagnostics orchestrator) is a wrapper of gcc that outputs its errors and warnings in a more poetic format.

Dikson Santos 19 Jun 25, 2022
Rates how pog a word or user is. Not random and does have *some* kind of algorithm to it.

PogRater :D Rates how pogchamp a word is :D A fun project coded by JBYT27 using Python3 Have you ever wondered how pog a word is? Well, congrats, you

an aspirin 2 Jun 25, 2022
Buffer Overflows

BOF Buffer Overflows 1. BOF tips Practice using mona.py Download vulnerable exe from Exploit DB.

Vinh Nguyễn 27 Dec 08, 2022
Secret santa is a fun and easy way to get together with your friends and/or family with a gift for them.

Vaccine Validator Tool to validate domestic New Zealand vaccine passes Create a new virtual environment: python3 -m venv ./venv Activate virtual envi

2 Dec 06, 2021
NYCU(NCTU)-差勤-助教

NCTU-TA-fill 填寫 差勤-助教時數 有沒有覺得在差勤系統填助教時數有點浪費生命? 今天有個懶鬼浪費好多時間幫大家寫了code 只要填好的必要的資料,就可以讓電腦自動幫你完成差勤助教的時數填寫喔! https://pt-attendance.nctu.edu.tw/verify/userL

14 Dec 21, 2021
Random pass word generator made with python. PyQt5 module is used to design GUI.

Differences in this GUI program : Default titlebar removed Custom Minimize,Maximize and Close Buttons Drag & move window from any point Program work l

Dimuth De Zoysa 1 Jan 26, 2022
Analysis of ROM image for Norsk Data VDU 301 S

This repository is meant to analyze the ROM images from Norsk Data VDU 301 S as provided at by Torfinn. To combine the two ROM image halves and extrac

Sebastian Rasmussen 1 Oct 21, 2021
Python code to control laboratory hardware and perform Bayesian reaction optimization on the MIT Make-It system for chemical synthesis

Description This repository contains code accompanying the following paper on the Make-It robotic flow chemistry platform developed by the Jensen Rese

Anirudh Nambiar 11 Dec 10, 2022
Calculate the efficient frontier

关于 代码主要参考Fábio Neves的文章,你可以在他的文章中找到一些细节性的解释

Wyman Lin 104 Nov 11, 2022
Leveraging pythonic forces to defeat different coding challenges 🐍

Pyforces Leveraging pythonic forces to defeat different coding challenges! Table of Contents Pyforces Tests Pyforces Pyforces is a study repo with a c

Igor Grillo Peternella 8 Dec 14, 2022
- Auto join teams teams ( from calendar invite )

Auto Join Teams Meetings Requirements: Python 3.7 or higher Latest Google Chrome This script automatically logins to your account and joins the meetin

Prajin Khadka 10 Aug 20, 2022
Source code for Learn Programming: Python

This repository contains the source code of the game engine behind Learn Programming: Python. The two key files are game.py (the main source of the ga

Niema Moshiri 25 Apr 24, 2022
Companion Web site for Fluent Python, Second Edition

Fluent Python, the site Source code and content for fluentpython.com. The site complements Fluent Python, Second Edition with extra content that did n

Fluent Python 49 Dec 08, 2022
Gmvault: Backup and restore your gmail account

Gmvault: Backup and restore your gmail account Gmvault is a tool for backing up your gmail account and never lose email correspondence. Gmvault is ope

Guillaume Aubert 3.5k Jan 01, 2023
My collection of mini-projects in various languages

Mini-Projects My collection of mini-projects in various languages About: This repository consists of a number of small projects. Most of these "mini-p

Siddhant Attavar 1 Jul 11, 2022
Implent of Oracle Base line and Lea-3 Baseline

Oracle-Baseline Implent of Oracle Base line and Lea-3 Baseline Oracle Oracle : This model is used to obtain an oracle with a greedy algorithm similar

Andrew Zeng 2 Nov 12, 2021
Quanser Labs Robotic Arm With Python

Quanser-Labs-Robotic-Arm As a team, we programmed a Robotic-Arm in Python on the

1 Jul 11, 2022
Mpis-ex7 - Implementation of tasks 1, 2, 3 for Metody Probabilistyczne i Statystyka Lista 7

Implementations of task 1, 2 and 3 from here Author: Maciej Bazela Index: 261743 Each task was implemented in Python 3. I've used Cython to speed up e

Maciej Bazela 1 Feb 27, 2022
Boot.img patcher for Tolino ebook readers to enable ADB and root.

I'm not responsible for any damage to your devices by running this tool. Please note that you may loose warranty when using this, although (This is no

Aaron Dewes 9 Nov 13, 2022