syncora-resilience 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- syncora_resilience-1.0.0/LICENSE +17 -0
- syncora_resilience-1.0.0/PKG-INFO +139 -0
- syncora_resilience-1.0.0/README.md +104 -0
- syncora_resilience-1.0.0/pyproject.toml +62 -0
- syncora_resilience-1.0.0/setup.cfg +4 -0
- syncora_resilience-1.0.0/src/syncora/__init__.py +19 -0
- syncora_resilience-1.0.0/src/syncora/circuit.py +84 -0
- syncora_resilience-1.0.0/src/syncora/cli.py +60 -0
- syncora_resilience-1.0.0/src/syncora/limiter.py +44 -0
- syncora_resilience-1.0.0/src/syncora/retry.py +70 -0
- syncora_resilience-1.0.0/src/syncora_resilience.egg-info/PKG-INFO +139 -0
- syncora_resilience-1.0.0/src/syncora_resilience.egg-info/SOURCES.txt +15 -0
- syncora_resilience-1.0.0/src/syncora_resilience.egg-info/dependency_links.txt +1 -0
- syncora_resilience-1.0.0/src/syncora_resilience.egg-info/entry_points.txt +2 -0
- syncora_resilience-1.0.0/src/syncora_resilience.egg-info/requires.txt +6 -0
- syncora_resilience-1.0.0/src/syncora_resilience.egg-info/top_level.txt +1 -0
- syncora_resilience-1.0.0/tests/test_circuit.py +59 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2026 Syncora Systems Ltd.
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: syncora-resilience
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Production-grade resilience engine: distributed circuit breakers, adaptive rate limiters, and exponential jitter backoff for high-load Python microservices
|
|
5
|
+
Author-email: Syncora Systems Core Platform <engineering@syncora.io>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://syncora.io
|
|
8
|
+
Project-URL: Documentation, https://docs.syncora.io/resilience
|
|
9
|
+
Project-URL: Repository, https://github.com/syncora-systems/syncora-resilience
|
|
10
|
+
Project-URL: Tracker, https://github.com/syncora-systems/syncora-resilience/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/syncora-systems/syncora-resilience/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: resilience,circuit-breaker,rate-limiter,retry,backoff,microservices,asyncio,fault-tolerance,sre
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Information Technology
|
|
16
|
+
Classifier: Intended Audience :: System Administrators
|
|
17
|
+
Classifier: Topic :: System :: Networking
|
|
18
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Operating System :: OS Independent
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
32
|
+
Requires-Dist: build; extra == "dev"
|
|
33
|
+
Requires-Dist: twine; extra == "dev"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# Syncora Resilience Engine (`syncora-resilience`)
|
|
37
|
+
|
|
38
|
+
[](https://pypi.org/project/syncora-resilience/)
|
|
39
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
40
|
+
[](https://www.python.org/downloads/)
|
|
41
|
+
[](https://syncora.io)
|
|
42
|
+
[](https://syncora.io)
|
|
43
|
+
|
|
44
|
+
A production-grade, zero-dependency fault tolerance toolkit engineered for high-throughput Python microservices, distributed RPC pipelines, and mission-critical cloud backends.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Architectural Highlights
|
|
49
|
+
|
|
50
|
+
- **Three-State Circuit Breakers**: Protect upstream systems from cascading downtime using finite state machines (`CLOSED` -> `OPEN` -> `HALF_OPEN`).
|
|
51
|
+
- **Jittered Exponential Retries**: Mitigate thundering herd problems with full-jitter backoff for synchronous functions and asyncio coroutines.
|
|
52
|
+
- **Token Bucket Rate Limiting**: Enforce hard concurrency bounds and smooth bursty traffic spikes.
|
|
53
|
+
- **Zero Third-Party Dependencies**: Pure standard library implementation with nanosecond-scale overhead.
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install syncora-resilience
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
### 1. Circuit Breaker Protection
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from syncora import CircuitBreaker, CircuitBreakerOpenError
|
|
71
|
+
|
|
72
|
+
breaker = CircuitBreaker(
|
|
73
|
+
name="payment-gateway",
|
|
74
|
+
failure_threshold=5,
|
|
75
|
+
recovery_timeout=30.0
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@breaker
|
|
79
|
+
def charge_customer(account_id: str, amount_cents: int):
|
|
80
|
+
# Remote HTTP call to payment processor
|
|
81
|
+
return remote_payment_api.charge(account_id, amount_cents)
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
charge_customer("acc_94821", 5000)
|
|
85
|
+
except CircuitBreakerOpenError:
|
|
86
|
+
# Circuit is open - immediate fallback, avoiding socket exhaustion
|
|
87
|
+
enqueue_offline_retry("acc_94821", 5000)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Async Exponential Retries with Full Jitter
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import httpx
|
|
94
|
+
from syncora import retry, BackoffPolicy
|
|
95
|
+
|
|
96
|
+
@retry(
|
|
97
|
+
max_attempts=4,
|
|
98
|
+
initial_delay=0.1,
|
|
99
|
+
max_delay=5.0,
|
|
100
|
+
backoff=BackoffPolicy.EXPONENTIAL,
|
|
101
|
+
jitter=True,
|
|
102
|
+
exceptions=(httpx.ConnectTimeout, httpx.ReadTimeout)
|
|
103
|
+
)
|
|
104
|
+
async def fetch_user_profile(user_id: str):
|
|
105
|
+
async with httpx.AsyncClient() as client:
|
|
106
|
+
resp = await client.get(f"https://users.internal.net/{user_id}", timeout=2.0)
|
|
107
|
+
resp.raise_for_status()
|
|
108
|
+
return resp.json()
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### 3. High-Throughput Token Bucket Limiter
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from syncora import TokenBucketRateLimiter
|
|
115
|
+
|
|
116
|
+
limiter = TokenBucketRateLimiter(rate=200.0, capacity=50.0)
|
|
117
|
+
|
|
118
|
+
def handle_incoming_webhook(event):
|
|
119
|
+
if not limiter.acquire(1):
|
|
120
|
+
return {"status": 429, "error": "Too Many Requests"}
|
|
121
|
+
return process_event(event)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Benchmark Suite
|
|
127
|
+
|
|
128
|
+
Run the built-in latency benchmark:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
syncora bench
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## License
|
|
137
|
+
|
|
138
|
+
Syncora Resilience Engine is distributed under the **Apache License 2.0**.
|
|
139
|
+
Copyright 2026 Syncora Systems Ltd.
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Syncora Resilience Engine (`syncora-resilience`)
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/syncora-resilience/)
|
|
4
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
5
|
+
[](https://www.python.org/downloads/)
|
|
6
|
+
[](https://syncora.io)
|
|
7
|
+
[](https://syncora.io)
|
|
8
|
+
|
|
9
|
+
A production-grade, zero-dependency fault tolerance toolkit engineered for high-throughput Python microservices, distributed RPC pipelines, and mission-critical cloud backends.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Architectural Highlights
|
|
14
|
+
|
|
15
|
+
- **Three-State Circuit Breakers**: Protect upstream systems from cascading downtime using finite state machines (`CLOSED` -> `OPEN` -> `HALF_OPEN`).
|
|
16
|
+
- **Jittered Exponential Retries**: Mitigate thundering herd problems with full-jitter backoff for synchronous functions and asyncio coroutines.
|
|
17
|
+
- **Token Bucket Rate Limiting**: Enforce hard concurrency bounds and smooth bursty traffic spikes.
|
|
18
|
+
- **Zero Third-Party Dependencies**: Pure standard library implementation with nanosecond-scale overhead.
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install syncora-resilience
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
### 1. Circuit Breaker Protection
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from syncora import CircuitBreaker, CircuitBreakerOpenError
|
|
36
|
+
|
|
37
|
+
breaker = CircuitBreaker(
|
|
38
|
+
name="payment-gateway",
|
|
39
|
+
failure_threshold=5,
|
|
40
|
+
recovery_timeout=30.0
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
@breaker
|
|
44
|
+
def charge_customer(account_id: str, amount_cents: int):
|
|
45
|
+
# Remote HTTP call to payment processor
|
|
46
|
+
return remote_payment_api.charge(account_id, amount_cents)
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
charge_customer("acc_94821", 5000)
|
|
50
|
+
except CircuitBreakerOpenError:
|
|
51
|
+
# Circuit is open - immediate fallback, avoiding socket exhaustion
|
|
52
|
+
enqueue_offline_retry("acc_94821", 5000)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### 2. Async Exponential Retries with Full Jitter
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import httpx
|
|
59
|
+
from syncora import retry, BackoffPolicy
|
|
60
|
+
|
|
61
|
+
@retry(
|
|
62
|
+
max_attempts=4,
|
|
63
|
+
initial_delay=0.1,
|
|
64
|
+
max_delay=5.0,
|
|
65
|
+
backoff=BackoffPolicy.EXPONENTIAL,
|
|
66
|
+
jitter=True,
|
|
67
|
+
exceptions=(httpx.ConnectTimeout, httpx.ReadTimeout)
|
|
68
|
+
)
|
|
69
|
+
async def fetch_user_profile(user_id: str):
|
|
70
|
+
async with httpx.AsyncClient() as client:
|
|
71
|
+
resp = await client.get(f"https://users.internal.net/{user_id}", timeout=2.0)
|
|
72
|
+
resp.raise_for_status()
|
|
73
|
+
return resp.json()
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 3. High-Throughput Token Bucket Limiter
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from syncora import TokenBucketRateLimiter
|
|
80
|
+
|
|
81
|
+
limiter = TokenBucketRateLimiter(rate=200.0, capacity=50.0)
|
|
82
|
+
|
|
83
|
+
def handle_incoming_webhook(event):
|
|
84
|
+
if not limiter.acquire(1):
|
|
85
|
+
return {"status": 429, "error": "Too Many Requests"}
|
|
86
|
+
return process_event(event)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Benchmark Suite
|
|
92
|
+
|
|
93
|
+
Run the built-in latency benchmark:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
syncora bench
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
Syncora Resilience Engine is distributed under the **Apache License 2.0**.
|
|
104
|
+
Copyright 2026 Syncora Systems Ltd.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "syncora-resilience"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Production-grade resilience engine: distributed circuit breakers, adaptive rate limiters, and exponential jitter backoff for high-load Python microservices"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Syncora Systems Core Platform", email = "engineering@syncora.io"}
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"resilience",
|
|
17
|
+
"circuit-breaker",
|
|
18
|
+
"rate-limiter",
|
|
19
|
+
"retry",
|
|
20
|
+
"backoff",
|
|
21
|
+
"microservices",
|
|
22
|
+
"asyncio",
|
|
23
|
+
"fault-tolerance",
|
|
24
|
+
"sre"
|
|
25
|
+
]
|
|
26
|
+
classifiers = [
|
|
27
|
+
"Development Status :: 5 - Production/Stable",
|
|
28
|
+
"Intended Audience :: Developers",
|
|
29
|
+
"Intended Audience :: Information Technology",
|
|
30
|
+
"Intended Audience :: System Administrators",
|
|
31
|
+
"Topic :: System :: Networking",
|
|
32
|
+
"Topic :: System :: Distributed Computing",
|
|
33
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
34
|
+
"Programming Language :: Python :: 3",
|
|
35
|
+
"Programming Language :: Python :: 3.9",
|
|
36
|
+
"Programming Language :: Python :: 3.10",
|
|
37
|
+
"Programming Language :: Python :: 3.11",
|
|
38
|
+
"Programming Language :: Python :: 3.12",
|
|
39
|
+
"Operating System :: OS Independent",
|
|
40
|
+
]
|
|
41
|
+
dependencies = []
|
|
42
|
+
|
|
43
|
+
[project.optional-dependencies]
|
|
44
|
+
dev = [
|
|
45
|
+
"pytest>=7.0.0",
|
|
46
|
+
"pytest-asyncio>=0.21.0",
|
|
47
|
+
"build",
|
|
48
|
+
"twine",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
[project.urls]
|
|
52
|
+
Homepage = "https://syncora.io"
|
|
53
|
+
Documentation = "https://docs.syncora.io/resilience"
|
|
54
|
+
Repository = "https://github.com/syncora-systems/syncora-resilience"
|
|
55
|
+
Tracker = "https://github.com/syncora-systems/syncora-resilience/issues"
|
|
56
|
+
Changelog = "https://github.com/syncora-systems/syncora-resilience/blob/main/CHANGELOG.md"
|
|
57
|
+
|
|
58
|
+
[project.scripts]
|
|
59
|
+
syncora = "syncora.cli:main"
|
|
60
|
+
|
|
61
|
+
[tool.setuptools.packages.find]
|
|
62
|
+
where = ["src"]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Syncora Resilience Engine: Production-grade fault-tolerance primitives for Python services.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from .circuit import CircuitBreaker, CircuitBreakerOpenError, State
|
|
6
|
+
from .retry import retry, BackoffPolicy
|
|
7
|
+
from .limiter import TokenBucketRateLimiter, RateLimitExceededError
|
|
8
|
+
|
|
9
|
+
__version__ = "1.0.0"
|
|
10
|
+
__author__ = "Syncora Systems Core Platform"
|
|
11
|
+
__all__ = [
|
|
12
|
+
"CircuitBreaker",
|
|
13
|
+
"CircuitBreakerOpenError",
|
|
14
|
+
"State",
|
|
15
|
+
"retry",
|
|
16
|
+
"BackoffPolicy",
|
|
17
|
+
"TokenBucketRateLimiter",
|
|
18
|
+
"RateLimitExceededError",
|
|
19
|
+
]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import enum
|
|
3
|
+
import threading
|
|
4
|
+
import functools
|
|
5
|
+
from typing import Callable, Any, Optional
|
|
6
|
+
|
|
7
|
+
class State(str, enum.Enum):
|
|
8
|
+
CLOSED = "CLOSED"
|
|
9
|
+
OPEN = "OPEN"
|
|
10
|
+
HALF_OPEN = "HALF_OPEN"
|
|
11
|
+
|
|
12
|
+
class CircuitBreakerOpenError(Exception):
|
|
13
|
+
"""Raised when call is blocked due to open circuit state."""
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
class CircuitBreaker:
|
|
17
|
+
"""
|
|
18
|
+
Thread-safe and async-compatible circuit breaker.
|
|
19
|
+
Protects downstream services from cascading failures.
|
|
20
|
+
"""
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
name: str = "default",
|
|
24
|
+
failure_threshold: int = 5,
|
|
25
|
+
recovery_timeout: float = 30.0,
|
|
26
|
+
expected_exception: type = Exception
|
|
27
|
+
):
|
|
28
|
+
self.name = name
|
|
29
|
+
self.failure_threshold = failure_threshold
|
|
30
|
+
self.recovery_timeout = recovery_timeout
|
|
31
|
+
self.expected_exception = expected_exception
|
|
32
|
+
|
|
33
|
+
self._state = State.CLOSED
|
|
34
|
+
self._failure_count = 0
|
|
35
|
+
self._last_failure_time = 0.0
|
|
36
|
+
self._lock = threading.Lock()
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def state(self) -> State:
|
|
40
|
+
with self._lock:
|
|
41
|
+
if self._state == State.OPEN:
|
|
42
|
+
if time.time() - self._last_failure_time >= self.recovery_timeout:
|
|
43
|
+
self._state = State.HALF_OPEN
|
|
44
|
+
return self._state
|
|
45
|
+
|
|
46
|
+
def call(self, func: Callable, *args, **kwargs) -> Any:
|
|
47
|
+
current_state = self.state
|
|
48
|
+
if current_state == State.OPEN:
|
|
49
|
+
raise CircuitBreakerOpenError(
|
|
50
|
+
f"Circuit '{self.name}' is OPEN. Fast-failing request."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
result = func(*args, **kwargs)
|
|
55
|
+
self._on_success()
|
|
56
|
+
return result
|
|
57
|
+
except self.expected_exception as exc:
|
|
58
|
+
self._on_failure()
|
|
59
|
+
raise exc
|
|
60
|
+
|
|
61
|
+
def _on_success(self):
|
|
62
|
+
with self._lock:
|
|
63
|
+
if self._state == State.HALF_OPEN:
|
|
64
|
+
self._state = State.CLOSED
|
|
65
|
+
self._failure_count = 0
|
|
66
|
+
|
|
67
|
+
def _on_failure(self):
|
|
68
|
+
with self._lock:
|
|
69
|
+
self._failure_count += 1
|
|
70
|
+
self._last_failure_time = time.time()
|
|
71
|
+
if self._state == State.HALF_OPEN or self._failure_count >= self.failure_threshold:
|
|
72
|
+
self._state = State.OPEN
|
|
73
|
+
|
|
74
|
+
def reset(self):
|
|
75
|
+
with self._lock:
|
|
76
|
+
self._state = State.CLOSED
|
|
77
|
+
self._failure_count = 0
|
|
78
|
+
self._last_failure_time = 0.0
|
|
79
|
+
|
|
80
|
+
def __call__(self, func: Callable) -> Callable:
|
|
81
|
+
@functools.wraps(func)
|
|
82
|
+
def wrapper(*args, **kwargs):
|
|
83
|
+
return self.call(func, *args, **kwargs)
|
|
84
|
+
return wrapper
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
import time
|
|
4
|
+
from syncora import __version__, CircuitBreaker, CircuitBreakerOpenError, TokenBucketRateLimiter
|
|
5
|
+
|
|
6
|
+
def run_benchmark():
|
|
7
|
+
print("=" * 60)
|
|
8
|
+
print(f"Syncora Resilience Engine Benchmark (v{__version__})")
|
|
9
|
+
print("Simulating 1,000 downstream requests with fault injection...")
|
|
10
|
+
print("=" * 60)
|
|
11
|
+
|
|
12
|
+
cb = CircuitBreaker("bench-cb", failure_threshold=10, recovery_timeout=0.5)
|
|
13
|
+
limiter = TokenBucketRateLimiter(rate=500, capacity=100)
|
|
14
|
+
|
|
15
|
+
start = time.perf_counter()
|
|
16
|
+
blocked_count = 0
|
|
17
|
+
passed_count = 0
|
|
18
|
+
|
|
19
|
+
for i in range(1000):
|
|
20
|
+
try:
|
|
21
|
+
limiter.acquire(1)
|
|
22
|
+
def sim_call():
|
|
23
|
+
if i % 15 == 0:
|
|
24
|
+
raise ConnectionResetError("Simulated socket drop")
|
|
25
|
+
return True
|
|
26
|
+
cb.call(sim_call)
|
|
27
|
+
passed_count += 1
|
|
28
|
+
except CircuitBreakerOpenError:
|
|
29
|
+
blocked_count += 1
|
|
30
|
+
except ConnectionResetError:
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
elapsed = time.perf_counter() - start
|
|
34
|
+
print(f"[+] Processed 1,000 requests in {elapsed * 1000:.2f} ms")
|
|
35
|
+
print(f"[+] Circuit Breaker tripped fast-fails: {blocked_count}")
|
|
36
|
+
print(f"[+] Healthy requests serviced: {passed_count}")
|
|
37
|
+
print("[+] All resilience primitives operational.")
|
|
38
|
+
|
|
39
|
+
def main():
|
|
40
|
+
parser = argparse.ArgumentParser(
|
|
41
|
+
prog="syncora",
|
|
42
|
+
description="Syncora Resilience Engine: Microservice Fault-Tolerance & SRE Tooling"
|
|
43
|
+
)
|
|
44
|
+
parser.add_argument("--version", "-v", action="version", version=f"syncora-resilience {__version__}")
|
|
45
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
46
|
+
|
|
47
|
+
subparsers.add_parser("bench", help="Execute high-load circuit breaker benchmark")
|
|
48
|
+
subparsers.add_parser("info", help="Display platform resilience specifications")
|
|
49
|
+
|
|
50
|
+
args = parser.parse_args()
|
|
51
|
+
if args.command == "bench":
|
|
52
|
+
run_benchmark()
|
|
53
|
+
else:
|
|
54
|
+
print(f"Syncora Resilience Engine v{__version__}")
|
|
55
|
+
print("Organization: Syncora Systems Ltd. (Platform Architecture)")
|
|
56
|
+
print("Documentation: https://docs.syncora.io/resilience")
|
|
57
|
+
print("Repository: https://github.com/syncora-systems/syncora-resilience")
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
main()
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import threading
|
|
3
|
+
|
|
4
|
+
class RateLimitExceededError(Exception):
|
|
5
|
+
"""Raised when request rate exceeds allowed threshold."""
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
class TokenBucketRateLimiter:
|
|
9
|
+
"""
|
|
10
|
+
Thread-safe Token Bucket rate limiter.
|
|
11
|
+
Smooths bursty traffic and enforces hard request quotas.
|
|
12
|
+
"""
|
|
13
|
+
def __init__(self, rate: float, capacity: float):
|
|
14
|
+
"""
|
|
15
|
+
:param rate: Number of tokens replenished per second.
|
|
16
|
+
:param capacity: Maximum token capacity (burst capacity).
|
|
17
|
+
"""
|
|
18
|
+
self.rate = float(rate)
|
|
19
|
+
self.capacity = float(capacity)
|
|
20
|
+
self.tokens = float(capacity)
|
|
21
|
+
self.last_update = time.time()
|
|
22
|
+
self._lock = threading.Lock()
|
|
23
|
+
|
|
24
|
+
def acquire(self, tokens: float = 1.0) -> bool:
|
|
25
|
+
"""
|
|
26
|
+
Attempt to consume tokens. Returns True if granted, False otherwise.
|
|
27
|
+
"""
|
|
28
|
+
with self._lock:
|
|
29
|
+
now = time.time()
|
|
30
|
+
elapsed = now - self.last_update
|
|
31
|
+
self.last_update = now
|
|
32
|
+
|
|
33
|
+
# Replenish
|
|
34
|
+
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
|
|
35
|
+
|
|
36
|
+
if self.tokens >= tokens:
|
|
37
|
+
self.tokens -= tokens
|
|
38
|
+
return True
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
def check(self, tokens: float = 1.0):
|
|
42
|
+
"""Consume tokens or raise RateLimitExceededError."""
|
|
43
|
+
if not self.acquire(tokens):
|
|
44
|
+
raise RateLimitExceededError("Rate limit exceeded for token bucket.")
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import random
|
|
3
|
+
import functools
|
|
4
|
+
import asyncio
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Callable, Type, Tuple, Union, Any
|
|
7
|
+
|
|
8
|
+
class BackoffPolicy(str, Enum):
|
|
9
|
+
CONSTANT = "constant"
|
|
10
|
+
LINEAR = "linear"
|
|
11
|
+
EXPONENTIAL = "exponential"
|
|
12
|
+
|
|
13
|
+
def retry(
|
|
14
|
+
max_attempts: int = 3,
|
|
15
|
+
initial_delay: float = 0.1,
|
|
16
|
+
max_delay: float = 10.0,
|
|
17
|
+
backoff: Union[BackoffPolicy, str] = BackoffPolicy.EXPONENTIAL,
|
|
18
|
+
jitter: bool = True,
|
|
19
|
+
exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = Exception
|
|
20
|
+
):
|
|
21
|
+
"""
|
|
22
|
+
Decorator for retrying failed function invocations with configurable backoff policies.
|
|
23
|
+
Supports both synchronous functions and asyncio coroutines.
|
|
24
|
+
"""
|
|
25
|
+
policy = BackoffPolicy(backoff)
|
|
26
|
+
|
|
27
|
+
def calculate_delay(attempt: int) -> float:
|
|
28
|
+
if policy == BackoffPolicy.CONSTANT:
|
|
29
|
+
delay = initial_delay
|
|
30
|
+
elif policy == BackoffPolicy.LINEAR:
|
|
31
|
+
delay = initial_delay * attempt
|
|
32
|
+
else: # EXPONENTIAL
|
|
33
|
+
delay = initial_delay * (2 ** (attempt - 1))
|
|
34
|
+
|
|
35
|
+
delay = min(delay, max_delay)
|
|
36
|
+
if jitter:
|
|
37
|
+
delay = random.uniform(0, delay)
|
|
38
|
+
return delay
|
|
39
|
+
|
|
40
|
+
def decorator(func: Callable) -> Callable:
|
|
41
|
+
if asyncio.iscoroutinefunction(func):
|
|
42
|
+
@functools.wraps(func)
|
|
43
|
+
async def async_wrapper(*args, **kwargs) -> Any:
|
|
44
|
+
last_exc = None
|
|
45
|
+
for attempt in range(1, max_attempts + 1):
|
|
46
|
+
try:
|
|
47
|
+
return await func(*args, **kwargs)
|
|
48
|
+
except exceptions as exc:
|
|
49
|
+
last_exc = exc
|
|
50
|
+
if attempt >= max_attempts:
|
|
51
|
+
raise exc
|
|
52
|
+
await asyncio.sleep(calculate_delay(attempt))
|
|
53
|
+
raise last_exc
|
|
54
|
+
return async_wrapper
|
|
55
|
+
else:
|
|
56
|
+
@functools.wraps(func)
|
|
57
|
+
def sync_wrapper(*args, **kwargs) -> Any:
|
|
58
|
+
last_exc = None
|
|
59
|
+
for attempt in range(1, max_attempts + 1):
|
|
60
|
+
try:
|
|
61
|
+
return func(*args, **kwargs)
|
|
62
|
+
except exceptions as exc:
|
|
63
|
+
last_exc = exc
|
|
64
|
+
if attempt >= max_attempts:
|
|
65
|
+
raise exc
|
|
66
|
+
time.sleep(calculate_delay(attempt))
|
|
67
|
+
raise last_exc
|
|
68
|
+
return sync_wrapper
|
|
69
|
+
|
|
70
|
+
return decorator
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: syncora-resilience
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Production-grade resilience engine: distributed circuit breakers, adaptive rate limiters, and exponential jitter backoff for high-load Python microservices
|
|
5
|
+
Author-email: Syncora Systems Core Platform <engineering@syncora.io>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://syncora.io
|
|
8
|
+
Project-URL: Documentation, https://docs.syncora.io/resilience
|
|
9
|
+
Project-URL: Repository, https://github.com/syncora-systems/syncora-resilience
|
|
10
|
+
Project-URL: Tracker, https://github.com/syncora-systems/syncora-resilience/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/syncora-systems/syncora-resilience/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: resilience,circuit-breaker,rate-limiter,retry,backoff,microservices,asyncio,fault-tolerance,sre
|
|
13
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Information Technology
|
|
16
|
+
Classifier: Intended Audience :: System Administrators
|
|
17
|
+
Classifier: Topic :: System :: Networking
|
|
18
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Operating System :: OS Independent
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
|
|
32
|
+
Requires-Dist: build; extra == "dev"
|
|
33
|
+
Requires-Dist: twine; extra == "dev"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# Syncora Resilience Engine (`syncora-resilience`)
|
|
37
|
+
|
|
38
|
+
[](https://pypi.org/project/syncora-resilience/)
|
|
39
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
40
|
+
[](https://www.python.org/downloads/)
|
|
41
|
+
[](https://syncora.io)
|
|
42
|
+
[](https://syncora.io)
|
|
43
|
+
|
|
44
|
+
A production-grade, zero-dependency fault tolerance toolkit engineered for high-throughput Python microservices, distributed RPC pipelines, and mission-critical cloud backends.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Architectural Highlights
|
|
49
|
+
|
|
50
|
+
- **Three-State Circuit Breakers**: Protect upstream systems from cascading downtime using finite state machines (`CLOSED` -> `OPEN` -> `HALF_OPEN`).
|
|
51
|
+
- **Jittered Exponential Retries**: Mitigate thundering herd problems with full-jitter backoff for synchronous functions and asyncio coroutines.
|
|
52
|
+
- **Token Bucket Rate Limiting**: Enforce hard concurrency bounds and smooth bursty traffic spikes.
|
|
53
|
+
- **Zero Third-Party Dependencies**: Pure standard library implementation with nanosecond-scale overhead.
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install syncora-resilience
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
### 1. Circuit Breaker Protection
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from syncora import CircuitBreaker, CircuitBreakerOpenError
|
|
71
|
+
|
|
72
|
+
breaker = CircuitBreaker(
|
|
73
|
+
name="payment-gateway",
|
|
74
|
+
failure_threshold=5,
|
|
75
|
+
recovery_timeout=30.0
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@breaker
|
|
79
|
+
def charge_customer(account_id: str, amount_cents: int):
|
|
80
|
+
# Remote HTTP call to payment processor
|
|
81
|
+
return remote_payment_api.charge(account_id, amount_cents)
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
charge_customer("acc_94821", 5000)
|
|
85
|
+
except CircuitBreakerOpenError:
|
|
86
|
+
# Circuit is open - immediate fallback, avoiding socket exhaustion
|
|
87
|
+
enqueue_offline_retry("acc_94821", 5000)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### 2. Async Exponential Retries with Full Jitter
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import httpx
|
|
94
|
+
from syncora import retry, BackoffPolicy
|
|
95
|
+
|
|
96
|
+
@retry(
|
|
97
|
+
max_attempts=4,
|
|
98
|
+
initial_delay=0.1,
|
|
99
|
+
max_delay=5.0,
|
|
100
|
+
backoff=BackoffPolicy.EXPONENTIAL,
|
|
101
|
+
jitter=True,
|
|
102
|
+
exceptions=(httpx.ConnectTimeout, httpx.ReadTimeout)
|
|
103
|
+
)
|
|
104
|
+
async def fetch_user_profile(user_id: str):
|
|
105
|
+
async with httpx.AsyncClient() as client:
|
|
106
|
+
resp = await client.get(f"https://users.internal.net/{user_id}", timeout=2.0)
|
|
107
|
+
resp.raise_for_status()
|
|
108
|
+
return resp.json()
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### 3. High-Throughput Token Bucket Limiter
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from syncora import TokenBucketRateLimiter
|
|
115
|
+
|
|
116
|
+
limiter = TokenBucketRateLimiter(rate=200.0, capacity=50.0)
|
|
117
|
+
|
|
118
|
+
def handle_incoming_webhook(event):
|
|
119
|
+
if not limiter.acquire(1):
|
|
120
|
+
return {"status": 429, "error": "Too Many Requests"}
|
|
121
|
+
return process_event(event)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Benchmark Suite
|
|
127
|
+
|
|
128
|
+
Run the built-in latency benchmark:
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
syncora bench
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
---
|
|
135
|
+
|
|
136
|
+
## License
|
|
137
|
+
|
|
138
|
+
Syncora Resilience Engine is distributed under the **Apache License 2.0**.
|
|
139
|
+
Copyright 2026 Syncora Systems Ltd.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/syncora/__init__.py
|
|
5
|
+
src/syncora/circuit.py
|
|
6
|
+
src/syncora/cli.py
|
|
7
|
+
src/syncora/limiter.py
|
|
8
|
+
src/syncora/retry.py
|
|
9
|
+
src/syncora_resilience.egg-info/PKG-INFO
|
|
10
|
+
src/syncora_resilience.egg-info/SOURCES.txt
|
|
11
|
+
src/syncora_resilience.egg-info/dependency_links.txt
|
|
12
|
+
src/syncora_resilience.egg-info/entry_points.txt
|
|
13
|
+
src/syncora_resilience.egg-info/requires.txt
|
|
14
|
+
src/syncora_resilience.egg-info/top_level.txt
|
|
15
|
+
tests/test_circuit.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
syncora
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import time
|
|
3
|
+
from syncora import (
|
|
4
|
+
CircuitBreaker,
|
|
5
|
+
CircuitBreakerOpenError,
|
|
6
|
+
State,
|
|
7
|
+
retry,
|
|
8
|
+
TokenBucketRateLimiter,
|
|
9
|
+
RateLimitExceededError
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
def test_circuit_breaker_transitions():
|
|
13
|
+
cb = CircuitBreaker(name="test", failure_threshold=2, recovery_timeout=0.2)
|
|
14
|
+
assert cb.state == State.CLOSED
|
|
15
|
+
|
|
16
|
+
def failing():
|
|
17
|
+
raise ValueError("Service error")
|
|
18
|
+
|
|
19
|
+
with pytest.raises(ValueError):
|
|
20
|
+
cb.call(failing)
|
|
21
|
+
assert cb.state == State.CLOSED
|
|
22
|
+
|
|
23
|
+
with pytest.raises(ValueError):
|
|
24
|
+
cb.call(failing)
|
|
25
|
+
assert cb.state == State.OPEN
|
|
26
|
+
|
|
27
|
+
# Fast fail
|
|
28
|
+
with pytest.raises(CircuitBreakerOpenError):
|
|
29
|
+
cb.call(lambda: 123)
|
|
30
|
+
|
|
31
|
+
# Wait for recovery timeout
|
|
32
|
+
time.sleep(0.25)
|
|
33
|
+
assert cb.state == State.HALF_OPEN
|
|
34
|
+
|
|
35
|
+
# Successful call resets state to CLOSED
|
|
36
|
+
res = cb.call(lambda: "ok")
|
|
37
|
+
assert res == "ok"
|
|
38
|
+
assert cb.state == State.CLOSED
|
|
39
|
+
|
|
40
|
+
def test_retry_decorator_success():
|
|
41
|
+
attempts = 0
|
|
42
|
+
@retry(max_attempts=3, initial_delay=0.01)
|
|
43
|
+
def flaky():
|
|
44
|
+
nonlocal attempts
|
|
45
|
+
attempts += 1
|
|
46
|
+
if attempts < 2:
|
|
47
|
+
raise ConnectionError("Transient error")
|
|
48
|
+
return "success"
|
|
49
|
+
|
|
50
|
+
assert flaky() == "success"
|
|
51
|
+
assert attempts == 2
|
|
52
|
+
|
|
53
|
+
def test_rate_limiter_tokens():
|
|
54
|
+
limiter = TokenBucketRateLimiter(rate=10, capacity=2)
|
|
55
|
+
assert limiter.acquire(1) is True
|
|
56
|
+
assert limiter.acquire(1) is True
|
|
57
|
+
assert limiter.acquire(1) is False
|
|
58
|
+
with pytest.raises(RateLimitExceededError):
|
|
59
|
+
limiter.check(1)
|