Python implementation of the Circuit Breaker pattern for handling failing subsystems gracefully
npx @tessl/cli install tessl/pypi-pybreaker@1.4.00
# PyBreaker
1
2
A robust Python implementation of the Circuit Breaker design pattern, allowing applications to handle failing subsystems gracefully without cascading failures. The library offers configurable failure thresholds and reset timeouts, supports event listeners for monitoring circuit state changes, can guard both synchronous and asynchronous (Tornado) functions, and provides thread-safe operation with optional Redis backing for distributed systems.
3
4
## Package Information
5
6
- **Package Name**: pybreaker
7
- **Language**: Python
8
- **Installation**: `pip install pybreaker`
9
- **Python Version**: 3.9+
10
11
## Core Imports
12
13
```python
14
import pybreaker
15
```
16
17
Common usage pattern:
18
19
```python
20
from pybreaker import CircuitBreaker, CircuitBreakerListener
21
```
22
23
Feature availability can be checked:
24
25
```python
26
# Check if Redis support is available
27
print(pybreaker.HAS_REDIS_SUPPORT) # True if redis package installed
28
29
# Check if Tornado async support is available
30
print(pybreaker.HAS_TORNADO_SUPPORT) # True if tornado package installed
31
```
32
33
## Basic Usage
34
35
```python
36
import pybreaker
37
38
# Create a circuit breaker with default settings
39
db_breaker = pybreaker.CircuitBreaker(fail_max=5, reset_timeout=60)
40
41
# Use as decorator
42
@db_breaker
43
def database_call():
44
# Potentially failing operation
45
# Will be protected by circuit breaker
46
pass
47
48
# Use with direct call
49
def another_db_call():
50
# Some database operation
51
pass
52
53
result = db_breaker.call(another_db_call)
54
55
# Use as context manager
56
with db_breaker.calling():
57
# Protected code block
58
pass
59
```
60
61
## Architecture
62
63
PyBreaker implements the Circuit Breaker pattern with three core states:
64
65
- **Closed State**: Normal operation, calls pass through to the wrapped function
66
- **Open State**: Circuit is open, calls fail immediately with `CircuitBreakerError`
67
- **Half-Open State**: Testing state allowing one trial call to determine if circuit should close
68
69
The architecture supports:
70
- **Storage Backends**: Memory-based and Redis-based storage for circuit state
71
- **Event System**: Listener pattern for monitoring circuit events and state changes
72
- **Thread Safety**: All operations are thread-safe using internal locking
73
- **Exception Filtering**: Configurable exclusion of business exceptions from circuit logic
74
75
## Capabilities
76
77
### Core Circuit Breaker
78
79
Main circuit breaker functionality with configurable failure thresholds, reset timeouts, and state management. Supports decorator, direct call, and context manager usage patterns.
80
81
```python { .api }
82
class CircuitBreaker:
83
def __init__(self, fail_max: int = 5, reset_timeout: float = 60,
84
success_threshold: int = 1,
85
exclude: Iterable[type | Callable[[Any], bool]] | None = None,
86
listeners: Sequence[CircuitBreakerListener] | None = None,
87
state_storage: CircuitBreakerStorage | None = None,
88
name: str | None = None,
89
throw_new_error_on_trip: bool = True): ...
90
91
def call(self, func, *args, **kwargs): ...
92
def calling(self): ... # Context manager
93
def open(self) -> bool: ...
94
def close(self) -> None: ...
95
def half_open(self) -> None: ...
96
```
97
98
[Core Circuit Breaker](./circuit-breaker.md)
99
100
### Storage Backends
101
102
Storage implementations for persisting circuit breaker state across application restarts and distributed systems. Includes in-memory storage for single-process applications and Redis storage for distributed scenarios.
103
104
```python { .api }
105
class CircuitBreakerStorage:
106
def __init__(self, name: str) -> None: ...
107
# Abstract base class with state management methods
108
109
class CircuitMemoryStorage:
110
def __init__(self, state: str): ...
111
112
class CircuitRedisStorage:
113
def __init__(self, state: str, redis_object: Redis, namespace: str | None = None,
114
fallback_circuit_state: str = "closed", cluster_mode: bool = False): ...
115
```
116
117
[Storage Backends](./storage.md)
118
119
### Event Listeners
120
121
Event listener system for monitoring circuit breaker state changes, failures, and successes. Enables integration with logging, metrics, and alerting systems.
122
123
```python { .api }
124
class CircuitBreakerListener:
125
def before_call(self, cb: CircuitBreaker, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ...
126
def failure(self, cb: CircuitBreaker, exc: BaseException) -> None: ...
127
def success(self, cb: CircuitBreaker) -> None: ...
128
def state_change(self, cb: CircuitBreaker, old_state: CircuitBreakerState | None, new_state: CircuitBreakerState) -> None: ...
129
```
130
131
[Event Listeners](./listeners.md)
132
133
### Async Support
134
135
Optional Tornado integration for protecting asynchronous operations with circuit breaker functionality. Requires tornado package to be installed.
136
137
```python { .api }
138
def call_async(self, func, *args, **kwargs): ...
139
```
140
141
[Async Support](./async.md)
142
143
## State Constants
144
145
```python { .api }
146
STATE_OPEN = "open"
147
STATE_CLOSED = "closed"
148
STATE_HALF_OPEN = "half-open"
149
150
# Feature availability flags
151
HAS_REDIS_SUPPORT: bool # True if redis package is available
152
HAS_TORNADO_SUPPORT: bool # True if tornado package is available
153
```
154
155
## Exception Types
156
157
```python { .api }
158
class CircuitBreakerError(Exception):
159
"""Raised when circuit breaker is open and calls are rejected."""
160
```