01B.9 Retries, Timeouts, Backoff and Resilience

FoundationsLesson 9 of 1113,181 words8 parts
Module 01B · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Every network call your code makes will eventually fail: the DNS lookup times out, the server is mid-deploy, a load balancer sheds your request, a rate limiter pushes back. Lesson 01B.5 taught you to make the calls; this lesson teaches you what to do when they don't succeed — and, just as important, what not to do. You will learn to tell transient failures from permanent ones, to put a timeout and a total deadline on every call, to understand which operations are safe to repeat, to wait between retries with exponential backoff and jitter, to drive all of it with tenacity, and to go beyond retries with the rest of the resilience toolbox: circuit breakers, bulkheads, load shedding, fallbacks and hedged requests. Every mechanism is built on standard-library code you can run yourself, then upgraded to the real library and to the aitoolkit deliverable.

What you'll learn

  • The failure taxonomy: transient errors (timeouts, connection resets, 429, 5xx) versus permanent ones (400, 401, 403, 404, 422), why retrying a permanent error is a bug, and the two ways retries make things worse — retry amplification and retry storms
  • Timeouts done properly: the four HTTP timeouts (connect, read, write, pool), asyncio.timeout and total deadlines, propagating a remaining-time budget through retries, and what happens to work after your client gives up
  • Idempotency: which methods are safe to repeat, how idempotency keys make POST safe (the Stripe pattern), "at-least-once / at-most-once / exactly-once" in plain words, and how to design operations that are safe to retry
  • Backoff algorithms: constant, linear and exponential waits, jitter (full, equal and decorrelated — with the AWS Architecture Blog's analysis), maximum delay and attempt caps, and honouring the server's Retry-After header (delay-seconds and HTTP-date)
  • A hand-written retry() and retry_async() in the standard library — with an injectable clock so the demos are deterministic — run for real
  • tenacity 9.1.4: the decorator API, stop and wait strategies, retry predicates on exceptions and results, reraise versus RetryError, async support, statistics, and how to test retry code without waiting
  • The resilience toolbox beyond retries: circuit breakers (closed/open/half-open, built and run for real), bulkheads, load shedding, fallbacks and graceful degradation, hedged requests, the order layers should wrap each other, retry budgets, and partial failure in batches
  • How all of this changes — and doesn't change — when the calls are LLM API calls, with links to where Module 03 and Module 11C take over
  • The aitoolkit/resilience.py deliverable: retry_async, a CircuitBreaker and a Deadline, ready to drop into the toolkit

What you don't need

  • Module 02 or later. Every example calls a fake service that fails on a schedule you control — no API key, no network, no third-party packages for the runnable parts.
  • Prior resilience theory. Circuit breakers, backoff and deadlines are each explained from the failure they prevent.
  • httpx internals. Lesson 01B.5 owns the client; this lesson owns what you wrap around it. Async fluency helps — 01B.3 and 01B.4 are the prerequisites.

Setup

No API key needed. The hand-rolled retry, backoff, Retry-After parsing and circuit-breaker demos use the Python standard library only (random, time, asyncio, email.utils, datetime), so they run on a bare interpreter — Python 3.11 or newer. If you work inside the aitoolkit project from 01B.1, run them with uv run python file.py; otherwise python3 file.py works.

The tenacity examples were written and checked against tenacity 9.1.4 as of November 2026. The current release line is 9.2.x, so an unversioned install may give you a newer one; the behaviour this lesson relies on is the documented API, but check the tenacity release notes if a sample does not match:

bash
uv add tenacity        # inside the aitoolkit project
# or: pip install tenacity

The tenacity code blocks are written from the official documentation, and the behaviour they rely on (the wait formulas, stop_before_delay, the order of the after and before_sleep hooks, retry_unless_exception_type, and the decorator's handling of async callables) was checked against the tenacity 9.1.4 source on 11 November 2026. They were not executed end to end for this lesson, so any output they print is labelled illustrative. Everything else — every retry(), backoff_delay(), parse_retry_after() and CircuitBreaker demo — runs on the standard library alone, and the output pasted here is what it really prints.


What you must be able to do after this lesson#

  • Classify an error as transient or permanent and decide whether to retry
  • Set connect, read, write and pool timeouts and a total deadline
  • Make a POST safe to repeat with an idempotency key
  • Write exponential backoff with jitter and honour Retry-After
  • Retry a call with tenacity
  • Explain when a circuit breaker or fallback helps
  • Use retry_async, CircuitBreaker and Deadline from aitoolkit

Why this matters for an AI engineer#

An applied AI engineer's code is a chain of unreliable dependencies: the provider API, the embedding endpoint, the vector database, the crawl target, the user's own flaky network. Each link fails in ways that are temporary far more often than permanent — and each failure has a price. A naive try/except: pass loses work; a naive while True: retry melts your rate-limit budget and your invoice; a naive "just call it again" sends the customer two refund emails. Resilience is the discipline of deciding, per failure, whether to wait, retry, degrade, shed or give up — and of bounding the total time and money any one logical operation can spend.

You'll hear... You'll understand it after...
"It failed once — just retry it." 1.1 Transient vs permanent
"The job retried a bad request 10,000 times and got us banned." 1.3 Retry amplification and storms
"Set a timeout on every call." Part 2: Timeouts and deadlines
"The POST may have gone through — is it safe to send again?" Part 3: Idempotency
"Use exponential backoff with jitter." Part 4: Backoff
"tenacity is retrying everything, including my 400s." 5.4 Retry predicates
"The provider is down — stop calling it for a while." 6.1 Circuit breakers
"Half the batch failed; do we redo all of it?" 6.9 Partial failure in batches
"Why did the retried generation bill us twice?" 7.1 What changes for LLM APIs

Part 1: Failure is normal#

1.1 Transient vs permanent: the first sorting hat#

Every failure your code can observe falls into one of two buckets, and the whole lesson is downstream of telling them apart:

  • Transient means "the request was fine; the moment was bad". The network blinked, the server was mid-restart, a queue overflowed, you arrived during a deploy, you exceeded a rate limit that resets in a second. The same request, sent a moment later, will probably succeed. These are the only failures a retry can fix.
  • Permanent means "the request itself is wrong". The JSON is malformed, the auth token is revoked, the resource doesn't exist, the payload violates the schema. Sending the identical request again will fail identically — and every retry burns time, sockets and (for metered APIs) money while producing the same error.

HTTP gives you a rough first cut via the status code, because the standard assigns meaning to the classes:

Status class Meaning Retry?
1xx informational Interim response n/a — handled by the client library
2xx success Done n/a
3xx redirect Go elsewhere Usually handled automatically; a loop is a bug (TooManyRedirects)
4xx client error Your request is the problem Almost never — see the table below
5xx server error Their problem Usually yes, a bounded number of times
No response at all Timeout, DNS failure, connection reset, TLS error Yes — the classic transient case

The 4xx/5xx split is a rule of thumb, not a law. The exceptions matter:

  • 408 Request Timeout and 429 Too Many Requests are 4xx but transient — the server is telling you to come back later (RFC 9110 §15.5.9, RFC 6585 §4). 425 Too Early (RFC 8470) is another "come back later" 4xx.
  • 409 Conflict is often transient (the resource was mid-update) but sometimes permanent (a duplicate you must resolve differently).
  • Some APIs return 500 for what is really a permanent validation problem — sloppy servers exist. When in doubt, read the error body, not just the status.

Here's the decision table to internalise. It is deliberately generic; 03.8 applies the same logic to the four LLM providers, where the wrinkles are provider-specific (a 429 can mean "slow down" or "out of credits").

Failure Examples Retry? What to do instead
Connection failed / reset ConnectError, ReadError, RemoteProtocolError Yes Backoff + jitter
Timeout (connect/read/total) ConnectTimeout, ReadTimeout, your deadline fired Yes, carefully The request may still have completed server-side — see Part 3
408, 425, 429 Rate limited, server asking you to wait Yes Honour Retry-After if present; back off
500, 502, 503, 504 Server errors, overload, bad gateway Yes, a few times Backoff; if it persists, the input may be the trigger
400, 401, 403, 404, 422 Bad request, bad key, forbidden, missing, unprocessable Never Fix the request or the credentials; alert if it's systemic
402, quota/billing errors Out of money, quota exhausted Never Fail fast and alert a human — retrying can't add credits
DNS / TLS / certificate errors ConnectError on DNS or TLS-handshake failure Usually not blindly DNS blips are transient; a bad certificate is permanent — check which
Your own bug TypeError, KeyError, ValidationError Never A retry will crash identically; this is a programming error, not a failure of the moment

1.2 Why "just retry" is never the whole answer#

Suppose your code wraps every call in for i in range(3): try: ... except: sleep(1). Three problems, all quiet:

  1. It retries permanent errors. A 401 (revoked key) fails three times, sleeps three seconds, and still fails — while the log says "transient error, retrying", sending you debugging the network instead of the key.
  2. It waits a fixed time. If the server said "I'm overloaded, come back in 30 seconds" (Retry-After), sleeping 1 second just guarantees the next attempt also fails — you've converted a polite rate limit into a self-inflicted denial of service.
  3. It has no total budget. Three attempts × (timeout + sleep) can exceed the time your caller is willing to wait. The retry loop becomes the reason the request is late.

The rest of this lesson is the checklist that fixes each of these: classify (Part 1), bound in time (Part 2), make repeatable (Part 3), wait smartly (Part 4), automate safely (Part 5), and know when not to retry at all (Part 6).

1.3 Retry amplification and retry storms#

Retries are not free, and they multiply. Two failure modes have names because they take down real systems:

  • Retry amplification is what happens when layers each retry. Your code retries 3 times; the HTTP client library retries 2 times; the API gateway retries 2 times. One logical call becomes 1 × 3 × 2 × 2 = 12 actual requests — and if the gateway's retries hit a different backend each time, your "one retry" is really load on the whole fleet. This is why 03.8 §5.5 insists that exactly one layer owns retries: typically yours, with the SDK's built-in retries turned off (max_retries=0 on the OpenAI and Anthropic clients).
  • Retry storms (also called retry synchronisation or the thundering herd — 01B.4 introduced the herd) happen when many clients fail together — a provider blip, a deploy, a shared downstream — and then all retry on the same schedule. If every client waits exactly 1 s, 2 s, 4 s, they all hammer the recovering server at the same instants, and the server falls over again. Jitter (4.2) is the fix: it spreads the retries out so the server gets a smooth trickle instead of a synchronized wave.

The cost side is equally real: every retry of a metered API call can cost money if the first attempt actually ran (a timed-out generation may still have been billed — 03.8 §6.6), and every retry of a side-effecting call can duplicate the effect (Part 3). A retry is a bet that "the failure was about timing" — the rest of the lesson is about making that bet well.


Part 2: Timeouts and deadlines#

2.1 Why every call needs a timeout#

A network call without a timeout is a loaded gun pointed at your event loop. If the far end accepts your TCP connection and then goes silent — no response, no FIN, no RST — your code waits forever: the coroutine never resumes, the request handler never returns, the worker slot never frees. Multiply by concurrency and one hung dependency takes down the whole service. This is the single most common production outage pattern in I/O-bound Python, and the fix is boring: every outbound call gets a timeout, and the timeout is chosen, not defaulted.

Two distinct concepts get conflated constantly, so fix the vocabulary now:

  • A timeout bounds one wait: how long a single operation (connect, read one chunk, write) may take.
  • A deadline bounds the whole logical operation: the total time budget across all attempts, retries, sleeps and sub-calls. You set it once at the top and pass the remaining budget down.

A timeout answers "is this step stuck?". A deadline answers "has this request been allowed to take any longer?". You need both: timeouts keep individual steps from hanging, and the deadline keeps the sum of steps and retries inside the caller's patience.

2.2 The four HTTP timeouts#

httpx (lesson 01B.5) models a request as four separate waits, and httpx.Timeout lets you bound each independently:

Timeout Bounds Typical value What a violation means
connect Opening the TCP/TLS connection 5 s Host unreachable, firewall dropping SYNs, DNS resolved but nothing listening
read Waiting for response data — per chunk, not the whole body 10–60 s for APIs; longer for LLM streams Server accepted but is slow, or the stream stalled mid-body
write Sending the request body 5–10 s Upload stalled; mostly matters for big payloads
pool Waiting for a free connection from the pool 5 s Your own client is saturated — you opened too many concurrent calls (see 01B.4)
python
# http.py — an httpx client with deliberately chosen timeouts (illustrative:
# needs httpx; see lesson 01B.5 for the full client setup)
import httpx

TIMEOUT = httpx.Timeout(
    connect=5.0,    # a dead host should fail fast
    read=30.0,      # slow APIs get room; LLM calls need more — see below
    write=10.0,
    pool=5.0,       # pool starvation is our bug, not the server's — fail fast
)

client = httpx.Client(timeout=TIMEOUT, limits=httpx.Limits(max_connections=100))

2.3 asyncio.timeout and friends#

In async Python you have two stdlib tools for bounding a block of code:

python
import asyncio

async def fetch_with_budget(coro, seconds: float):
    try:
        async with asyncio.timeout(seconds):      # Python 3.11+
            return await coro
    except TimeoutError:
        return None                                # give up cleanly
  • asyncio.timeout(delay) (3.11+) is a context manager: on exit past the deadline it cancels the block and raises TimeoutError. It composes — nest it and the innermost wins — and it cancels the awaited work, which is what you want: the coroutine gets a CancelledError at its current await point and can clean up in finally.
  • asyncio.timeout_at(when) takes an absolute loop.time() deadline instead of a relative delay — the primitive you use to implement "the whole request gets 10 s, minus what we've already spent".
  • asyncio.wait_for(coro, timeout) is the older function form; it also cancels on timeout but is being superseded by asyncio.timeout in new code (the context manager version handles nested cancellation more predictably).

2.4 Deadlines: the total budget#

Here is the pattern that separates toy retries from production ones. The caller says "this whole operation may take at most D seconds". Every layer below shares that one number:

python
import asyncio
import time

class Deadline:
    """A monotonic-clock budget shared across retries and sub-calls."""
    def __init__(self, seconds: float) -> None:
        self._end = time.monotonic() + seconds

    def remaining(self) -> float:
        return max(0.0, self._end - time.monotonic())

    @property
    def expired(self) -> bool:
        return self.remaining() <= 0

    def timeout(self):
        """An asyncio.timeout for whatever is left of the budget."""
        return asyncio.timeout(self.remaining())

Used like this:

python
import httpx

# retry_policy() is shorthand for the AsyncRetrying policy built in Part 5;
# Deadline is the class above. Sketch — see 01B.5 for the client setup.
# (The Part 8 deliverable ships the general version of this idea as
# `call_with_retry(fn, *args, policy=...)` — same name, callable-shaped.)
async def call_with_retry(client, payload, *, deadline_seconds: float = 20.0):
    deadline = Deadline(deadline_seconds)
    async for attempt in retry_policy():
        with attempt:
            async with deadline.timeout():                  # whole attempt inside budget
                resp = await client.post("/v1/complete", json=payload,
                                          timeout=httpx.Timeout(30.0))
                return resp.json()

The arithmetic is the point: if the deadline is 20 s and attempt 1 burns 8 s before timing out, attempt 2's deadline.timeout() gives it only ~12 s — the retries share the budget, they don't each get a fresh 20 s. Without this, attempts=4 × timeout=30 s can run for two minutes inside a request the caller abandoned at 30 s.

2.5 What happens after the timeout#

The moment your client gives up, the server doesn't necessarily stop. Three cases:

  1. The request never arrived (connect timeout, DNS failure) — nothing happened server-side; safe to retry.
  2. The request arrived, the response was lost (read timeout mid-body, connection reset after the server finished) — the work was done, you just didn't see the receipt. Retrying a GET is harmless; retrying a POST may duplicate the effect. This is the idempotency problem, fully in Part 3.
  3. The request is still running (you timed out at 30 s, the model is still generating at 45 s) — the server will finish, bill, and possibly trigger side effects (a tool call that sends an email) after you've already retried and gotten a second answer. For LLM APIs this is why 03.8 §6.6 warns that "timeouts that still bill" are a cost leak, not just a latency one.

The practical rule: a timeout converts "waiting" into "unknown". Your retry logic must treat post-timeout retries as potentially duplicating work — which is why the next part exists before the backoff part.


Part 3: Idempotency#

3.1 What "idempotent" actually means#

An operation is idempotent when performing it once and performing it n times have the same effect. GET /tickets/42 is idempotent: asking for ticket 42 ten times returns the same ticket ten times and changes nothing. DELETE /tickets/42 is idempotent: the first delete removes it; the second returns 404 — annoying but not wrong, because the end state (ticket gone) is identical. POST /tickets that creates a ticket is not idempotent: ten posts create ten tickets.

The HTTP spec formalises this: RFC 9110 §9.2 defines safe methods (§9.2.1) (GET, HEAD, OPTIONS, TRACE) and idempotent methods (§9.2.2: PUT, DELETE, plus the safe ones) — and pointedly does not include POST, because POST means "process this, the outcome may differ each time" (create, charge, send, enqueue).

3.2 The three delivery promises#

Distributed systems describe message delivery with three promises, and they're worth knowing because providers' SLAs are written in them:

Promise Meaning Can you get it?
At-most-once The operation happens zero or one times — never twice Easy: don't retry. But "zero times" means lost work when the failure was transient
At-least-once The operation happens one or more times — never zero What retries give you: if you keep trying until something answers, the work eventually lands — possibly more than once
Exactly-once The operation happens exactly once, guaranteed A myth at the network level; what you actually build is effectively-once via idempotency

3.3 Idempotency keys: making POST safe#

The standard solution is an idempotency key: a unique token the client generates per logical operation and sends with the request. The server remembers "I've seen key K" and, if the same key arrives again, returns the first result instead of doing the work twice.

Stripe's API is the canonical example (docs, verified November 2026):

bash
# First attempt — times out, you never see the response
curl https://api.stripe.com/v1/payment_intents \
  -u sk_test_...: \
  -H "Idempotency-Key: 9f2c1e7a-..." \
  -d amount=2000 -d currency=usd

# Retry with the SAME key and SAME parameters — Stripe returns the original
# result instead of charging twice. Same key + different parameters = error.

The rules that make it work (from Stripe's docs): the key is up to 255 characters, should be a random UUID ("avoid sensitive data"), results are kept ~24 h for API v1, and the parameters must match the original request — the key identifies the request, not just the intent.

python
# The pattern in Python: one key per logical operation, reused across retries
import uuid

def create_charge_once(client, payload: dict) -> dict:
    key = str(uuid.uuid4())                     # generated ONCE, outside the retry loop
    for attempt in retry_policy():
        with attempt:
            return client.post("/v1/payment_intents", json=payload,
                               headers={"Idempotency-Key": key}).json()

3.4 When the API has no idempotency keys#

Most APIs — including, as of November 2026, none of the four LLM inference providers — don't accept idempotency keys on model calls (03.8 §11.1 verifies this provider by provider). You build the dedupe yourself:

  1. Natural idempotency — make the operation itself safe. PUT /tickets/42 {status: "closed"} run twice ends in the same state; POST /charges doesn't. Prefer update-style operations where the domain allows.
  2. Your own dedupe table — before executing a side effect, compute a stable key (hash of the operation's identity: user + action + target + payload), check a done_keys table, execute only if new, record the key and the result. 03.8 §11.3 shows this with SQLite for LLM tool calls.
  3. Check-before-retry — for "did it happen?" cases, query state first: GET /tickets?email=x before re-sending the "create ticket" email.
  4. Accept and reconcile — for genuinely non-idempotent operations (a charge, an email), accept that a retry might duplicate and build reconciliation: a nightly job that finds and refunds duplicates. Last resort, but honest.

3.5 Designing retryable operations#

A checklist for "can I retry this?":

  • The operation is a safe method (GET/HEAD) or idempotent (PUT/DELETE) — free retry.
  • It's a POST but the API supports idempotency keys — retry with the key.
  • It's a POST with no key support — add your own dedupe or don't retry blindly.
  • It has side effects outside your control (sends email, charges card, writes to a third party) — the side effect needs its own idempotency, downstream of your retry.
  • The failure mode is "did it happen?" — query state before retrying, don't assume.

Part 4: Backoff#

4.1 Constant, linear, exponential#

Once you've decided a failure is worth retrying, the next question is when. Three shapes cover almost everything:

Strategy Wait before retry n Behaviour When it's right
Constant base every time Predictable, simple The failure isn't load-related (a flaky DNS blip); rare in practice
Linear base × n Grows slowly: 0.5, 1.0, 1.5, 2.0 s Mild backpressure; almost never enough for a struggling server
Exponential min(cap, base × 2ⁿ⁻¹) Doubles each time: 0.5, 1, 2, 4, 8 s… The default for transient failures — gives the server exponentially more room to recover

Exponential is the workhorse because failures that are about load (overload, rate limits, connection exhaustion) get worse the harder you push, and better the longer you wait. The cap (maximum delay) matters as much as the base: without it, the tenth retry waits 0.5 × 2⁹ = 256 s — you've built a very patient outage. A cap of 8–30 s is typical for interactive calls; batch jobs can afford more.

Run for real — the same seed, four strategies, six retries each:

python
# backoff_demo.py — the four shapes side by side (stdlib only)
import random

BASE, CAP = 0.5, 8.0
N = 6

def schedule(name, fn, seed=42):
    rng = random.Random(seed)
    waits = [round(fn(i + 1, rng=rng), 2) for i in range(N)]
    print(f"{name:<38} {waits}")

ceilings = [round(min(CAP, BASE * 2 ** i), 2) for i in range(N)]
print(f"exponential ceiling (base={BASE}, cap={CAP}): {ceilings}\n")

schedule("constant 0.5s",            lambda a, rng: 0.5)
schedule("linear 0.5 * attempt",     lambda a, rng: min(CAP, 0.5 * a))
schedule("exponential, NO jitter",   lambda a, rng: min(CAP, BASE * 2 ** (a - 1)))
schedule("exponential + full jitter", lambda a, rng: rng.uniform(0, min(CAP, BASE * 2 ** (a - 1))))
Output6 lines
exponential ceiling (base=0.5, cap=8.0): [0.5, 1.0, 2.0, 4.0, 8.0, 8.0]

constant 0.5s                          [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
linear 0.5 * attempt                   [0.5, 1.0, 1.5, 2.0, 2.5, 3.0]
exponential, NO jitter                 [0.5, 1.0, 2.0, 4.0, 8.0, 8.0]
exponential + full jitter              [0.32, 0.03, 0.55, 0.89, 5.89, 5.41]

The ceiling row is what exponential could wait; the jittered row is what it actually waits — anywhere from near-zero up to the ceiling, because uniform(0, ceiling) is the definition of full jitter.

4.2 Jitter: full, equal and decorrelated#

Plain exponential backoff has a fatal flaw at scale: if a thousand clients all hit the same failure at the same instant (a provider blip, a shared downstream), they all compute the same delays — 0.5, 1, 2, 4 — and all retry at the same instants. The recovering server gets a synchronized wave it can't absorb, and falls over again. Jitter breaks the synchronisation by randomising each wait.

Marc Brooker's post "Exponential Backoff And Jitter" on the AWS Architecture Blog (2015) is the standard reference; it compared four formulas that are still what everyone means when they say "exponential backoff with jitter":

Strategy Wait before retry n One sentence
Exponential (no jitter) min(cap, base × 2ⁿ⁻¹) Predictable — and synchronised across clients
Full jitter random(0, min(cap, base × 2ⁿ⁻¹)) Anywhere from zero up to the exponential ceiling
Equal jitter ceiling/2 + random(0, ceiling/2) Always waits at least half the ceiling
Decorrelated jitter min(cap, random(base, previous × 3)) Grows from the previous wait, not the attempt number

The post's conclusions, which are still quoted everywhere: "the no-jitter exponential backoff approach is the clear loser", "of the jittered approaches, 'Equal Jitter' is the loser", and "'Full Jitter' uses less work, but slightly more time" than decorrelated jitter. For your own code, full jitter (uniform(0, ceiling)) is the right default: simplest, and it spreads retries across the whole window. Decorrelated jitter is what you reach for when you want waits that trend upward without a fixed schedule — it depends on the previous sleep, so it needs state.

4.3 Retry-After: the server knows best#

When a server knows how long you should wait — its queue depth, its recovery time, its rate-limit window — it says so in the Retry-After response header, and that beats any backoff formula: the server can see itself, you can't.

The standard (RFC 9110 §10.2.3) defines two forms:

text
Retry-After: 30                              # delay-seconds: wait 30 seconds
Retry-After: Fri, 06 Nov 2026 12:00:30 GMT   # HTTP-date: wait until this instant

Retry-After is defined by RFC 9110 for 503 responses and 3xx redirects, and RFC 6585 §4 says a 429 response "MAY include a Retry-After header indicating how long to wait". Parsing it correctly is a small but real piece of work — the date form needs an HTTP-date parser, and both forms need clamping (a past date means "now", a huge value means "give up"). Python's stdlib does it:

python
# retry_after.py — parse a Retry-After header into seconds-to-wait (stdlib only)
import math
import time
from datetime import timezone
from email.utils import parsedate_to_datetime

def parse_retry_after(value: str | None, *, now: float | None = None) -> float | None:
    """Seconds to wait from a Retry-After header: '30' or an HTTP-date.
    `now` is a POSIX timestamp (time.time()); injectable for tests.
    Returns None when the header is missing or unparseable."""
    if not value:
        return None
    value = value.strip()
    try:
        seconds = float(value)              # delay-seconds (fractional tolerated)
    except ValueError:
        pass
    else:
        # 'inf' and 'nan' parse as floats but aren't real hints — reject them
        return max(0.0, seconds) if math.isfinite(seconds) else None
    try:
        when = parsedate_to_datetime(value)    # HTTP-date
    except (TypeError, ValueError):
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    current = time.time() if now is None else now
    return max(0.0, when.timestamp() - current)

Run for real:

python
# demo: every shape a server can send
from datetime import datetime, timezone
NOW = datetime(2026, 11, 6, 12, 0, 0, tzinfo=timezone.utc).timestamp()
for value in ["30", "  2.5  ", "0",
              "Fri, 06 Nov 2026 12:00:45 GMT",
              "Fri, 06 Nov 2026 11:59:30 GMT",
              "not-a-date", "", None]:
    print(f"{str(value):<32} -> {parse_retry_after(value, now=NOW)}")
Output8 lines
30                               -> 30.0
  2.5                            -> 2.5
0                                -> 0.0
Fri, 06 Nov 2026 12:00:45 GMT    -> 45.0
Fri, 06 Nov 2026 11:59:30 GMT    -> 0.0
not-a-date                       -> None
                               -> None
None                             -> None

How to use the hint, in order of precedence:

  1. Wait at least that long, plus a small random amount — if 1,000 clients are all told "30 s", they should still spread out, not return in lockstep.
  2. Cap it. A Retry-After: 3600 inside a web request is a failure, not a wait. If the hint exceeds your remaining budget, give up (or queue the work for later). 03.8 §7.2 covers provider-specific hints (retry-after-ms, Gemini's RetryInfo in the body).
  3. Fall back to full-jitter backoff when there's no hint or it can't be parsed.
  4. Share it. A rate-limit hint applies to your whole account, not just this call — tell your rate limiter so sibling calls wait too (01B.4).

4.4 Hand-written retry(): the whole mechanism in ~40 lines#

Before reaching for a library, it's worth seeing that a correct retry is small. Here's the whole thing — standard library only, with sleep, clock and rng injectable so tests and demos never really wait:

python
# mini_resilience.py — part 1: hand-rolled retries and backoff.
# Standard library only. `clock` and `sleep` are injectable: tests and demos
# pass a fake clock instead of really waiting. (The circuit breaker that
# completes this file is added in Part 6; the Retry-After parser is the
# separate retry_after.py from 4.3.)
import asyncio
import logging
import random
import time
from typing import Any, Callable, TypeVar

T = TypeVar("T")


class TransientError(Exception):
    """A failure that may succeed if tried again: timeout, reset, 503, 429."""


class PermanentError(Exception):
    """A failure that will never succeed on retry: 400, 401, 404, bad input."""


def backoff_delay(failed_attempts: int, *, base: float = 0.5, cap: float = 8.0,
                  rng: random.Random | None = None) -> float:
    """Full-jitter exponential backoff before the next retry.
    `failed_attempts` is how many attempts have already failed (1 = first
    failure). The ceiling doubles each time: base, 2*base, 4*base ... capped.
    The actual wait is uniform(0, ceiling) — "full jitter"."""
    rng = rng or random
    ceiling = min(cap, base * 2 ** (failed_attempts - 1))
    return rng.uniform(0.0, ceiling)


def retry(
    fn: Callable[[], T],
    *,
    attempts: int = 4,
    base_delay: float = 0.5,
    max_delay: float = 8.0,
    deadline: float | None = None,                    # monotonic timestamp
    is_retryable: Callable[[BaseException], bool] = lambda e: isinstance(e, TransientError),
    sleep: Callable[[float], None] = time.sleep,
    clock: Callable[[], float] = time.monotonic,
    rng: random.Random | None = None,
    on_retry: Callable[[int, BaseException, float], None] | None = None,
) -> T:
    """Call fn() until it returns, raises a non-retryable error, runs out of
    attempts, or can't afford the next wait inside `deadline`.
    Returns fn's result; raises the last exception on failure."""
    for attempt in range(1, attempts + 1):
        try:
            return fn()
        except Exception as exc:
            if attempt == attempts or not is_retryable(exc):
                raise
            delay = backoff_delay(attempt, base=base_delay, cap=max_delay, rng=rng)
            if deadline is not None:
                remaining = deadline - clock()
                if remaining <= 0 or delay > remaining:
                    raise                      # can't afford the wait: fail now
            if on_retry is not None:
                on_retry(attempt, exc, delay)
            sleep(delay)
    raise AssertionError("unreachable")


async def retry_async(
    fn: Callable[[], Any],
    *,
    attempts: int = 4,
    base_delay: float = 0.5,
    max_delay: float = 8.0,
    deadline: float | None = None,
    is_retryable: Callable[[BaseException], bool] = lambda e: isinstance(e, TransientError),
    sleep: Callable[[float], Any] = asyncio.sleep,
    clock: Callable[[], float] = time.monotonic,
    rng: random.Random | None = None,
    on_retry: Callable[[int, BaseException, float], None] | None = None,
) -> T:
    """The async twin of retry(): `fn` is an async callable, `sleep` an async one."""
    for attempt in range(1, attempts + 1):
        try:
            return await fn()
        except Exception as exc:
            if attempt == attempts or not is_retryable(exc):
                raise
            delay = backoff_delay(attempt, base=base_delay, cap=max_delay, rng=rng)
            if deadline is not None:
                remaining = deadline - clock()
                if remaining <= 0 or delay > remaining:
                    raise
            if on_retry is not None:
                on_retry(attempt, exc, delay)
            await sleep(delay)
    raise AssertionError("unreachable")

Every parameter is there for a reason you now know: attempts caps the count, base_delay/max_delay shape the exponential, deadline bounds the total, is_retryable is the classifier that keeps permanent errors out, sleep/clock/rng make it testable, and on_retry is where your logging goes (Part 7).

4.5 Run it: a flaky service and a fake clock#

The demo uses a FakeClock — a time.monotonic stand-in that only advances when sleep() is called — so the "elapsed" times are virtual and the output is identical every run:

python
# demo_retry.py — hand-written retry() with a fake clock (stdlib only)
import random
from mini_resilience import PermanentError, TransientError, retry

class FakeClock:
    """A monotonic clock that only moves when sleep() is called."""
    def __init__(self):
        self.t = 0.0
    def __call__(self):
        return self.t
    def sleep(self, seconds):
        self.t += seconds

clock = FakeClock()
log = []
def on_retry(attempt, exc, delay):
    log.append(f"  t={clock():5.2f}s  attempt {attempt} failed ({exc}); "
               f"sleeping {delay:.2f}s")

def flaky(failures_before_success: int, label: str):
    """A service that raises TransientError N times, then works."""
    state = {"calls": 0}
    def fn():
        state["calls"] += 1
        if state["calls"] <= failures_before_success:
            raise TransientError(f"{label}: connection reset (call {state['calls']})")
        return f"{label}: ok after {state['calls']} calls"
    return fn, state

rng = random.Random(7)

# Scenario 1: two transient failures, then success
fn, state = flaky(2, "ticket-api")
result = retry(fn, attempts=4, base_delay=0.5, max_delay=8.0,
               sleep=clock.sleep, clock=clock, rng=rng, on_retry=on_retry)
print("\n".join(log)); log.clear()
print(f"  -> {result}  | virtual elapsed: {clock():.2f}s\n")

# Scenario 2: a PermanentError is never retried
def always_bad():
    raise PermanentError("ticket-api: 400 bad request — your payload is wrong")
try:
    retry(always_bad, attempts=4, sleep=clock.sleep, clock=clock, rng=rng, on_retry=on_retry)
except PermanentError as e:
    print(f"  -> gave up immediately: {e}")

# Scenario 3: transient failures outlast the attempt budget
fn3, state3 = flaky(10, "ticket-api")
try:
    retry(fn3, attempts=4, base_delay=0.5, max_delay=8.0,
          sleep=clock.sleep, clock=clock, rng=rng, on_retry=on_retry)
except TransientError as e:
    print("\n".join(log)); log.clear()
    print(f"  -> gave up: {e}  | calls made: {state3['calls']}  | virtual elapsed: {clock():.2f}s")

# Scenario 4: a deadline the next wait can't fit inside
fn4, state4 = flaky(10, "ticket-api")
deadline = clock() + 0.05   # only 50 ms of budget left
try:
    retry(fn4, attempts=4, base_delay=0.5, max_delay=8.0,
          deadline=deadline, sleep=clock.sleep, clock=clock, rng=rng,
          on_retry=on_retry)
except TransientError as e:
    print("\n".join(log)); log.clear()
    print(f"  -> gave up at the deadline: {e}  | calls made: {state4['calls']}")
Output11 lines
  t= 0.00s  attempt 1 failed (ticket-api: connection reset (call 1)); sleeping 0.16s
  t= 0.16s  attempt 2 failed (ticket-api: connection reset (call 2)); sleeping 0.15s
  -> ticket-api: ok after 3 calls  | virtual elapsed: 0.31s

  -> gave up immediately: ticket-api: 400 bad request — your payload is wrong
  t= 0.31s  attempt 1 failed (ticket-api: connection reset (call 1)); sleeping 0.33s
  t= 0.64s  attempt 2 failed (ticket-api: connection reset (call 2)); sleeping 0.07s
  t= 0.71s  attempt 3 failed (ticket-api: connection reset (call 3)); sleeping 1.07s
  -> gave up: ticket-api: connection reset (call 4)  | calls made: 4  | virtual elapsed: 1.78s

  -> gave up at the deadline: ticket-api: connection reset (call 1)  | calls made: 1

Read it carefully — every behaviour you need is on the page:

  • Scenario 1 retried twice with jittered waits (0.16 s, 0.15 s — both under the 0.5 s ceiling) and succeeded on call 3.
  • Scenario 2 made exactly one call: PermanentError isn't TransientError, so is_retryable refused and the exception propagated immediately.
  • Scenario 3 exhausted attempts=4, made 4 calls, and raised the last TransientError — not a generic "retries failed" wrapper.
  • Scenario 4 is the deadline doing its job: after the first failure, the computed wait didn't fit inside the 50 ms remaining budget, so it gave up before sleeping — calls made: 1, virtual time didn't advance. This is stop_before_delay semantics, hand-rolled.

And the async version is the same loop with await — the only real difference is that await sleep(delay) yields to the event loop, so other tasks keep running while one request backs off:

python
# demo_retry_async.py — retry_async() for real; tiny real sleeps (stdlib only)
import asyncio
import random
from mini_resilience import TransientError, retry_async

async def main() -> None:
    ticks = {"n": 0}
    stop = asyncio.Event()

    async def heartbeat():
        while not stop.is_set():
            ticks["n"] += 1
            await asyncio.sleep(0.002)

    hb = asyncio.create_task(heartbeat())
    calls = {"n": 0}

    async def flaky_fetch() -> str:
        calls["n"] += 1
        if calls["n"] <= 2:
            raise TransientError(f"reset on call {calls['n']}")
        return "payload"

    ticks_before = ticks["n"]
    result = await retry_async(
        flaky_fetch, attempts=4, base_delay=0.02, max_delay=0.05,
        rng=random.Random(3),
        on_retry=lambda a, e, d: print(f"  retry #{a} scheduled in {d*1000:.0f} ms ({e})"),
    )
    during = ticks["n"] - ticks_before
    print(f"-> {result!r} after {calls['n']} attempts")
    print(f"-> heartbeat ticked during the retry sleeps: {during > 0}")

asyncio.run(main())
Output4 lines
  retry #1 scheduled in 5 ms (reset on call 1)
  retry #2 scheduled in 22 ms (reset on call 2)
-> 'payload' after 3 attempts
-> heartbeat ticked during the retry sleeps: True

The heartbeat is the point: while retry_async slept between attempts, the event loop ran other tasks. A sync time.sleep in the same position would have frozen everything — the bug 01B.3 warned about, now with a concrete reason to care.


Part 5: tenacity#

tenacity is the standard Python retry library — "a general-purpose retrying library to simplify the task of adding retry behaviour to just about anything", in its own words. It's what the OpenAI rate-limits guide's examples reach for, and what 03.8 Part 8 builds the provider-aware policy on. This part teaches the library itself; that lesson applies it to LLM errors specifically.

The core idea: a retry policy is built from small composable pieces — when to stop, how long to wait, what to retry — and tenacity lets you mix and match them with decorators, context managers or explicit loops.

5.1 The three knobs#

Every tenacity policy answers three questions:

Knob Question Examples
stop When do we give up? stop_after_attempt(4), stop_after_delay(30), stop_before_delay(30)
wait How long between attempts? wait_fixed(2), wait_exponential(...), wait_random_exponential(...), wait_chain(...)
retry Which failures are worth another try? retry_if_exception_type(...), retry_if_exception(predicate), retry_if_result(predicate)

The defaults are deliberately dangerous — @retry with no arguments retries forever on any exception with no wait. That's a footgun for learners and a feature for the "keep trying until it works" cases. Always set all three.

5.2 Stop conditions#

Stop Meaning Watch out for
stop_after_attempt(n) Give up after n total attempts n=1 means "try once, never retry" — sometimes what you want
stop_after_delay(s) Give up once s seconds have passed since the first attempt Checked after a failure, so a long sleep + attempt can overrun the budget
stop_before_delay(s) Give up if the next sleep would end past s seconds The deadline-correct one: it never starts a wait it can't finish (4.5 scenario 4 showed the same logic hand-rolled)
stop_a | stop_b Stop when either says stop Compose attempt + delay limits
python
# A policy that stops on whichever comes first: 4 attempts or ~20 s of budget
from tenacity import stop_after_attempt, stop_before_delay

stop = stop_after_attempt(4) | stop_before_delay(20)

5.3 Wait strategies — and the two "jitter" waits that aren't the same#

The wait strategies map directly onto Part 4:

Strategy Formula Jitter?
wait_fixed(wait) wait seconds every time No
wait_random(min=…, max=…) uniform(min, max) Yes, but not exponential
wait_exponential(multiplier=…, max=…, exp_base=2, min=…) multiplier × exp_baseⁿ⁻¹, clamped to [min, max] No — the herd problem
wait_random_exponential(multiplier=…, max=…) uniform(min, ceiling) where ceiling is the clamped exponential — uniform(0, ceiling) by default Full jitter — the one you want
wait_exponential_jitter(initial=…, max=…, exp_base=2, jitter=…) min(initial × exp_baseⁿ⁻¹ + uniform(0, jitter), max) Partial — exponential plus noise, not up to the ceiling
wait_chain(*waits) First strategy for attempt 1, second for 2… last repeats For "quick retries, then patient ones"
wait_a + wait_b Sum of two waits e.g. wait_fixed(3) + wait_random(0, 2) = at least 3 s plus up to 2 s of jitter

Two signature details worth knowing: exp_base (default 2) sits between max and min/jitter in the real signatures, so always pass these strategies by keyword — wait_exponential_jitter(0.5, 8, 1) positionally sets exp_base=1, after which 1**(n−1) is 1 forever and every wait collapses to initial + jitter with no error. exp_base is the growth factor: 3 triples the ceiling each attempt, 1.5 grows gently. And wait_random_exponential is also exported under its blog-name alias wait_full_jitter.

5.4 Retry predicates: exceptions and results#

retry= decides which failures deserve another attempt. The building blocks:

Predicate Retries when…
retry_if_exception_type(types) The exception is an instance of types — coarse, can't see a 429's code
retry_if_not_exception_type(types) The exception is not one of types (retry everything except these)
retry_if_exception(predicate) predicate(exception) returns true — the one you want for status-code-aware decisions
retry_if_result(predicate) The function returned a value matching predicate — for "the call succeeded but the answer is unusable"
retry_any(a, b) / retry_all(a, b) Combine predicates: any-match / all-match
retry_unless_exception_type(types) The exception is not one of types — and, easy to miss, also when the call returns normally. It only stops once one of types is raised, so it suits polling loops ("keep calling until NotFound appears"), not ordinary error handling

The mistake to avoid is retry_if_exception_type(Exception) — that's "retry everything", which retries your TypeErrors and KeyErrors forever. The right shape for HTTP work is a classifier that inspects the exception and answers "was this about timing?":

python
# errors.py — classify an httpx error into retryable vs permanent (illustrative:
# needs httpx; the real classifier for LLM SDKs is 03.8 §4.4)
import httpx

# 409 is included: most APIs use it for transient state conflicts — but some
# APIs use it for permanent duplicates; drop it from the set if yours does (§1.1).
RETRYABLE_STATUSES = {408, 409, 425, 429, 500, 502, 503, 504}
TRANSIENT_ERRORS = (
    httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout,
    httpx.WriteTimeout, httpx.PoolTimeout, httpx.RemoteProtocolError,
    httpx.ReadError, httpx.WriteError,
)

def is_transient(exc: BaseException) -> bool:
    """True only for failures a retry could plausibly fix."""
    if isinstance(exc, httpx.HTTPStatusError):
        return exc.response.status_code in RETRYABLE_STATUSES
    if isinstance(exc, httpx.HTTPError):
        return isinstance(exc, TRANSIENT_ERRORS)   # transport-level: no response
    return isinstance(exc, (TimeoutError, ConnectionError))

Then retry=retry_if_exception(is_transient) retries timeouts and 5xx/429 but lets a 400 or your own TypeError escape on the first attempt — exactly the 1.1 taxonomy as code.

5.5 reraise, RetryError and the callback#

When retries run out, tenacity's default is to raise tenacity.RetryError — a wrapper that contains the last exception but isn't the exception itself. That breaks except httpx.HTTPStatusError downstream, because the real error is buried inside the wrapper. The fix is reraise=True, which re-raises the original last exception:

python
from tenacity import retry, stop_after_attempt, wait_fixed, retry_if_exception_type

@retry(retry=retry_if_exception_type(TransientError),
       wait=wait_fixed(1), stop=stop_after_attempt(3),
       reraise=True)                       # raise the TransientError, not RetryError
async def fetch():
    ...

retry_error_callback is the alternative: instead of raising, it returns a value — useful for "give up and return a fallback" patterns:

python
from tenacity import retry, stop_after_attempt     # retry_error_callback is a keyword of @retry, not an import

def fallback(retry_state):
    return {"status": "unavailable", "attempts": retry_state.attempt_number}

@retry(stop=stop_after_attempt(3), retry_error_callback=fallback)
def get_status():
    ...   # returns the dict above instead of raising when retries run out

5.6 Async: @retry just works on async def#

Tenacity detects coroutine functions and uses AsyncRetrying automatically — the same decorator works for sync and async:

python
import logging

from tenacity import (
    before_sleep_log, retry, retry_if_exception, stop_after_attempt,
    stop_before_delay, wait_random_exponential,
)

# is_transient is the classifier from 5.4

log = logging.getLogger("app.http")

@retry(
    retry=retry_if_exception(is_transient),
    wait=wait_random_exponential(multiplier=0.5, max=8),
    stop=stop_after_attempt(4) | stop_before_delay(20),
    before_sleep=before_sleep_log(log, logging.WARNING),
    reraise=True,
)
async def post_with_retry(client, url, payload):
    resp = await client.post(url, json=payload)
    resp.raise_for_status()
    return resp.json()

For the non-decorator form — when you want the policy as a value you can pass around or compose — AsyncRetrying works as an async context manager or async for loop:

python
from tenacity import AsyncRetrying, stop_after_attempt, wait_fixed

async def call_with_policy(client, url, payload, policy: AsyncRetrying):
    async for attempt in policy:
        with attempt:
            resp = await client.post(url, json=payload)
            resp.raise_for_status()
            return resp.json()

5.7 Statistics, retry_with, TryAgain and the context manager#

A decorated function carries useful attributes:

python
@retry(stop=stop_after_attempt(3), reraise=True)
def flaky():
    ...

try:
    flaky()
except Exception:
    pass

flaky.statistics          # {'start_time': ..., 'attempt_number': 3, 'idle_for': ...}
flaky.retry               # the Retrying object — inspect .stop, .wait, .retry
flaky.retry_with(stop=stop_after_attempt(10))   # a NEW decorated fn, same fn, new policy
  • f.statistics — a dict with attempt_number, idle_for (total time slept), start_time. Useful for logging "this call took 4 attempts and 6.2 s of backoff".
  • f.retry_with(...) — re-wrap the same function with different parameters, without redefining it. (It's a method on the decorated function, not a standalone import.)
  • TryAgain — raise tenacity.TryAgain inside a retried function to force a retry regardless of the predicate — an escape hatch for "the call returned 200 but the body says try later".
  • before / after / before_sleep — the attempt hooks. before runs before every attempt; after runs after each failed attempt the retry predicate accepted — it fires before the stop check, so it also runs on the attempt that turns out to be the last; before_sleep runs only when a retry is genuinely about to sleep, which is why before_sleep_log (the logging-ready version) is the right place for "retrying in X s" lines.
  • Retrying for one-off use — Retrying(...)(fn, *args) runs the whole retry loop and returns the result, and for attempt in Retrying(...): with attempt: gives you the per-attempt protocol inline (the same shape as async for with AsyncRetrying, 5.6). There is no .call() method and Retrying itself isn't a context manager — the with belongs to each yielded attempt.

5.8 Testing retry code without waiting#

Tenacity is built to be tested: Retrying accepts a sleep callable you can replace, and wait_none() makes waits instant:

python
# tests/test_retry.py — illustrative: needs tenacity + pytest
import pytest
from tenacity import Retrying, stop_after_attempt, wait_none, retry_if_exception_type

class FlakyError(Exception): pass

def test_retries_until_success():
    calls = {"n": 0}
    def fn():
        calls["n"] += 1
        if calls["n"] < 3:
            raise FlakyError("boom")
        return "ok"
    policy = Retrying(retry=retry_if_exception_type(FlakyError),
                      stop=stop_after_attempt(5), wait=wait_none())
    assert policy(fn) == "ok"
    assert calls["n"] == 3

def test_gives_up_after_n():
    policy = Retrying(retry=retry_if_exception_type(FlakyError),
                      stop=stop_after_attempt(3), wait=wait_none(), reraise=True)
    with pytest.raises(FlakyError):
        policy(lambda: (_ for _ in ()).throw(FlakyError("always")))

The pattern that matters: inject sleep or use wait_none, and a "retries 3 times with backoff" test runs in microseconds with zero real waiting — the same trick as the FakeClock in 4.5, now as a library feature.

5.9 Common mistakes#

Mistake What happens Fix
@retry bare Retries forever on any exception, no wait Always set stop, wait, retry, reraise
retry_if_exception_type(Exception) Retries your own bugs Use a classifier (retry_if_exception(is_transient))
No reraise=True Callers see RetryError, not the real error Always reraise=True unless you want the wrapper
Retrying inside a retrying SDK max_retries=2 SDK × your 4 attempts = 12 calls Turn the SDK's retries off; one layer owns them (03.8 §5.5)
wait_exponential without jitter Synchronized retry storms wait_random_exponential
Retrying non-idempotent POSTs Duplicate side effects Idempotency keys / dedupe (Part 3)
No deadline attempts × (timeout + max_wait) can exceed caller patience stop_before_delay or a shared Deadline (2.4)
Retrying streaming bodies Replays the start of an answer the user saw Explicit restart logic (03.3 §7.4)

5.10 Hand-rolled vs tenacity vs SDK retries#

Situation Use
A script, a prototype, one flaky call The SDK's built-in retries (if any) — simplest
You need classification, a deadline, Retry-After, logging, one policy for many calls tenacity with a classifier — the production default
You need to understand the mechanism, or can't add a dependency The hand-rolled retry()/retry_async() from 4.4 — ~40 lines, fully yours
Only connection-setup failures (refused, connect timeout) httpx.HTTPTransport(retries=N) — it retries while the connection is being established, never on a status code and never after the request was sent, so it complements but does not replace a policy (01B.5)
Streaming responses Neither — explicit restart/continue/resume (03.3 §7.5)
A whole provider is down Retries alone won't help — you need a circuit breaker and fallbacks

Part 6: Beyond retries — the resilience toolbox#

Deep-dive

Retries answer "this one call failed, try again". But some failures aren't about one call — a whole provider is down, your own connection pool is exhausted, or the dependency will be slow for the next ten minutes. For those you need the rest of the toolbox. Each pattern below is a sketch you can run; 11C.3 builds the production versions for LLM services.

6.1 Circuit breakers#

A circuit breaker is a switch that stops you from calling a service you already know is failing. The name comes from electrical panels: when too much current flows, the breaker trips and cuts power before the wiring melts — then it resets after a cooldown.

The software version has three states:

stateDiagram-v2
    [*] --> closed: start
    closed --> open: failures ≥ threshold
    open --> half_open: cooldown elapsed
    half_open --> closed: probe succeeds
    half_open --> open: probe fails
    open --> open: calls fail fast (no provider call)
  • Closed — normal operation; every call goes through, and consecutive failures are counted.
  • Open — after failure_threshold consecutive failures, the breaker "trips": calls fail immediately with CircuitOpenError without touching the provider. This is the whole point — while the provider is down, you stop feeding it requests and stop waiting on timeouts.
  • Half-open — after reset_timeout seconds, one probe call is let through. Success → closed (reset the count). Failure → open again (reset the timer). Only one probe at a time, so a still-sick provider doesn't get a wave.

Here's the hand-rolled version — the same CircuitBreaker that's in mini_resilience.py, stdlib only, clock injectable. This is part 2 of that file: append it to the listing from 4.4 (it reuses that file's imports, T and TransientError):

python
# mini_resilience.py — part 2: the circuit breaker (stdlib only)
class CircuitOpenError(Exception):
    """Raised instead of calling the service while the circuit is open."""


class CircuitBreaker:
    """Closed -> open -> half-open -> closed.

    Counts *consecutive* failures. After `failure_threshold` the breaker opens
    and calls fail fast with CircuitOpenError. After `reset_timeout` seconds
    one probe is let through (half-open): success closes it, failure reopens.
    `clock` is injectable so demos and tests never really wait."""

    CLOSED, OPEN, HALF_OPEN = "closed", "open", "half_open"

    def __init__(
        self,
        *,
        failure_threshold: int = 3,
        reset_timeout: float = 30.0,
        clock: Callable[[], float] = time.monotonic,
        on_state_change: Callable[[str, str], None] | None = None,
    ) -> None:
        # A NaN timeout compares False with everything, so an opened breaker would
        # never half-open; a threshold below 1 would open on the first success.
        if (isinstance(failure_threshold, bool) or not isinstance(failure_threshold, int)
                or failure_threshold < 1 or not 0 <= reset_timeout < float("inf")):
            raise ValueError("failure_threshold must be an int >= 1 and "
                             "reset_timeout a finite number >= 0")
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self._clock = clock
        self._on_state_change = on_state_change
        self._state = self.CLOSED
        self._failures = 0
        self._opened_at = 0.0
        self._probing = False

    @property
    def state(self) -> str:
        # Reading .state can itself transition open -> half_open: observation
        # mutates. Safe under asyncio (_before_call sets _probing before any
        # await); racy if one breaker is shared across threads.
        if self._state == self.OPEN and self._clock() - self._opened_at >= self.reset_timeout:
            self._transition(self.HALF_OPEN)
        return self._state

    def _transition(self, new: str) -> None:
        old = self._state
        self._state = new
        if self._on_state_change:
            try:
                self._on_state_change(old, new)
            except Exception:    # a broken observer must not mask the call's own result
                logging.getLogger(__name__).exception("on_state_change callback failed")

    def _before_call(self) -> None:
        if self.state == self.OPEN:
            raise CircuitOpenError("circuit open: failing fast")
        if self.state == self.HALF_OPEN:
            if self._probing:
                raise CircuitOpenError("circuit half-open: probe in flight")
            self._probing = True

    def _after_success(self) -> None:
        self._failures = 0
        self._probing = False
        if self._state == self.HALF_OPEN:
            self._transition(self.CLOSED)

    def _after_failure(self) -> None:
        self._probing = False
        self._failures += 1
        if self._state == self.HALF_OPEN or self._failures >= self.failure_threshold:
            self._opened_at = self._clock()
            self._transition(self.OPEN)

    def call(self, fn: Callable[[], T]) -> T:
        """Run fn() through the breaker (sync)."""
        self._before_call()
        try:
            result = fn()
        except Exception:
            self._after_failure()
            raise
        except BaseException:      # KeyboardInterrupt, SystemExit: release a half-open probe
            self._probing = False
            raise
        self._after_success()
        return result

    async def acall(self, fn: Callable[[], Any], *args: Any, **kwargs: Any) -> T:
        """Run an async fn() through the breaker."""
        self._before_call()
        try:
            result = await fn(*args, **kwargs)
        except asyncio.CancelledError:
            # An outer deadline (6.7) can cancel a call mid-flight. That is not a
            # verdict on the dependency, but it must release a half-open probe slot
            # or every later call would be refused as "probe in flight".
            self._probing = False
            raise
        except Exception:
            self._after_failure()
            raise
        self._after_success()
        return result

Run it — a provider that fails while down, a fake clock, and the full lifecycle:

python
# demo_breaker.py — CircuitBreaker with a fake clock (stdlib only)
from mini_resilience import CircuitBreaker, CircuitOpenError, TransientError

class FakeClock:
    def __init__(self): self.t = 0.0
    def __call__(self): return self.t
    def advance(self, s): self.t += s

clock = FakeClock()
transitions = []
breaker = CircuitBreaker(failure_threshold=3, reset_timeout=10.0,
                         clock=clock,
                         on_state_change=lambda o, n: transitions.append(f"{o}->{n}"))
service = {"down": True, "calls": 0}
def call_provider():
    service["calls"] += 1
    if service["down"]:
        raise TransientError("provider: 503 overloaded")
    return "answer"
def attempt(label):
    try:
        out = breaker.call(call_provider)
        print(f"{label:<34} -> {out!r}   (breaker={breaker.state})")
    except CircuitOpenError as e:
        print(f"{label:<34} -> CircuitOpenError   (breaker={breaker.state})")
    except TransientError as e:
        print(f"{label:<34} -> TransientError   (breaker={breaker.state})")

for i in range(1, 6): attempt(f"call {i}")          # trips after 3 failures
clock.advance(10.0); attempt("call 6 (half-open)")   # probe: still down -> reopen
service["down"] = False
clock.advance(10.0); attempt("call 7 (half-open)")   # probe: recovered -> close
attempt("call 8 (closed)")
print("transitions:", transitions)
print("provider calls:", service["calls"])
Output10 lines
call 1                             -> TransientError   (breaker=closed)
call 2                             -> TransientError   (breaker=closed)
call 3                             -> TransientError   (breaker=open)
call 4                             -> CircuitOpenError   (breaker=open)
call 5                             -> CircuitOpenError   (breaker=open)
call 6 (half-open)                 -> TransientError   (breaker=open)
call 7 (half-open)                 -> 'answer'   (breaker=closed)
call 8 (closed)                    -> 'answer'   (breaker=closed)
transitions: ['closed->open', 'open->half_open', 'half_open->open', 'open->half_open', 'half_open->closed']
provider calls: 6

The money shot is calls 4 and 5: while the provider is down, the breaker fails them instantly — no timeout wait, no provider call, no load on a service that can't serve you. That's the difference between "retry a failing call" and "stop calling a failing service".

Misuse tests. The demo shows a well-behaved breaker. These three tests hold fixes for misuse: a breaker built with settings that can never work (a NaN reset timeout compares false with everything, so an opened breaker would never half-open), a metrics callback that raises (it used to replace the real error from the failing call, and could lose a successful result), and a half-open probe interrupted by KeyboardInterrupt (it kept the probe slot, so every later call was refused as "probe in flight"). Save as test_breaker_attacks.py beside mini_resilience.py:

python
# test_breaker_attacks.py — misuse of CircuitBreaker (stdlib only).
# Run beside mini_resilience.py: python3 -m unittest test_breaker_attacks -v
import unittest

from mini_resilience import CircuitBreaker


class BreakerAttackTests(unittest.TestCase):
    def test_settings_that_could_never_work_are_refused(self):
        for bad in ({"failure_threshold": 0}, {"failure_threshold": True},
                    {"reset_timeout": float("nan")}, {"reset_timeout": -1}):
            with self.assertRaises(ValueError):
                CircuitBreaker(**bad)

    def test_a_broken_observer_does_not_replace_the_real_error(self):
        def broken(old, new):
            raise RuntimeError("the metrics client is down")
        breaker = CircuitBreaker(failure_threshold=1, on_state_change=broken)
        with self.assertLogs("mini_resilience", level="ERROR"):   # the failure is logged
            with self.assertRaises(ZeroDivisionError):            # not RuntimeError
                breaker.call(lambda: 1 / 0)

    def test_an_interrupted_probe_releases_the_probe_slot(self):
        now = [0.0]
        breaker = CircuitBreaker(failure_threshold=1, reset_timeout=1, clock=lambda: now[0])
        with self.assertRaises(ZeroDivisionError):
            breaker.call(lambda: 1 / 0)                 # opens the circuit
        now[0] = 2                                      # half-open: one probe allowed

        def interrupted():
            raise KeyboardInterrupt
        with self.assertRaises(KeyboardInterrupt):
            breaker.call(interrupted)
        self.assertEqual(breaker.call(lambda: "ok"), "ok")   # the next probe is allowed


if __name__ == "__main__":
    unittest.main()

Run python3 -m unittest test_breaker_attacks -v and you get real output:

text
test_a_broken_observer_does_not_replace_the_real_error ... ok
test_an_interrupted_probe_releases_the_probe_slot ... ok
test_settings_that_could_never_work_are_refused ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

Still true of this breaker: it is not thread-safe (use one per event loop, or add a lock), and a half-open probe that never returns holds the slot until your call-level timeout cancels it, so always wrap the call in a timeout (Part 2).

6.2 Bulkheads#

A bulkhead isolates failure so one sick dependency can't sink the ship — named after the watertight compartments in a ship's hull. In software: separate connection pools, separate concurrency limits, separate queues per downstream. If the embeddings API is slow, your chat completions keep working because they have their own pool and their own semaphore.

The mechanism is usually just "don't share the limiter": 01B.4 taught asyncio.Semaphore and asyncio.Queue for bounding concurrency — a bulkhead is the same tool applied per dependency instead of globally. 11C.3 §4 shows bounded per-key concurrency in production code.

6.3 Rate limiting and throttling#

Distinct from retries: a rate limiter prevents you from causing the 429 in the first place by pacing requests under the provider's limit (token bucket, sliding window — both built from scratch in 01B.4 §4). The relationship: the limiter keeps you under the limit so retries are rare; retries handle the residual failures the limiter couldn't predict (a sudden provider-side slowdown). You need both — a limiter can't help when the server is the bottleneck.

6.4 Load shedding#

Load shedding is the deliberate decision to refuse work when you're saturated, rather than accept it and fail slowly. A queue that's full returns 503/429 immediately instead of letting requests pile up until every timeout fires. It's the difference between "we're busy, try later" and "we accepted your request and will get to it in 40 seconds" — the second is worse for everyone. API gateways do this automatically; in your own service it's a bounded queue plus a fast-fail when queue.full() (11C.3 §4.2).

6.5 Fallbacks and graceful degradation#

A fallback is what you do when the primary path fails after retries and the breaker has tripped: serve something lesser rather than nothing. The degradation ladder for an LLM feature, simplest to most degraded:

  1. Primary model/provider
  2. Fallback model or provider (11C.3 §6)
  3. A cached or simpler answer (a template, a "let me get back to you" response, a smaller model)
  4. A clear error to the user

6.6 Hedged requests#

A hedged request sends the same request to two providers (or twice to one) after a delay, and uses whichever answers first — cancelling the loser. It cuts tail latency (the "one slow request in twenty" problem from The Tail at Scale, Dean & Barroso 2013). The catch is obvious: you pay for both, and for LLM calls you may get two different answers — which one is "the" answer? Use it for latency-critical, cheap, idempotent reads; think twice before hedging a billed generation. 11C.3 covers when it's worth it in production.

6.7 Composition order: who wraps whom#

The patterns nest, and the order matters:

Layer (outermost → innermost) Job Why this order
Deadline Total budget for the whole operation Outermost — everything below shares it
Fallback chain Try route B when route A is out Above the per-route guards — it decides which route to try, and each route has its own breaker, limiter and retry policy
Circuit breaker (one per route) Stop calling a dead dependency Outside the retries — when it is open, don't even start retrying
Retry + backoff Retry transient failures of one call Inside the breaker — the per-call mechanism. The breaker sees one outcome per logical call (after retries are exhausted), so a persistent outage still trips it within a few calls
Rate limiter Pace requests under the limit Inside the retry loop, so every attempt (first try or retry) takes a token and retries cannot burst past the limit
Timeout Bound each individual attempt Innermost of all — every socket wait is capped

The rule of thumb: the cheaper and more local the guard, the further in. A timeout is per-socket (innermost); a deadline is per-request (outermost); a breaker is per-dependency (middle). Get the order wrong — retries outside the breaker — and every retry counts as a separate call through it, so one logical request can trip the breaker by itself and keeps knocking on a door the breaker is trying to keep shut; timeouts outside the deadline and each attempt gets a fresh budget. (Orders differ between libraries and teams. What must hold: the deadline is outermost, the timeout innermost, and CircuitOpenError is never retried — is_transient in Part 8 already answers "no" for it, because it is neither a TimeoutError nor a ConnectionError.)

6.8 Retry budgets#

A retry budget caps the total retry work a system may do, independent of per-call limits. If your service makes 1,000 calls/min and each may retry 4×, you could generate 4,000 requests/min of pure retry traffic during an outage — a self-inflicted DDoS. The budget says "at most X% of my capacity may be retries" or "at most Y retries per minute globally"; when it's exhausted, calls fail fast instead of retrying. 03.8 §7.4 works the numbers for LLM calls; the concept is generic — retries are load too.

6.9 Partial failure in batches#

When you process a batch (10,000 embeddings, 5,000 classifications), a failure in one item shouldn't sink the run — and a retry of the batch shouldn't redo the successes. The pattern:

  1. Process items independently; collect each outcome as success or failure.
  2. Retry only the failed items, with backoff — never the whole batch.
  3. After the retry budget, write failures to a dead-letter list/file for inspection or replay — don't drop them silently.
python
# The shape: per-item outcome collection + selective retry (illustrative)
results, failures = [], []
for item in batch:
    try:
        results.append(process(item))
    except TransientError as e:
        failures.append((item, e))
# retry only `failures`, not the whole batch — then dead-letter what's left

05.9 §1.4 applies exactly this "fail-soft per document" to ingestion pipelines, and 01B.4 built the Result type for collecting successes and failures concurrently.


Part 7: What changes for LLM APIs — and how to watch it all#

7.1 What changes for LLM APIs#

Everything in Parts 1–6 is generic HTTP-client discipline; it applies to LLM calls unchanged. What does change is the failure surface, and Module 03 owns the details — this is the map, not the territory:

Generic mechanism What LLM APIs add Where it's covered
Transient vs permanent Provider-specific error codes decide the bucket: a 429 can mean "slow down" or "out of credits", Anthropic's overload is 529 not 503, billing errors arrive as 429/402 03.8 §4
Timeouts Non-streaming generations legitimately take 30–120 s; "timeouts that still bill" — the server may finish and charge after you give up 03.8 §6
Idempotency None of the four providers offers idempotency keys for inference; a retried generation bills twice and can repeat tool side effects — you build your own dedupe 03.8 §11
Backoff / Retry-After Provider hints differ: retry-after-ms, Gemini's RetryInfo in the body, x-should-retry headers 03.8 §7
SDK retries openai/anthropic/google-genai retry by default with their own counts and formulas — the double-retry trap means one layer owns retries 03.8 §5
tenacity The provider-aware classifier + policy that wraps all four SDKs 03.8 §8
Rate limits Per-model RPM/TPM tiers, x-ratelimit-* headers, shared-account limits 03.8 §9, 03.9 §5
Circuit breaker / fallback Per-provider and per-model-key breakers, degradation ladders, gateways 11C.3
Streaming Retries can't replay a stream the user already saw — restart/continue/resume is explicit 03.3 §7

Three LLM-specific wrinkles worth internalising now:

  • Retries cost tokens. A retried generation may have already consumed input tokens (and produced partial output you discard). Retry budgets matter more when each attempt has a price tag — 03.8 §7.4 works the arithmetic.
  • Non-determinism. Even a "successful" retry can return a different answer — for classification/extraction that's usually fine, for anything where consistency matters it's a subtle hazard.
  • Side effects via tools. A retried call can re-emit a tool call that sends an email or issues a refund — the dedupe-key pattern from 3.4 is what makes agent retries safe (03.8 §11.3).

7.2 Observability of resilience#

Resilience mechanisms are invisible when they work — which is exactly why you must log them. The rules:

  • Log every retry with the attempt number, the reason (exception type + status, never secrets), and the scheduled delay. before_sleep_log in tenacity does this for you; your hand-rolled on_retry callback is the same seam.
  • Never log secrets. A retry log that includes the request headers can leak the API key — log method, URL path, status and error type, not bodies or auth headers (01B.2 owns secret hygiene; 03.10 shows redacted HTTP logging).
  • Count retries as metrics. A retry counter per dependency (retry_count{service="openai"}) is the earliest warning that a provider is degrading — 11A.2 §1 covers the metrics that matter, including retry rates.
  • Alert on retry-rate anomalies, not individual retries. One retry is normal; a service whose retry rate jumps from 1 % to 40 % is having an incident — that's an alert, not a log line.
  • Circuit-breaker transitions are events. Log closed→open and open→half_open loudly — they're the moments your system changed behaviour.

Part 8: The aitoolkit/resilience.py deliverable#

This is the production version of everything in Parts 4–6, as a module you drop into the aitoolkit project from 01B.1. It needs tenacity and httpx (checked against 9.1.4 and 0.28.1). It is illustrative: the tenacity calls match the 9.1.4 source (checked 11 November 2026), but the module was not run end to end here, so run it inside your project where the dependencies exist.

python
# src/aitoolkit/resilience.py — retries, deadlines and a circuit breaker for aitoolkit.
# Used by http.py (the configured client) and service.py (the FastAPI app).
import asyncio
import logging
import random
import time
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, TypeVar

import httpx
from tenacity import (AsyncRetrying, RetryCallState, before_sleep_log, retry,
                      retry_if_exception, stop_after_attempt, stop_before_delay,
                      wait_random_exponential)
from tenacity.wait import wait_base

log = logging.getLogger("aitoolkit.resilience")
T = TypeVar("T")

# --------------------------------------------------------------------------
# Classification: which failures are worth another attempt?
# --------------------------------------------------------------------------

# 409 is included: most APIs use it for transient state conflicts — but some
# APIs use it for permanent duplicates; drop it from the set if yours does (§1.1).
RETRYABLE_STATUSES = {408, 409, 425, 429, 500, 502, 503, 504}
TRANSIENT_TRANSPORT = (
    httpx.ConnectError, httpx.ConnectTimeout, httpx.ReadTimeout,
    httpx.WriteTimeout, httpx.PoolTimeout, httpx.RemoteProtocolError,
    httpx.ReadError, httpx.WriteError,
)


def is_transient(exc: BaseException) -> bool:
    """True only for failures a retry could plausibly fix.

    - HTTPStatusError: retry only the transient status codes (4xx client errors
      like 400/401/404 are permanent — a retry fails identically).
    - Other httpx errors: transport-level (no response arrived) — transient.
    - Built-in TimeoutError/ConnectionError: same, for non-httpx callables.
    """
    if isinstance(exc, httpx.HTTPStatusError):
        return exc.response.status_code in RETRYABLE_STATUSES
    if isinstance(exc, httpx.HTTPError):
        return isinstance(exc, TRANSIENT_TRANSPORT)
    return isinstance(exc, (TimeoutError, ConnectionError))


# --------------------------------------------------------------------------
# Retry policy: tenacity, configured once, shared everywhere
# --------------------------------------------------------------------------

class wait_retry_after(wait_base):
    """Wait what the server asked for (Retry-After), else full-jitter backoff."""
    def __init__(self, fallback: wait_base) -> None:
        self.fallback = fallback

    def __call__(self, retry_state: RetryCallState) -> float:
        exc = retry_state.outcome.exception() if retry_state.outcome else None
        hint = _retry_after_hint(exc)
        if hint is not None and hint <= 60:               # cap absurd hints
            return hint + random.uniform(0, 0.25)          # "a minimum": add jitter
        return self.fallback(retry_state)


def _retry_after_hint(exc: BaseException | None) -> float | None:
    """Seconds from a Retry-After header on an httpx error response, if any."""
    if exc is None:
        return None
    response = getattr(exc, "response", None)
    if response is None:
        return None
    from .retry_after import parse_retry_after       # the Part 4 parser
    return parse_retry_after(response.headers.get("retry-after"))


def _policy(**overrides: Any) -> dict[str, Any]:
    policy: dict[str, Any] = dict(
        retry=retry_if_exception(is_transient),
        wait=wait_retry_after(wait_random_exponential(multiplier=0.5, max=8)),
        stop=stop_after_attempt(4) | stop_before_delay(30),
        before_sleep=before_sleep_log(log, logging.WARNING),
        reraise=True,                                   # raise the real error
    )
    policy.update(overrides)
    return policy


def retry_async(**overrides: Any):
    """@retry_async() on an `async def` — tenacity's @retry, pre-configured.

    Usage:
        @retry_async()
        async def fetch(client, url):
            resp = await client.get(url)
            resp.raise_for_status()
            return resp.json()
    """
    return retry(**_policy(**overrides))


async def call_with_retry(fn: Callable[..., Awaitable[T]], *args: Any,
                          policy: AsyncRetrying | None = None, **kwargs: Any) -> T:
    """Call an async fn under the shared policy — for callers that can't use
    the decorator (e.g. a function chosen at runtime)."""
    policy = policy or AsyncRetrying(**_policy())
    async for attempt in policy:
        with attempt:
            return await fn(*args, **kwargs)
    raise AssertionError("unreachable")


# --------------------------------------------------------------------------
# Deadline: a total budget shared across retries and sub-calls
# --------------------------------------------------------------------------

@dataclass
class Deadline:
    """A monotonic-clock budget. `remaining()` shrinks as time passes;
    `timeout()` gives an asyncio.timeout for whatever is left."""
    seconds: float
    _end: float = 0.0

    def __post_init__(self) -> None:
        self._end = time.monotonic() + self.seconds

    def remaining(self) -> float:
        return max(0.0, self._end - time.monotonic())

    @property
    def expired(self) -> bool:
        return self.remaining() <= 0

    def timeout(self):
        return asyncio.timeout(self.remaining())


# --------------------------------------------------------------------------
# CircuitBreaker: stop calling a dependency that's down
# --------------------------------------------------------------------------

class CircuitOpenError(Exception):
    """Raised instead of calling the service while the circuit is open."""


class CircuitBreaker:
    """Closed -> open -> half-open -> closed (the Part 6 state machine).

    Async-first (`acall`); `call` covers sync fns. `clock` is injectable so
    tests never really wait. For per-key breakers and sliding-window failure
    rates, see Module 11C's resilience layer.
    """

    CLOSED, OPEN, HALF_OPEN = "closed", "open", "half_open"

    def __init__(
        self,
        *,
        failure_threshold: int = 5,
        reset_timeout: float = 30.0,
        clock: Callable[[], float] = time.monotonic,
        on_state_change: Callable[[str, str], None] | None = None,
    ) -> None:
        # A NaN timeout compares False with everything, so an opened breaker would
        # never half-open; a threshold below 1 would open on the first success.
        if (isinstance(failure_threshold, bool) or not isinstance(failure_threshold, int)
                or failure_threshold < 1 or not 0 <= reset_timeout < float("inf")):
            raise ValueError("failure_threshold must be an int >= 1 and "
                             "reset_timeout a finite number >= 0")
        self.failure_threshold = failure_threshold
        self.reset_timeout = reset_timeout
        self._clock = clock
        self._on_state_change = on_state_change
        self._state = self.CLOSED
        self._failures = 0
        self._opened_at = 0.0
        self._probing = False

    @property
    def state(self) -> str:
        # Reading .state can itself transition open -> half_open: observation
        # mutates. Safe under asyncio (_before_call sets _probing before any
        # await); racy if one breaker is shared across threads.
        if self._state == self.OPEN and self._clock() - self._opened_at >= self.reset_timeout:
            self._transition(self.HALF_OPEN)
        return self._state

    def _transition(self, new: str) -> None:
        old = self._state
        self._state = new
        log.warning("circuit %s -> %s", old, new)
        if self._on_state_change:
            try:
                self._on_state_change(old, new)
            except Exception:    # a broken observer must not mask the call's own result
                logging.getLogger(__name__).exception("on_state_change callback failed")

    def _before_call(self) -> None:
        if self.state == self.OPEN:
            raise CircuitOpenError("circuit open: failing fast")
        if self.state == self.HALF_OPEN:
            if self._probing:
                raise CircuitOpenError("circuit half-open: probe in flight")
            self._probing = True

    def _after_success(self) -> None:
        self._failures = 0
        self._probing = False
        if self._state == self.HALF_OPEN:
            self._transition(self.CLOSED)

    def _after_failure(self) -> None:
        self._probing = False
        self._failures += 1
        if self._state == self.HALF_OPEN or self._failures >= self.failure_threshold:
            self._opened_at = self._clock()
            self._transition(self.OPEN)

    async def acall(self, fn: Callable[..., Awaitable[T]], *args: Any, **kwargs: Any) -> T:
        self._before_call()
        try:
            result = await fn(*args, **kwargs)
        except asyncio.CancelledError:
            # An outer deadline (6.7) can cancel a call mid-flight. That is not a
            # verdict on the dependency, but it must release a half-open probe slot
            # or every later call would be refused as "probe in flight".
            self._probing = False
            raise
        except Exception:
            self._after_failure()
            raise
        self._after_success()
        return result

    def call(self, fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
        self._before_call()
        try:
            result = fn(*args, **kwargs)
        except Exception:
            self._after_failure()
            raise
        except BaseException:      # KeyboardInterrupt, SystemExit: release a half-open probe
            self._probing = False
            raise
        self._after_success()
        return result

It also needs the parse_retry_after helper from 4.3 as aitoolkit/retry_after.py — copy it verbatim. One naming note: despite the shared name, this retry_async is a tenacity-backed decorator factory — @retry_async() or retry_async(...)(fn) — not the hand-rolled direct-call function from 4.4. For calling an already-chosen async function directly, use call_with_retry above. Lesson 01B.8's tests/test_resilience.py exercises exactly this API. The tests for all three live in tests/test_resilience.py and use the same fake-clock and flaky-fake tricks as 4.5 and 01B.8: a FlakyBackend that fails N times then succeeds, a FakeClock for the breaker, and wait_none()-style instant waits where tenacity allows. The shape:

python
# tests/test_resilience.py — illustrative: needs pytest + tenacity + httpx
import pytest
from tenacity import wait_none

from aitoolkit.resilience import CircuitBreaker, CircuitOpenError, retry_async

class FlakyBackend:
    """A fake that raises TransientError N times, then returns 'ok'."""
    def __init__(self, failures: int):
        self.failures = failures
        self.calls = 0
    async def __call__(self):
        self.calls += 1
        if self.calls <= self.failures:
            raise TimeoutError("simulated timeout")
        return "ok"

@pytest.mark.asyncio
async def test_retry_async_recovers():
    backend = FlakyBackend(failures=2)
    result = await retry_async(wait=wait_none())(backend)()  # instant waits for the test
    assert result == "ok" and backend.calls == 3

@pytest.mark.asyncio
async def test_circuit_opens_and_fails_fast():
    breaker = CircuitBreaker(failure_threshold=2, reset_timeout=30.0)
    dead = FlakyBackend(failures=99)
    for _ in range(2):
        with pytest.raises(TimeoutError):
            await breaker.acall(dead)
    with pytest.raises(CircuitOpenError):
        await breaker.acall(dead)          # fails fast — dead.calls doesn't grow
    assert dead.calls == 2

The failures this lesson exists to prevent, as symptom → cause → fix:

Symptom Cause Fix
tenacity.RetryError[<Future ... raised HTTPStatusError>] instead of the real error reraise not set — tenacity wraps the last failure reraise=True (5.5)
The same HTTPStatusError: 400 logged over and over, then gave up A permanent error inside the retry predicate Classify first: retry_if_exception(is_transient) (5.4)
Attempts forever with zero delay — the job never ends Bare @retry defaults to stop_never + wait_none + retry-anything Always set stop, wait, retry, reraise (5.1)
Retry spikes at identical instants; the recovering server falls over again Exponential backoff without jitter — synchronised clients wait_random_exponential / full jitter (4.2)
Customer charged twice, or two confirmation emails, after one timeout A retried non-idempotent POST; the first attempt may have completed Idempotency key or your own dedupe (3.3, 3.4)
The caller gave up at 30 s but the work ran for 2 minutes attempts × (timeout + max_wait) with no total budget A shared Deadline / stop_before_delay (2.4)
httpx.PoolTimeout bursts while the server is healthy Concurrency exceeds max_connections — your own queue Lower the concurrency limit, not a bigger timeout (2.2)
CircuitOpenError: circuit open: failing fast during an outage The breaker doing its job — calls fail instantly instead of timing out Working as intended; tune failure_threshold/reset_timeout (6.1)
A request that simply never returns No timeout anywhere on the call httpx.Timeout per request + asyncio.timeout for the total (2.2, 2.3)

Four of them as the errors typically surface (reconstructed from the documented exception types and their str() formats, so file names, line numbers and exact wording will differ in your project):

RetryError — the wrapper hiding the real exception:

Example output · illustrative6 lines
Traceback (most recent call last):
  File "sync.py", line 42, in <module>
    tickets = await fetch_all()
  File "client.py", line 88, in fetch_all
    return await post_with_retry(client, url, payload)
tenacity.RetryError[<Future at 0x7f2c1a3b4e50 state=finished raised httpx.HTTPStatusError>]

The real HTTPStatusError is inside the Future — except httpx.HTTPStatusError downstream won't catch this. reraise=True fixes it.

TimeoutError — asyncio.timeout firing at the deadline:

Example output · illustrative7 lines
Traceback (most recent call last):
  File "report.py", line 17, in <module>
    asyncio.run(build_report())
  File "report.py", line 31, in build_report
    async with deadline.timeout():
  ...
TimeoutError

This is the deadline doing its job — but remember the awaited call was cancelled, and work already sent may still complete server-side (2.5).

CircuitOpenError — the breaker failing fast:

Example output · illustrative8 lines
Traceback (most recent call last):
  File "worker.py", line 55, in process_one
    answer = await breaker.acall(call_provider)
  File "mini_resilience.py", line 143, in acall
    self._before_call()
  File "mini_resilience.py", line 135, in _before_call
    raise CircuitOpenError("circuit open: failing fast")
mini_resilience.CircuitOpenError: circuit open: failing fast

Not a bug — the provider is down and the breaker is refusing to feed it. Make sure the retry policy never retries it (is_transient already answers no) and catch it above the retry layer, where you can serve a fallback or a clear "try later" message.

httpx.PoolTimeout — your own concurrency queue:

Example output · illustrative4 lines
Traceback (most recent call last):
  File "fanout.py", line 28, in <module>
    asyncio.run(main())
httpx.PoolTimeout: timed out

All max_connections were busy and the request waited past the pool timeout — the fix is a smaller concurrency limit (01B.4), not retries.


Common misconceptions#

Misconception Reality
"Retries are always safe — just try again" Only transient failures are safe to retry; permanent ones fail identically and waste time and money (1.1)
"A timeout means the request failed" A timeout means you stopped waiting — the server may have completed and billed the work (2.5)
"Exactly-once delivery exists" It doesn't at the network level; you build effectively-once with idempotency keys or dedupe (3.2)
"Exponential backoff alone prevents retry storms" Without jitter, synchronised clients retry in synchronised waves — jitter is the fix (4.2)
"Retry-After is just another number to parse" It's either delay-seconds or an HTTP-date; parse both, clamp both, cap absurd values (4.3)
"wait_random_exponential and wait_exponential_jitter are the same" One draws uniform(0, ceiling), the other waits at least the exponential value — different spread behaviour (5.3)
"A bigger timeout is always safer" A read timeout bounds gaps between chunks, not total time; you need a deadline for the whole operation (2.1, 2.4)
"Retries and the SDK's built-in retries can coexist" They multiply — max_retries=2 × your 4 attempts = 12 calls; one layer owns retries (5.9)
"A circuit breaker replaces retries" They solve different problems: retries handle transient blips, the breaker stops calling a down service (6.1)
"Fallbacks are free" Each fallback route can itself retry; a 3-route chain with 4 attempts each is 12 provider calls per user request (6.5)

Key takeaways#

  • Classify before you retry. Transient failures (timeouts, resets, 408/425/429/5xx, transport errors) are worth retrying; permanent ones (400/401/403/404/422, quota/billing, your own bugs) are not. When unsure, don't retry.
  • Timeout every call, deadline every operation. Timeouts bound each wait; a Deadline bounds the total across all attempts. Propagate the remaining budget, never a fresh one.
  • Idempotency is the price of admission for retries on POST. Safe methods and PUT/DELETE are free; everything else needs an idempotency key, your own dedupe, or a conscious "may duplicate" decision.
  • Exponential backoff + full jitter + a cap + Retry-After awareness is the correct wait. The server's hint beats your formula; your formula beats nothing.
  • One layer owns retries. Turn off SDK retries when you add your own; otherwise attempts multiply.
  • tenacity is the production default for Python retries — stop/wait/retry/reraise, async-aware, testable via injected sleep/wait_none.
  • Retries are necessary but not sufficient. Circuit breakers stop calls to dead dependencies, bulkheads isolate them, rate limiters prevent the 429s, fallbacks degrade gracefully, and retry budgets cap total retry load.
  • For LLM APIs, the same machinery applies but the failure surface is provider-specific — Module 03 owns that detail; this lesson owns the mechanism.

Where you'll use this in the AI path#

Skill from this lesson Used in
Retry classification, tenacity policy, Retry-After 03.8 Errors, Rate Limits, Timeouts and Retries — the provider-aware version of everything here
Bounded concurrency + retries together 03.9 §4.5 Retries inside the bound, 03.9 §5 Rate-aware throughput
Deadlines and cancellation across a pipeline 07.11 §4.7 Graceful degradation — per-stage timeouts in a RAG service
Circuit breakers, bulkheads, fallbacks, retry budgets 11C.3 Fallbacks, Gateways and Reliability — the production system version
Retry/deadline metrics and alerting 11A.2 §1 The metrics that matter
Partial failure and dead-letter in batch jobs 05.9 §1.4 Fail-soft per document
Testing retry behaviour without waiting 01B.8 Testing with pytest, 03.10 §2
Idempotent tool side effects for agents 03.8 §11.3, Module 08A

Terms introduced in this lesson#

Term One-line definition
Transient failure A failure caused by timing or load — the same request may succeed later (timeout, reset, 429, 5xx)
Permanent failure A failure caused by the request itself — retrying fails identically (400, 401, 404, validation)
Timeout A bound on one wait (connect, read, write, pool); distinct from a deadline
Deadline A bound on the whole logical operation across all attempts and retries
asyncio.timeout A context manager that cancels a block and raises TimeoutError at a deadline
Idempotency Performing an operation once vs n times has the same effect
Idempotency key A client-generated unique token that lets a server dedupe retried requests
At-most-once / at-least-once / exactly-once The three delivery promises; "exactly-once" is a myth, "effectively-once" is built via idempotency
Exponential backoff Wait time that doubles each retry, up to a cap
Jitter Randomisation added to backoff waits to prevent synchronised retry storms
Full / equal / decorrelated jitter The three jitter formulas from the AWS Architecture Blog analysis
Retry-After A response header (delay-seconds or HTTP-date) telling the client how long to wait
Retry amplification Retry layers multiplying each other's attempts (SDK × your policy × gateway)
Retry storm / thundering herd Synchronised retries from many clients overwhelming a recovering service
Circuit breaker A switch that fails fast on a dead dependency, with closed/open/half-open states
Bulkhead Isolated resource pools per dependency so one failure can't sink the ship
Load shedding Deliberately refusing work when saturated rather than accepting and failing slowly
Hedged request Sending the same request twice and using the first response (cuts tail latency, costs double)
Retry budget A cap on total retry work a system may do, independent of per-call limits
Dead-letter A holding area for items that failed all retries, for inspection or replay
tenacity The standard Python retry library; policies built from stop/wait/retry pieces
reraise A tenacity option that raises the original exception instead of RetryError
Retrying / AsyncRetrying Tenacity's retry controllers, usable as decorators or for/with loops
wait_none A tenacity wait strategy that sleeps zero — for tests

All terms are also collected in the glossary.


Exercises#

  1. Classification. Given these failures, say retry / don't retry and why: httpx.ConnectTimeout, httpx.HTTPStatusError with response.status_code == 404, httpx.HTTPStatusError with status_code == 503, a TypeError from your own code, TimeoutError from asyncio.timeout.
  2. Backoff by hand. Using backoff_delay(failed_attempts=3, base=0.5, cap=8.0, rng=random.Random(1)), what is the ceiling of the wait? Now call it and print the result — is it below the ceiling?
  3. Retry-After parsing. Write a test for parse_retry_after covering: "120", an HTTP-date 90 s in the future, a date in the past, "garbage", and None. What does each return?
  4. Deadline arithmetic. A request has a 20 s deadline. Attempt 1 times out at 8 s, attempt 2 at 7 s. How much budget does attempt 3's deadline.timeout() give? What if attempt 3 also fails — is there budget for a sleep before attempt 4?
  5. Idempotency design. Your POST /refunds API has no idempotency-key support. Sketch (in words or pseudocode) how you'd make a retried refund safe using a dedupe table — what goes in the key, what's stored, what a dedupe hit returns.
  6. Jitter intuition. Why does full jitter (uniform(0, ceiling)) spread retries better than equal jitter (ceiling/2 + uniform(0, ceiling/2))? What does equal jitter guarantee that full jitter doesn't?
  7. tenacity policy. Write the tenacity decorator for: retry only TransientError, wait_random_exponential(multiplier=0.5, max=8), stop after 4 attempts or 20 s (stop_before_delay), reraise=True, log before each sleep.
  8. The double-retry trap. Your code uses openai.OpenAI(max_retries=2) (the default) and a tenacity policy with stop_after_attempt(4). How many provider calls can one logical request make? What's the fix?
  9. Circuit breaker tuning. With failure_threshold=3 and reset_timeout=10, a service fails 2 calls, succeeds 5, then fails 3 more. Does the breaker open? Why or why not? What does "consecutive" buy you here?
  10. Composition order. You put retries outside the circuit breaker (retry calls the breaker). What goes wrong during a provider outage? What's the correct nesting?
  11. Partial failure. A 100-item batch has 7 transient failures. Should you retry all 100 or just the 7? What do you do with items that fail all retries?
  12. wait_none test. Write a pytest test (illustrative) that verifies retry_async retries a FlakyBackend exactly 3 times using wait_none() — no real sleeping.
  13. What counts as a failure. Extend the hand-rolled CircuitBreaker.call with an is_failure: Callable[[BaseException], bool] constructor argument (default: every exception counts). Write a demo showing that with is_failure=lambda e: isinstance(e, TransientError) three PermanentErrors in a row leave the breaker closed, while three TransientErrors open it.
Solutions
  1. Retry: ConnectTimeout (transient), 503 (transient). Don't retry: 404 (permanent — resource doesn't exist), TypeError (your bug), TimeoutError from asyncio.timeout — careful: this one is retryable as a transient timeout, but only if the operation is idempotent; the classification is "retryable", the idempotency check is separate.
  2. Ceiling: min(8.0, 0.5 × 2²) = 2.0 s. backoff_delay returns uniform(0, 2.0) — always ≤ 2.0, could be anywhere in [0, 2.0).
  3. "120" → 120.0; HTTP-date +90 s → 90.0; past date → 0.0; "garbage" → None; None → None. (The demo loop in 4.3 prints these same cases.)
  4. Remaining after two timeouts: 20 − 8 − 7 = 5 s. Attempt 3 gets ~5 s. If it also fails, there is no budget for a sleep — stop_before_delay/deadline check would refuse to start a wait that can't finish, so the operation fails rather than overrunning.
  5. Key = stable hash of (user_id, refund_id, amount) — same logical refund, same key. Before calling the API: INSERT INTO dedupe_keys(key, result) ... ON CONFLICT DO NOTHING RETURNING * — if a row exists, return its stored result; if not, call the API, store (key, response) on success. A retry with the same key hits the row and returns the original response instead of refunding twice.
  6. Full jitter spreads retries across [0, ceiling) — maximum spread, minimum synchronisation. Equal jitter guarantees at least ceiling/2 — a floor that keeps retries from being too eager but clusters them in the upper half. Full jitter is preferred for de-synchronising fleets; equal jitter trades a bit of spread for a minimum wait.
  7. python
    @retry(
        retry=retry_if_exception_type(TransientError),
        wait=wait_random_exponential(multiplier=0.5, max=8),
        stop=stop_after_attempt(4) | stop_before_delay(20),
        before_sleep=before_sleep_log(log, logging.WARNING),
        reraise=True,
    )
    async def fetch(*args, **kwargs): ...
  8. Up to 4 × 3 = 12 provider calls (4 tenacity attempts × 3 SDK attempts each). Fix: OpenAI(max_retries=0) — one layer owns retries.
  9. No. The breaker counts consecutive failures; the 5 successes reset the counter, so the second run of 3 failures is the first time it reaches the threshold — it opens on the 3rd of those. "Consecutive" prevents old failures from keeping a recovered service open.
  10. Retrying outside the breaker means each retry goes through breaker.call(). One logical request then counts several failures against the breaker, and once it is open every remaining retry fails instantly with CircuitOpenError — which a broad policy (retry_if_exception_type(Exception)) would retry again, burning attempts and masking the "service is down" signal. Correct: breaker outside, retry inside — breaker.call(lambda: retry(fn)) or equivalent, so one trip stops the whole operation.
  11. Retry only the 7 — retrying all 100 wastes calls and can duplicate side effects on the 93 that succeeded. Items that exhaust retries go to a dead-letter list/file for inspection or replay; never drop them silently.
  12. python

@pytest.mark.asyncio async def test_retry_async_retries(): backend = FlakyBackend(failures=2) decorated = retry_async(wait=wait_none())(backend) assert await decorated() == "ok" assert backend.calls == 3

text
(`wait_none()` makes every sleep instant — the test verifies the *count*, not the timing.)
13. A subclass is enough (it reuses the `_before_call`/`_after_failure` hooks from [6.1](#61-circuit-breakers)); this runs on the standard library next to `mini_resilience.py`:

 ```python
 from mini_resilience import CircuitBreaker, PermanentError, TransientError


 class FilteredBreaker(CircuitBreaker):
     """Only failures that say something about the dependency's health count."""

     def __init__(self, *, is_failure=lambda exc: True, **kwargs):
         super().__init__(**kwargs)
         self._is_failure = is_failure

     def call(self, fn):
         self._before_call()
         try:
             result = fn()
         except Exception as exc:
             if self._is_failure(exc):
                 self._after_failure()
             else:
                 self._probing = False   # a half-open probe that failed for another reason is not a verdict
             raise
         self._after_success()
         return result


 def boom(exc_type):
     def fn():
         raise exc_type("x")
     return fn


 breaker = FilteredBreaker(failure_threshold=3, is_failure=lambda e: isinstance(e, TransientError))
 for _ in range(3):
     try:
         breaker.call(boom(PermanentError))
     except PermanentError:
         pass
 print("after 3 PermanentError:", breaker.state)
 for _ in range(3):
     try:
         breaker.call(boom(TransientError))
     except TransientError:
         pass
 print("after 3 TransientError:", breaker.state)
 ```

 Output:

 ```text
 after 3 PermanentError: closed
 after 3 TransientError: open
 ```

</details>

---

## Check yourself

1. What's the difference between a timeout and a deadline?
2. Name the four `httpx.Timeout` fields and what each bounds.
3. Why is `time.monotonic()` preferred over `time.time()` for deadlines?
4. Which HTTP methods are idempotent per RFC 9110 §9.2.2, and which is notably *not*?
5. What does an idempotency key actually do, and why must it be generated once per *operation*, not per *attempt*?
6. What's the difference between at-least-once and effectively-once delivery?
7. Write the formula for exponential backoff with full jitter.
8. Why is plain exponential backoff (no jitter) dangerous at scale?
9. What are the two forms of `Retry-After`, and which stdlib function parses the date form?
10. What does `reraise=True` do in tenacity, and why does it matter?
11. What's the difference between `wait_random_exponential` and `wait_exponential_jitter`?
12. Name the three circuit-breaker states and what triggers each transition.
13. Why should the circuit breaker wrap *outside* the retry logic, not inside?
14. What's a retry budget, and why do retries need one?
15. For LLM APIs, why does a retried call cost more than a retried `GET`?

<details>
<summary>Answers</summary>

1. A timeout bounds one wait (connect/read/write/pool); a deadline bounds the whole logical operation across all attempts.
2. `connect` (opening the connection), `read` (waiting for response data, per chunk), `write` (sending the body), `pool` (waiting for a free connection from the pool).
3. `time.monotonic()` only moves forward and isn't affected by system-clock adjustments; `time.time()` can jump backwards and break deadline arithmetic.
4. `GET`, `HEAD`, `OPTIONS`, `TRACE` (safe) and `PUT`, `DELETE` (idempotent) are; `POST` is notably *not* — its outcome can differ each time.
5. It's a unique token the client sends so the server can dedupe retries and return the first result. Per-operation, because per-attempt keys make each retry look like a new request.
6. At-least-once means the work may happen more than once; effectively-once means it *appears* to happen once because the consumer dedupes — the network can't guarantee exactly-once.
7. `wait = uniform(0, min(cap, base × 2^(failed_attempts − 1)))`.
8. Synchronised clients compute identical delays and retry in synchronised waves, re-overwhelming a recovering server — jitter spreads them out.
9. `delay-seconds` (e.g. `30`) and `HTTP-date` (e.g. `Fri, 06 Nov 2026 12:00:30 GMT`); `email.utils.parsedate_to_datetime` parses the date form.
10. It re-raises the *original* last exception instead of wrapping it in `tenacity.RetryError` — so `except httpx.HTTPStatusError` still works downstream.
11. `wait_random_exponential` draws `uniform(0, exponential_ceiling)` — full jitter, can wait less than exponential. `wait_exponential_jitter` waits *at least* the exponential value plus up to `jitter` extra — partial jitter, stays near the schedule.
12. **Closed** (normal), **open** (failure_threshold consecutive failures), **half-open** (reset_timeout elapsed → one probe; success closes, failure reopens).
13. Because the breaker should stop the *whole operation* when the dependency is down, and should see one outcome per logical call. If retries wrap the breaker, one request counts several failures against it, and once it is open each remaining retry fails fast and pointlessly.
14. A cap on total retry work a system may do, independent of per-call limits — prevents retries from becoming self-inflicted DDoS during an outage.
15. Because a retried generation may have already consumed input tokens and produced output — each attempt has a price tag that a `GET` retry doesn't.

</details>

---

## Further resources

- **Marc Brooker, ["Exponential Backoff And Jitter"](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)** (AWS Architecture Blog, 2015): the canonical analysis of the four jitter formulas.
- **[tenacity documentation](https://tenacity.readthedocs.io/)** and **[GitHub repository](https://github.com/jd/tenacity)**: the API reference for every `stop`/`wait`/`retry` piece used here.
- **[RFC 9110](https://www.rfc-editor.org/rfc/rfc9110)**: §9.2.2 (idempotent methods), §10.2.3 (`Retry-After`), §15.5.9 (408), §15.6.4 (503).
- **[RFC 6585](https://www.rfc-editor.org/rfc/rfc6585#section-4)**: `429 Too Many Requests` and its `Retry-After` semantics.
- **[Stripe, Idempotent requests](https://docs.stripe.com/api/idempotent_requests)**: the canonical idempotency-key implementation.
- **Dean & Barroso, ["The Tail at Scale"](https://research.google/pubs/the-tail-at-scale/)** (CACM, 2013): hedged requests and why tail latency dominates at scale.
- **Michael Nygard, *Release It!*** (Pragmatic Bookshelf): the original stability-patterns catalogue (circuit breaker, bulkhead, timeouts).
- **[Python `asyncio` docs](https://docs.python.org/3/library/asyncio-task.html)**: `asyncio.timeout`, `wait_for`, task cancellation.
- **[Python `email.utils` docs](https://docs.python.org/3/library/email.utils.html)**: `parsedate_to_datetime` for HTTP-date parsing.
- **Module 03, [03.8 Errors, Rate Limits, Timeouts and Retries](../03-llm-apis/08-errors-and-retries.md)**: the provider-aware version of everything in this lesson.
- **[11C.3 Fallbacks, Gateways and Reliability](../11c-deployment-reliability-and-lifecycle/03-fallbacks-gateways-and-reliability.md)**: production circuit breakers, bulkheads and fallback chains for LLM services.

---

← [01B.8 — Testing with pytest](08-testing-with-pytest.md) | [Module 01B overview](index.md) | [01B.10 — Logging, Debugging and Packaging: Putting the Toolkit Together](10-logging-debugging-and-packaging.md) →
Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close