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)
A timer for bird lovers, plays a random birdcall while displaying its image and info.

Birdcall Timer A timer for bird lovers. Siriema hatchling by Junior Peres Junior Background My partner needed a customizable timer for sitting and sta

Marcelo Sanches 1 Jul 08, 2022
An Airflow operator to call the main function from the dbt-core Python package

airflow-dbt-python An Airflow operator to call the main function from the dbt-core Python package Motivation Airflow running in a managed environment

Tomás Farías Santana 93 Jan 08, 2023
Enjoyable scripting experience with Python

Enjoyable scripting experience with Python

8 Jun 08, 2022
A tool for light-duty persistent memoization of API calls

JSON Memoize What is this? json_memoize is a straightforward tool for light-duty persistent memoization, created with API calls in mind. It stores the

1 Dec 11, 2021
Code for Crowd counting via unsupervised cross-domain feature adaptation.

CDFA-pytorch Code for Unsupervised crowd counting via cross-domain feature adaptation. Pre-trained models Google Drive Baidu Cloud : t4qc Environment

Guanchen Ding 6 Dec 11, 2022
Tools to convert SQLAlchemy models to Pydantic models

Pydantic-SQLAlchemy Tools to generate Pydantic models from SQLAlchemy models. Still experimental. How to use Quick example: from typing import List f

Sebastián Ramírez 893 Dec 29, 2022
A little tool that uses LLVM to extract simple "what does this do" level instruction information from all architectures.

moirai: MOre InstRuctions and Information Backcronym. Anyway, this is a small project to extract useful instruction definitions from LLVM's platform d

2 Jul 30, 2022
A simple, light-weight and highly maintainable online judge system for secondary education

y³OJ a simple, light-weight and highly maintainable online judge system for secondary education 一个简单、轻量化、易于维护的、为中学信息技术学科课业教学设计的 Online Judge 系统。 Onlin

20 Oct 04, 2022
Write Streamlit apps using Notion! (Prototype)

Streamlit + Notion test app Write Streamlit apps using Notion! ☠️ IMPORTANT: This is just a little prototype I made to play with some ideas. Not meant

Thiago Teixeira 22 Sep 08, 2022
Virtual Assistant Using Python

-Virtual-Assistant-Using-Python Virtual desktop assistant is an awesome thing. If you want your machine to run on your command like Jarvis did for Ton

Bade om 1 Nov 13, 2021
Python script for converting obsidian md-file to html (recursively adds all link/images)

ObsidianToHtmlConverter I made a small python script for converting obsidian md-file to static (local) html (recursively adds all link/images) I made

47 Jan 03, 2023
Margin Calculator - Personally tailored investment tool

Margin Calculator - Personally tailored investment tool

1 Jul 19, 2022
Attempt at a Windows version of the plotman Chia Plot Manager system

windows plotman: an attempt to get plotman to work on windows THIS IS A BETA. Not ready for production use just yet. Almost, but not quite there yet.

59 May 11, 2022
Reconhecimento de voz, em português, com python

Speech_recognizer Reconhecimento de voz, em português, com python O ato de falar nada mais é que criar vibrações no ar. Por meio de um conversor analó

Marcus Vinícius Ribeiro Andrade 1 Dec 14, 2021
Trackthis - This library can be used to track USPS and UPS shipments.

Trackthis - This library can be used to track USPS and UPS shipments. It has the option of returning the raw API response, or optionally, it can be used to standardize the USPS and UPS responses so t

Aaron Guzman 0 Mar 29, 2022
A python program for rick rolling people.

Rickware A python program for rick rolling people. (And annoying them too) What is rick roll? Read this wikipedia article - Rickrolling About program

2 Jan 18, 2022
Collie is for uncovering RDMA NIC performance anomalies

Collie is for uncovering RDMA NIC performance anomalies. Overview Prerequ

Bytedance Inc. 34 Dec 11, 2022
A web app that is written entirely in Python

University Project About I made this web app to finish a project assigned by my teacher. It is written entirely in Python, thanks to streamlit to make

15 Nov 27, 2022
pyToledo is a Python library to interact with the common virtual learning environment for the Association KU Leuven (Toledo).

pyToledo pyToledo is a Python library to interact with the common virtual learning environment for the Association KU Leuven a.k.a Toledo. Motivation

Daan Vervacke 5 Jan 03, 2022
An alternative site to emplea.do due to inconsistent service of the app.

feline a agile and fast alternative to emplea.do License: MIT Settings Moved to settings. Basic Commands Setting Up Your Users To create a normal user

Codetiger 8 Nov 10, 2021