HTTP classifiers & Retry-After
See also: DB recipes, Observability recipes, Worker recipes.
Read this page when you want to apply redress to HTTP clients and response semantics. This section is intentionally domain-specific.
For the core API surface itself, see Usage. For classification semantics, see Classification.
This recipe shows two common patterns:
1) exception-based HTTP retries (raise for status) 2) result-based retries with Retry-After support
Request body replay
A retry requires two independent properties: repeating the operation must be
safe, and every attempt must send the intended body. An idempotent method such
as PUT does not make an iterator or file handle replayable. The wrappers do not
automatically restrict retries by method; configure skip_if or your policy
according to the upstream service's semantics and idempotency-key contract.
The sync and async HTTPX helpers, including RetryingHttpxClient and
AsyncRetryingHttpxClient, support these buffered bodies:
| Argument | Supported values |
|---|---|
content |
Built-in bytes, str, or None. |
json |
JSON-compatible built-in scalar values, dictionaries, lists, and tuples. |
data |
Mappings of built-in scalar values or lists/tuples of those values. For raw bytes/text, prefer content; HTTPX's legacy data=bytes/str form is also supported. |
files |
A mapping or list/tuple of (field_name, part) pairs. Each part contains built-in bytes/text, directly or in HTTPX's (filename, payload[, content_type[, headers]]) tuple form. |
Buffered containers are copied before policy execution and again for each
attempt. Changes to the caller's original JSON, form values, multipart list,
or part headers therefore do not change a later attempt. Multipart boundaries
may be regenerated by HTTPX; field values, file payloads, filenames, and part
headers are preserved. HTTPX still performs its normal encoding and validation.
Form scalar values are str, bytes, bool, int, float, and None;
multipart metadata uses HTTPX's normal string/None and header-mapping forms.
Mappings must have unique keys. A mapping that yields duplicate keys, such as a
multidict.MultiDict with repeated entries, raises TypeError before policy
execution or sending. For repeated form fields, use data={"tag": ["one", "two"]};
for repeated uploads, use files=[("upload", ("one.txt", b"one")), ("upload", ("two.txt", b"two"))].
These forms preserve every value on the first attempt and all retries.
Other objects, iterable content (including lists of chunks), generators, async
iterators, cyclic containers, and file handles raise TypeError before the
policy runs or any request is sent. This includes seekable and in-memory files:
redress does not read, buffer, rewind, or close them. These rules also apply to a
policy limited to one attempt. Use skip_if to bypass the policy and send an
unsupported body once, or recreate the body inside an operation passed directly
to policy.call().
For example, reopening a file on every attempt keeps memory bounded and gives the operation control of the starting offset and cleanup:
import httpx
from redress import Policy, Retry, default_classifier
from redress.contrib.httpx import default_result_classifier
policy = Policy(retry=Retry(
classifier=default_classifier,
result_classifier=default_result_classifier,
max_attempts=3,
))
with httpx.Client(timeout=3.0) as client:
def upload() -> httpx.Response:
with open("payload.bin", "rb") as source:
# Seek to the same application-defined offset here if needed.
return client.put("https://api.example.com/item", content=source)
response = policy.call(upload, operation="upload_item")
Keep the underlying file unchanged for the duration of the operation. With
AsyncPolicy, create a new async iterator and manage its resources inside the
async operation on each attempt, then use await policy.call(upload).
The requests and aiohttp wrappers currently reuse body arguments without
replay validation. With requests, generators and file-backed data or files
can produce empty bodies/parts on later attempts. With aiohttp, reused async
iterators, file objects, and multipart/form payloads can be consumed or closed.
For these wrappers, use buffered bytes/text or JSON/form values that remain
unchanged throughout the operation. For streams and uploads, use a direct policy
call that recreates the body and owns cleanup on each attempt; do not assume
redirect rewind or payload caching makes separate wrapper attempts safe.
Exception-based HTTP retries
Use http_retry_after_classifier when your HTTP client raises exceptions that carry
status/headers (e.g., httpx HTTPStatusError).
import httpx
from redress import Policy, Retry
from redress.extras import http_retry_after_classifier
from redress.strategies import decorrelated_jitter, retry_after_or
policy = Policy(
retry=Retry(
classifier=http_retry_after_classifier,
strategy=retry_after_or(decorrelated_jitter(max_s=5.0)),
max_attempts=5,
deadline_s=10.0,
)
)
def fetch(url: str) -> httpx.Response:
with httpx.Client(timeout=3.0) as client:
resp = client.get(url)
resp.raise_for_status() # raises for 4xx/5xx
return resp
response = policy.call(lambda: fetch("https://httpbin.org/status/429"), operation="http_fetch")
Result-based HTTP retries (no exceptions)
Use result_classifier when you want to inspect responses without raising.
This also lets you attach Retry-After metadata explicitly.
import httpx
from redress import Classification, ErrorClass, Policy, Retry
from redress.strategies import decorrelated_jitter, retry_after_or
def classify_result(resp: httpx.Response) -> ErrorClass | Classification | None:
if resp.status_code == 429:
return Classification(klass=ErrorClass.RATE_LIMIT, retry_after_s=1.0)
if resp.status_code >= 500:
return ErrorClass.SERVER_ERROR
return None
policy = Policy(
retry=Retry(
classifier=lambda exc: ErrorClass.UNKNOWN,
result_classifier=classify_result,
strategy=retry_after_or(decorrelated_jitter(max_s=3.0)),
max_attempts=5,
deadline_s=8.0,
)
)
with httpx.Client(timeout=3.0) as client:
response = policy.call(lambda: client.get("https://httpbin.org/status/503"))
Adding a circuit breaker
Circuit breakers use the same classification that drives retries. This example trips the breaker on repeated server errors.
import httpx
from redress import CircuitBreaker, ErrorClass, Policy, Retry, default_classifier
from redress.strategies import decorrelated_jitter
breaker = CircuitBreaker(
failure_threshold=3,
window_s=30.0,
recovery_timeout_s=10.0,
trip_on={ErrorClass.SERVER_ERROR},
)
policy = Policy(
retry=Retry(
classifier=default_classifier,
strategy=decorrelated_jitter(max_s=2.0),
max_attempts=3,
deadline_s=6.0,
),
circuit_breaker=breaker,
)
def fetch(url: str) -> httpx.Response:
with httpx.Client(timeout=3.0) as client:
resp = client.get(url)
resp.raise_for_status()
return resp
response = policy.call(lambda: fetch("https://httpbin.org/status/500"), operation="http_fetch")