Circuit Breaker

Threadsafe pure-Python implementation of the Circuit Breaker pattern, described by Michael T. Nygard in his book ‘Release It!’.

For more information on this and other patterns and best practices, buy the book at https://pragprog.com/titles/mnee2/release-it-second-edition/

CircuitBreaker

class aiobreaker.circuitbreaker.CircuitBreaker(fail_max=5, timeout_duration=None, exclude=None, listeners=None, state_storage=None, name=None)[source]

Bases: object

A circuit breaker is a route through which functions are executed. When a function is executed via a circuit breaker, the breaker is notified. Multiple failed attempts will open the breaker and block additional calls.

__init__(fail_max=5, timeout_duration=None, exclude=None, listeners=None, state_storage=None, name=None)[source]

Creates a new circuit breaker with the given parameters.

Parameters
property fail_counter

Returns the current number of consecutive failures.

property fail_max

Returns the maximum number of failures tolerated before the circuit is opened.

property timeout_duration

Once this circuit breaker is opened, it should remain opened until the timeout period elapses.

property opens_at: Optional[datetime.datetime]

Gets the remaining timeout for a breaker.

Return type

Optional[datetime]

property time_until_open: Optional[datetime.timedelta]

Returns a timedelta representing the difference between the current time and when the breaker closes again, or None if it has elapsed.

Return type

Optional[timedelta]

async sleep_until_open()[source]
property state

Update (if needed) and returns the cached state object.

property current_state: aiobreaker.state.CircuitBreakerState

Returns a CircuitBreakerState that identifies the state of the circuit breaker.

Return type

CircuitBreakerState

property excluded_exceptions: tuple

Returns a tuple of the excluded exceptions, e.g., exceptions that should not be considered system errors by this circuit breaker.

Return type

tuple

add_excluded_exception(exception)[source]

Adds an exception to the list of excluded exceptions.

add_excluded_exceptions(*exceptions)[source]

Adds exceptions to the list of excluded exceptions.

Parameters

exceptions – Any Exception types you wish to ignore.

remove_excluded_exception(exception)[source]

Removes an exception from the list of excluded exceptions.

is_system_error(exception)[source]

Returns whether the exception exception is considered a signal of system malfunction. Business exceptions should not cause this circuit breaker to open.

call(func, *args, **kwargs)[source]

Calls func with the given args and kwargs according to the rules implemented by the current state of this circuit breaker.

async call_async(func, *args, **kwargs)[source]

Calls func with the given args and kwargs according to the rules implemented by the current state of this circuit breaker.

open()[source]

Opens the circuit, e.g., the following calls will immediately fail until timeout elapses.

half_open()[source]

Half-opens the circuit, e.g. lets the following call pass through and opens the circuit if the call fails (or closes the circuit if the call succeeds).

close()[source]

Closes the circuit, e.g. lets the following calls execute as usual.

__call__(*call_args, ignore_on_call=True)[source]

Decorates the function such that calls are handled according to the rules implemented by the current state of this circuit breaker.

Parameters

ignore_on_call – Whether the decorated function should be ignored when using call(), preventing the breaker being triggered twice.

property listeners

Returns the registered listeners as a tuple.

add_listener(listener)[source]

Registers a listener for this circuit breaker.

add_listeners(*listeners)[source]

Registers listeners for this circuit breaker.

remove_listener(listener)[source]

Unregisters a listener of this circuit breaker.

property name: str

Returns the name of this circuit breaker. Useful for logging.

Return type

str

Listener

class aiobreaker.listener.CircuitBreakerListener[source]

Bases: object

Listener class used to plug code to a CircuitBreaker instance when certain events happen.

todo async listener handlers

before_call(breaker, func, *args, **kwargs)[source]

Called before a function is executed over a breaker.

Parameters
  • breaker (CircuitBreaker) – The breaker that is used.

  • func (Callable) – The function that is called.

  • args – The args to the function.

  • kwargs – The kwargs to the function.

Return type

None

failure(breaker, exception)[source]

Called when a function executed over the circuit breaker ‘breaker’ fails.

Return type

None

success(breaker)[source]

Called when a function executed over the circuit breaker ‘breaker’ succeeds.

