Skip to content

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 message.format().

()
**kwargs Any

Forwarded as error_code / error_data to the constructor.

{}

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 X-RateLimit-Reset), for deterministic tests.

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 httpx.AsyncClient.

required
name str

Default circuit/breaker key when :meth:request is not given an explicit key.

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

(key, old_state, new_state) called on every circuit transition. Defaults to an AppLogger warning — this is the metrics seam; wire it to your own backend rather than importing OpenTelemetry here.

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 asyncio.sleep.

None
**httpx_kwargs Any

Forwarded to httpx.AsyncClient.

{}

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 base_url per httpx rules).

required
key str | None

Circuit/breaker key. Defaults to the client's name.

None
**kwargs Any

Forwarded to httpx.AsyncClient.request.

{}

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

True for a connection/timeout error or a transient status code

bool | float

with no usable Retry-After; a float (seconds) when

bool | float

Retry-After is present and parsable; False for anything else

bool | float

(a non-transient 4xx is not retried — the case most likely to be got

bool | float

wrong).