|
| 1 | +# Spec: Retry middleware + RetryBudget (0.4.0, slice A of Epic 3) |
| 2 | + |
| 3 | +**Date:** 2026-06-05 |
| 4 | +**Topic slug:** `retry-and-retry-budget` |
| 5 | +**Status:** drafted, awaiting user review |
| 6 | +**Target release:** 0.4.0 |
| 7 | +**Epic 3 stories rolled in:** 3-2 (Retry), 3-3 (RetryBudget), 3-4 (RetryBudget middleware integration); 3-1 (per-attempt timeout) is dissolved into the `attempt_timeout=` parameter rather than shipping as a separate middleware. |
| 8 | + |
| 9 | +## Purpose |
| 10 | + |
| 11 | +Ship `httpware`'s first resilience primitive: a `Retry` middleware that automatically retries transient failures, scoped by a Finagle-style `RetryBudget` that prevents retry storms when downstream services degrade. This is the first ship-unit of Epic 3; `Bulkhead` and extension-slot docs ship as later slices (next: `Bulkhead`; then: extension-slot docs ride with the last code PR). |
| 12 | + |
| 13 | +## Non-goals |
| 14 | + |
| 15 | +Items deliberately deferred so this slice ships clean: |
| 16 | + |
| 17 | +- **No per-call retry override.** No `extensions["httpware_retry"]` key in v1. Callers with heterogeneous retry needs construct a second `AsyncClient` with different middleware. Purely additive to add later. |
| 18 | +- **No `Backoff` protocol.** Backoff is hardcoded to exponential with full jitter (AWS-recommended). Add a protocol later if a real use case emerges (YAGNI). |
| 19 | +- **No `retry_on_exception=` configuration.** The retryable-exception set is hardcoded to `(httpware.ConnectError, httpware.TimeoutError, asyncio.TimeoutError)`. Users wanting `ChunkedEncodingError`-style additions wait for v0.5. |
| 20 | +- **No `Bulkhead`.** Slice C, separate spec. |
| 21 | +- **No standalone per-attempt-timeout middleware.** Folded into `Retry.attempt_timeout=` (3-1 dissolved during brainstorming — `asyncio.timeout()` and httpx2's built-in per-op timeouts cover the standalone use case). |
| 22 | +- **No status-code re-classification.** `RetryBudgetExhaustedError` and `httpware.TimeoutError` map cleanly to existing exception types — no new `_internal/` plumbing. |
| 23 | + |
| 24 | +## Architecture & module layout |
| 25 | + |
| 26 | +```text |
| 27 | +src/httpware/middleware/ |
| 28 | +├── __init__.py # existing; re-export Retry, RetryBudget |
| 29 | +├── chain.py # existing |
| 30 | +└── resilience/ |
| 31 | + ├── __init__.py # re-export Retry, RetryBudget |
| 32 | + ├── retry.py # Retry middleware |
| 33 | + ├── budget.py # RetryBudget token bucket |
| 34 | + └── _backoff.py # full-jitter exponential helper (private) |
| 35 | +``` |
| 36 | + |
| 37 | +A `resilience/` subpackage anticipates `Bulkhead` landing as `resilience/bulkhead.py` in slice C. Retry, RetryBudget, and backoff live in separate modules so each is independently testable: the token-bucket math is pure, the backoff helper is pure, retry orchestrates on top. |
| 38 | + |
| 39 | +`Retry` and `RetryBudget` are re-exported from `httpware/__init__.py` so the public import is `from httpware import Retry, RetryBudget`. No new optional extra — retry is core, not behind `pip install httpware[resilience]`. |
| 40 | + |
| 41 | +## Public API |
| 42 | + |
| 43 | +### `RetryBudget` (Finagle-style token bucket) |
| 44 | + |
| 45 | +```python |
| 46 | +class RetryBudget: |
| 47 | + """Token-bucket budget bounding retry rate to prevent retry storms. |
| 48 | +
|
| 49 | + Each request deposits a token; each retry attempts to withdraw one. |
| 50 | + Available retries are bounded by `percent_can_retry` of recent successful |
| 51 | + requests, with a `min_retries_per_sec` floor. |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__( |
| 55 | + self, |
| 56 | + *, |
| 57 | + ttl: float = 10.0, # seconds tokens remain valid |
| 58 | + min_retries_per_sec: float = 10.0, # floor regardless of success rate |
| 59 | + percent_can_retry: float = 0.2, # fraction of recent successes retriable |
| 60 | + ) -> None: ... |
| 61 | + |
| 62 | + def deposit(self) -> None: |
| 63 | + """Record a request (success or failure attempt). Adds one token.""" |
| 64 | + |
| 65 | + def try_withdraw(self) -> bool: |
| 66 | + """Atomically attempt to spend one retry token. |
| 67 | +
|
| 68 | + Returns True if a retry is permitted, False if the budget is exhausted. |
| 69 | + Never blocks. |
| 70 | + """ |
| 71 | +``` |
| 72 | + |
| 73 | +**Internal data structure**: a `collections.deque[tuple[float, int]]` of `(deposit_timestamp, count)` entries. `try_withdraw` first purges entries older than `ttl`, then computes: |
| 74 | + |
| 75 | +``` |
| 76 | +available = floor(recent_deposits * percent_can_retry) + (min_retries_per_sec * ttl) - withdrawn_in_window |
| 77 | +``` |
| 78 | + |
| 79 | +and decrements `withdrawn_in_window` on success. No lock is required: asyncio runs coroutines cooperatively on a single thread, so deque mutations between `await` points are atomic with respect to other coroutines on the same event loop. Cross-thread use is out of scope (consumers calling httpware from threads carry their own synchronization burden). |
| 80 | + |
| 81 | +Defaults match Finagle's published defaults (ttl=10s, percent=20%, min=10/sec), which AWS SDK and Envoy converged on independently. |
| 82 | + |
| 83 | +### `Retry` middleware |
| 84 | + |
| 85 | +```python |
| 86 | +class Retry: |
| 87 | + """Retry middleware. See module docstring for default policy.""" |
| 88 | + |
| 89 | + def __init__( |
| 90 | + self, |
| 91 | + *, |
| 92 | + max_attempts: int = 3, # total tries, including first |
| 93 | + base_delay: float = 0.1, # seconds; exponential base |
| 94 | + max_delay: float = 5.0, # cap on backoff |
| 95 | + attempt_timeout: float | None = None, # wall-clock cap per attempt |
| 96 | + retry_status_codes: frozenset[int] = DEFAULT_RETRY_STATUS_CODES, |
| 97 | + retry_methods: frozenset[str] = DEFAULT_IDEMPOTENT_METHODS, |
| 98 | + respect_retry_after: bool = True, # honor Retry-After on 429/503 |
| 99 | + budget: RetryBudget | None = None, # None -> fresh per-client default |
| 100 | + ) -> None: ... |
| 101 | + |
| 102 | + async def __call__( |
| 103 | + self, |
| 104 | + request: httpx2.Request, |
| 105 | + next: Next, |
| 106 | + ) -> httpx2.Response: ... |
| 107 | +``` |
| 108 | + |
| 109 | +Module-level constants in `retry.py` (per the user's module-constants preference): |
| 110 | + |
| 111 | +```python |
| 112 | +DEFAULT_RETRY_STATUS_CODES: typing.Final = frozenset({ |
| 113 | + HTTPStatus.REQUEST_TIMEOUT, # 408 |
| 114 | + HTTPStatus.TOO_MANY_REQUESTS, # 429 |
| 115 | + HTTPStatus.BAD_GATEWAY, # 502 |
| 116 | + HTTPStatus.SERVICE_UNAVAILABLE, # 503 |
| 117 | + HTTPStatus.GATEWAY_TIMEOUT, # 504 |
| 118 | +}) |
| 119 | +DEFAULT_IDEMPOTENT_METHODS: typing.Final = frozenset({ |
| 120 | + "GET", "HEAD", "OPTIONS", "PUT", "DELETE", |
| 121 | +}) |
| 122 | +``` |
| 123 | + |
| 124 | +`http.HTTPStatus` is used rather than bare integers per the user preference. |
| 125 | + |
| 126 | +## Behavior |
| 127 | + |
| 128 | +### Retry trigger evaluation |
| 129 | + |
| 130 | +For each completed attempt (exception OR response), `Retry` evaluates: |
| 131 | + |
| 132 | +1. **Idempotency gate.** If `request.method.upper() not in retry_methods`, return the result as-is. POST/PATCH never retry by default. |
| 133 | +2. **Failure-type gate.** Retry IF: |
| 134 | + - the attempt raised `httpware.ConnectError`, `httpware.TimeoutError`, or `asyncio.TimeoutError`; OR |
| 135 | + - the attempt returned a response with `status_code in retry_status_codes`. |
| 136 | +3. **Attempt-count gate.** If `attempt_index + 1 >= max_attempts`, stop. |
| 137 | +4. **Budget gate.** Call `budget.try_withdraw()`. If `False`, raise `RetryBudgetExhaustedError` (see "Errors raised" below). |
| 138 | +5. **Sleep, then retry.** Compute delay via backoff (Retry-After overrides if applicable), `await self._sleep(delay)`, increment attempt index. |
| 139 | + |
| 140 | +### Backoff: exponential with full jitter |
| 141 | + |
| 142 | +```python |
| 143 | +sleep = random.uniform(0, min(max_delay, base_delay * (2 ** attempt_index))) |
| 144 | +``` |
| 145 | + |
| 146 | +This is AWS's "full jitter" formulation. `attempt_index` is 0 for the first retry. With `base_delay=0.1, max_delay=5.0, max_attempts=3`, the two retry delays draw from `U(0, 0.2)` and `U(0, 0.4)` respectively — fast enough for transient blips, slow enough not to thunderbolt a recovering downstream. |
| 147 | + |
| 148 | +### `Retry-After` interaction |
| 149 | + |
| 150 | +When `respect_retry_after=True` and the response carries a `Retry-After` header (seconds or HTTP-date form), the parsed delay **overrides** the backoff schedule for that attempt. If the parsed delay exceeds `max_delay`, we cap to `max_delay` (a misbehaving server shouldn't extend our budget arbitrarily). Malformed `Retry-After` values are ignored and backoff is used. |
| 151 | + |
| 152 | +Parsing: `int(value)` first, falling back to `email.utils.parsedate_to_datetime` for HTTP-date form. |
| 153 | + |
| 154 | +### `attempt_timeout` semantics |
| 155 | + |
| 156 | +When `attempt_timeout` is not `None`, each attempt runs inside `async with asyncio.timeout(attempt_timeout):`. A firing timeout is caught inside the retry loop, mapped to `httpware.TimeoutError`, and counts as a retryable failure (subject to the failure-type and attempt-count gates). |
| 157 | + |
| 158 | +`attempt_timeout=None` is the documented default: each attempt is bounded only by httpx2's per-op timeouts. |
| 159 | + |
| 160 | +### Middleware chain position |
| 161 | + |
| 162 | +Documented recommendation (not enforced): |
| 163 | + |
| 164 | +```python |
| 165 | +AsyncClient(middleware=[ |
| 166 | + Retry(...), # outermost: each retry re-runs middleware below |
| 167 | + # observability middlewares (5-x) when they land |
| 168 | +]) |
| 169 | +``` |
| 170 | + |
| 171 | +Rationale: putting `Retry` at the outermost position means each attempt re-runs every middleware below it — relevant when, e.g., an auth-refresh middleware sits below `Retry` and needs to refresh on retry. Users who prefer "log once across all attempts" can put observability above Retry; that trade-off is documented in the docstring, not enforced. |
| 172 | + |
| 173 | +## Errors raised |
| 174 | + |
| 175 | +- **`RetryBudgetExhaustedError(httpware.ClientError)`** — raised when `budget.try_withdraw()` returns `False` AND retries would otherwise have continued. Fields: |
| 176 | + - `last_response: httpx2.Response | None` — set if the latest attempt returned a response |
| 177 | + - `last_exception: BaseException | None` — set if the latest attempt raised |
| 178 | + - `attempts: int` — number of attempts completed before the budget refused |
| 179 | + - Inherits from `ClientError` so callers catching `httpware.ClientError` already handle it. |
| 180 | +- **`max_attempts` exhausted**: the *last* error (exception or `StatusError`) is **re-raised unwrapped**. `exc.__notes__` is appended with `"httpware: gave up after N attempts"` (PEP 678) so the gave-up-after context is preserved without changing the exception type. This keeps consumer `except SomeStatusError:` blocks working unchanged. |
| 181 | +- **`attempt_timeout` firing**: caught as `asyncio.TimeoutError` inside the retry loop, re-raised as `httpware.TimeoutError` (whether retried or surfaced as the final error). This matches the existing httpx2-error-mapping pattern in the `AsyncClient` terminal. |
| 182 | + |
| 183 | +`RetryBudgetExhaustedError` lives in `src/httpware/errors.py` alongside the existing exception tree, exported from `httpware/__init__.py`. |
| 184 | + |
| 185 | +## Testing |
| 186 | + |
| 187 | +Per `planning/engineering.md §6` (test patterns): |
| 188 | + |
| 189 | +- **`tests/test_budget.py`** — unit tests for `RetryBudget` token-bucket math. Deterministic time via `monkeypatch` of `time.monotonic`. Cases: TTL expiry purges old deposits; `min_retries_per_sec` floor honored even with zero deposits; `percent_can_retry` ceiling honored under high deposit rate; `try_withdraw` returns `False` when exhausted; deposits accumulate correctly. |
| 190 | +- **`tests/test_budget_props.py`** — Hypothesis property tests. Properties: for any interleaving of `deposit()` / `try_withdraw()` calls, `available <= floor(deposits * percent) + (min_retries_per_sec * ttl)`; for any monotonic clock advance, expired tokens are purged before the next computation; total `try_withdraw() == True` count never exceeds the theoretical bound over any window. |
| 191 | +- **`tests/test_retry.py`** — middleware behavior via injected `httpx2.MockTransport`. Cases: |
| 192 | + - succeeds first try (no retry, no sleep) |
| 193 | + - succeeds on 2nd attempt after 503 |
| 194 | + - gives up after `max_attempts`, re-raises last error unwrapped with PEP-678 note |
| 195 | + - respects `Retry-After` (integer-seconds form) |
| 196 | + - respects `Retry-After` (HTTP-date form) |
| 197 | + - `Retry-After` capped at `max_delay` |
| 198 | + - skips non-idempotent methods by default (POST returns 503 → not retried) |
| 199 | + - honors `attempt_timeout` (slow mock transport → `httpware.TimeoutError`) |
| 200 | + - retries on `httpware.ConnectError` / `httpware.TimeoutError` |
| 201 | + - does NOT retry on `httpware.NotFoundError` (404) |
| 202 | + - `RetryBudgetExhaustedError` raised when budget refuses |
| 203 | + - exhausted budget exposes `last_response` / `last_exception` / `attempts` |
| 204 | + - explicit `budget=` parameter shared across two `Retry` middlewares accumulates correctly |
| 205 | +- **`tests/test_retry_props.py`** — Hypothesis property tests. For any sequence of `(status_code | exception)` mock responses and any `Retry(...)` config: total attempts never exceeds `max_attempts`; total sleep time never exceeds `max_attempts * max_delay`; never retries a non-retryable status or a non-idempotent method. |
| 206 | + |
| 207 | +**Sleep injection**: `Retry.__init__` accepts a `_sleep: Callable[[float], Awaitable[None]] = asyncio.sleep` parameter (single leading underscore, omitted from the public docstring). Tests pass a recording mock so the suite runs instantly without `freezegun` or event-loop time-travel. The same pattern can apply to `time.monotonic` in `RetryBudget` via a `_now: Callable[[], float] = time.monotonic` parameter. |
| 208 | + |
| 209 | +**Coverage target**: 100% line coverage (existing project standard). |
| 210 | + |
| 211 | +## Open questions deferred to implementation |
| 212 | + |
| 213 | +- **Budget default-instantiation policy.** When `Retry(budget=None)`, does each `AsyncClient` get a *fresh* `RetryBudget()`, or do all clients in a process share a module-level singleton? The spec says fresh-per-client (safer default; explicit shared budgets via `budget=`). Implementation should add a test pinning this. |
| 214 | +- **`attempt_timeout` vs `httpx2.Timeout` interaction.** If both fire, which exception wins? The race is implementation-defined; the test should assert *some* `httpware.TimeoutError` is raised, not which path produced it. |
| 215 | +- **Streaming request bodies are out of scope for v0.4.** `Retry` re-invokes `next(request)` with the same `httpx2.Request` object on each attempt. This is safe for bytes/JSON bodies (the body is in-memory and re-readable) but unsafe for streaming/async-iterable bodies (a consumed iterator can't replay). Streaming lands in Epic 4 (`4-3` `AsyncClient.stream`); when it ships, retry will need to refuse to retry streamed-body requests (or document that callers must supply a body factory). Add a follow-up entry to `planning/deferred-work.md` once retry merges so this isn't forgotten. |
| 216 | + |
| 217 | +## References |
| 218 | + |
| 219 | +- `planning/engineering.md` §3 (protocol seams), §6 (testing patterns), §8 (roadmap) |
| 220 | +- `planning/deferred-work.md` (no items resolved by this slice) |
| 221 | +- Finagle `RetryBudget`: https://twitter.github.io/finagle/guide/Clients.html#retry-budget |
| 222 | +- AWS SDK adaptive retry mode (token bucket): https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html |
| 223 | +- RFC 9110 §9.2.2 (idempotent methods), §8.4 (Retry-After), §15.5.5/15.6.x (status semantics) |
0 commit comments