Return type

None

state_change(breaker, old, new)[source]

Called when the state of the circuit breaker ‘breaker’ changes.

Return type

None

State

exception aiobreaker.state.CircuitBreakerError(message, reopen_time)[source]

Bases: Exception

Raised when the function fails due to the breaker being open.

__init__(message, reopen_time)[source]
Parameters
  • message (str) – The reasoning.

  • reopen_time (datetime) – When the breaker re-opens.

property time_remaining: datetime.timedelta
Return type

timedelta

async sleep_until_open()[source]
class aiobreaker.state.CircuitBreakerBaseState(breaker, state)[source]

Bases: abc.ABC

Implements the behavior needed by all circuit breaker states.

__init__(breaker, state)[source]

Creates a new instance associated with the circuit breaker cb and identified by name.

property state: aiobreaker.state.CircuitBreakerState

Returns a human friendly name that identifies this state.

Return type

CircuitBreakerState

call(func, *args, **kwargs)[source]

Calls func with the given args and kwargs, and updates the circuit breaker state according to the result.

Return type

~T

async call_async(func, *args, **kwargs)[source]
Return type

Awaitable[~T]

generator_call(wrapped_generator)[source]
before_call(func, *args, **kwargs)[source]

Override this method to be notified before a call to the guarded operation is attempted.

on_success()[source]

Override this method to be notified when a call to the guarded operation succeeds.

on_failure(exception)[source]

Override this method to be notified when a call to the guarded operation fails.

class aiobreaker.state.CircuitClosedState(breaker, prev_state=None, notify=False)[source]

Bases: aiobreaker.state.CircuitBreakerBaseState

In the normal “closed” state, the circuit breaker executes operations as usual. If the call succeeds, nothing happens. If it fails, however, the circuit breaker makes a note of the failure.

Once the number of failures exceeds a threshold, the circuit breaker trips and “opens” the circuit.

__init__(breaker, prev_state=None, notify=False)[source]

Moves the given circuit breaker to the “closed” state.

on_failure(exception)[source]

Moves the circuit breaker to the “open” state once the failures threshold is reached.

class aiobreaker.state.CircuitOpenState(breaker, prev_state=None, notify=False)[source]

Bases: aiobreaker.state.CircuitBreakerBaseState

When the circuit is “open”, calls to the circuit breaker fail immediately, without any attempt to execute the real operation. This is indicated by the CircuitBreakerError exception.

After a suitable amount of time, the circuit breaker decides that the operation has a chance of succeeding, so it goes into the “half-open” state.

__init__(breaker, prev_state=None, notify=False)[source]

Moves the given circuit breaker to the “open” state.

before_call(func, *args, **kwargs)[source]

After the timeout elapses, move the circuit breaker to the “half-open” state. :raises CircuitBreakerError: if the timeout has still to be elapsed.

call(func, *args, **kwargs)[source]

Call before_call to check if the breaker should close and open it if it passes.

async call_async(func, *args, **kwargs)[source]

Call before_call to check if the breaker should close and open it if it passes.

class aiobreaker.state.CircuitHalfOpenState(breaker, prev_state=None, notify=False)[source]

Bases: aiobreaker.state.CircuitBreakerBaseState

In the “half-open” state, the next call to the circuit breaker is allowed to execute the dangerous operation. Should the call succeed, the circuit breaker resets and returns to the “closed” state. If this trial call fails, however, the circuit breaker returns to the “open” state until another timeout elapses.

__init__(breaker, prev_state=None, notify=False)[source]

Moves the given circuit breaker to the “half-open” state.

on_failure(exception)[source]

Opens the circuit breaker.

on_success()[source]

Closes the circuit breaker.

class aiobreaker.state.CircuitBreakerState(value)[source]

Bases: enum.Enum

An enumeration.

OPEN = <class 'aiobreaker.state.CircuitOpenState'>
CLOSED(breaker, prev_state=None, notify=False) = <class 'aiobreaker.state.CircuitClosedState'>
HALF_OPEN = <class 'aiobreaker.state.CircuitHalfOpenState'>

Version

aiobreaker.version.short_version = '1.1'

A short version.