Resilience API Reference¶
Circuit breaker and health check patterns.
financelib.resilience.CircuitBreaker(failure_threshold: int = 5, recovery_timeout: float = 30.0, name: str = 'default')
¶
Circuit breaker for external API calls.
Tracks failures and temporarily blocks calls to failing services to prevent cascading failures and allow recovery.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
failure_threshold
|
int
|
Number of consecutive failures before opening. |
5
|
recovery_timeout
|
float
|
Seconds to wait before trying half-open. |
30.0
|
name
|
str
|
Name for logging. |
'default'
|
Example
cb = CircuitBreaker(failure_threshold=5, recovery_timeout=30) @cb ... def call_api(): ... return requests.get("https://api.example.com")
Source code in financelib/resilience.py
Attributes¶
failure_count: int
property
¶
Get the current failure count.
state: CircuitState
property
¶
Get the current circuit state.
Functions¶
__call__(func: F) -> F
¶
Use as a decorator for protected function calls.
Source code in financelib/resilience.py
record_failure() -> None
¶
Record a failed call — may trip the circuit.
Source code in financelib/resilience.py
record_success() -> None
¶
Record a successful call — resets failure count.
Source code in financelib/resilience.py
financelib.resilience.CircuitState
¶
Bases: Enum
Circuit breaker states.
financelib.resilience.CircuitOpenError
¶
Bases: Exception
Raised when a call is blocked by an open circuit breaker.
financelib.resilience.HealthCheck(name: str, check_fn: Callable[[], bool], interval: float = 0)
¶
Simple health check for external services.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Service name. |
required |
check_fn
|
Callable[[], bool]
|
Callable that returns True if service is healthy. |
required |
interval
|
float
|
Seconds between automatic checks (0 = manual only). |
0
|
Example
def check_binance(): ... return requests.get("https://api.binance.com/api/v3/ping").ok health = HealthCheck("binance", check_binance) print(health.is_healthy())
Source code in financelib/resilience.py
Attributes¶
status: Dict
property
¶
Get health status as a dictionary.
Functions¶
is_healthy() -> bool
¶
Check if the service is healthy.
Returns cached result if within the check interval.