Resilience
rn_forge.commons.integration.resilience
Async HTTP resilience with per-key circuit breakers, retry, and rate limiting.
Retries honor Retry-After and the token bucket clamps its quota from
X-RateLimit-Remaining and X-RateLimit-Reset response headers. Circuits
are keyed independently so one failing upstream does not block another.
Requires the resilience extra (purgatory, stamina, httpx) and
must be imported directly.
CircuitOpenError(message, *message_args, error_code=-1, **error_data)
Bases: AppException
A call was refused because its circuit is open.
check(value, message, *message_args, **kwargs)
classmethod
Raise this exception if value is falsy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to test. |
required |
message
|
str
|
Exception message (supports positional format args). |
required |
*message_args
|
Any
|
Forwarded to |
()
|
**kwargs
|
Any
|
Forwarded as |
{}
|
Example::
AppException.check(path.exists(), "Missing file: {}", path, error_code=404)
RateLimiter(*, capacity=100)
A token bucket clamped from rate-limit response headers.
"Never optimistic": :meth:update_from_headers only ever lowers the
known remaining quota to match what the server reports, never raises it
back up except at a reset boundary. A limiter that trusted a stale
higher count would keep sending requests a server has already decided to
reject.
Initialize :class:RateLimiter with an assumed starting capacity.
acquire(*, clock=time.time, sleep)
async
Wait, if necessary, until quota is available, then consume one unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clock
|
Callable[[], float]
|
Injectable wall-clock time source (epoch seconds, the unit
of |
time
|
sleep
|
Callable[[float], Awaitable[None]]
|
Injectable async sleep, for deterministic tests. |
required |
update_from_headers(headers)
Clamp the known remaining quota from X-RateLimit-Remaining/-Reset.
X-RateLimit-Reset is read as a Unix epoch timestamp in seconds, so
:meth:acquire compares it against a wall clock.
ResilientAsyncHttpClient(base_url, *, name, stop_after_attempt=3, wait_initial=0.5, wait_max=8.0, fail_max=5, reset_timeout=60.0, on_state_change=None, clock=time.time, sleep=None, **httpx_kwargs)
An httpx.AsyncClient wrapped in a per-key circuit breaker, retry, and rate limiting.
Breakers use the request key, falling back to the client name, so one instance can protect independent upstreams separately.
Initialize :class:ResilientAsyncHttpClient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_url
|
str
|
Forwarded to |
required |
name
|
str
|
Default circuit/breaker key when :meth: |
required |
stop_after_attempt
|
int
|
Maximum attempts per logical call (initial + retries). |
3
|
wait_initial
|
float
|
Minimum backoff before the first retry, in seconds. |
0.5
|
wait_max
|
float
|
Maximum backoff between retries, in seconds. |
8.0
|
fail_max
|
int
|
Consecutive failures before a circuit opens. A non-transient status (a 404, a 422) is the caller's error, not the upstream's, and does not count. |
5
|
reset_timeout
|
float
|
Seconds an open circuit stays open before allowing a trial request. |
60.0
|
on_state_change
|
Callable[[str, str, str], None] | None
|
|
None
|
clock
|
Callable[[], float]
|
Injectable wall-clock time source (epoch seconds) used by the rate limiter, for deterministic tests. |
time
|
sleep
|
Callable[[float], Awaitable[None]] | None
|
Injectable async sleep used by the rate limiter. Defaults
to |
None
|
**httpx_kwargs
|
Any
|
Forwarded to |
{}
|
client
property
The underlying httpx.AsyncClient.
close()
async
Close the underlying httpx.AsyncClient.
delete(url, **kwargs)
async
DELETE via :meth:request.
get(url, **kwargs)
async
GET via :meth:request.
patch(url, **kwargs)
async
PATCH via :meth:request.
post(url, **kwargs)
async
POST via :meth:request.
put(url, **kwargs)
async
PUT via :meth:request.
request(method, url, *, key=None, **kwargs)
async
Issue one logical request: rate-limited, retried, and circuit-broken.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP method. |
required |
url
|
str
|
Request URL (joined with |
required |
key
|
str | None
|
Circuit/breaker key. Defaults to the client's name. |
None
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Raises:
| Type | Description |
|---|---|
CircuitOpenError
|
The circuit for key is open; the call was never attempted. |
HTTPError
|
The final retry attempt still failed. |
parse_retry_after(value)
Parse a Retry-After header value into seconds, or None if unparsable.
Handles both forms RFC 9110 allows: delta-seconds ("120") and an
HTTP-date ("Wed, 21 Oct 2026 07:28:00 GMT").
retryable(exc)
Stamina backoff hook for transient httpx failures.
Returns:
| Type | Description |
|---|---|
bool | float
|
|
bool | float
|
with no usable |
bool | float
|
|
bool | float
|
(a non-transient 4xx is not retried — the case most likely to be got |
bool | float
|
wrong). |