Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 3

Lab: Retries, Backoff and Timeouts

Make a model client survive rate limits, overloads and slow responses: watch the SDK's built-in retries, then write a bounded retry policy with exponential backoff, full jitter, Retry-After and a time budget, and test it against scripted failures.

Contentsand lesson path

What you will learn

  • Handle rate limits, timeouts and transient errors with bounded retries and exponential backoff with jitter.

Prerequisites: Python Foundations, HTTP & APIs

01. Goal and setup

Model APIs fail in ordinary ways: 429 when you exceed your rate limit, 529 or 503 when the provider is overloaded, 500 when something breaks, and sometimes no answer at all. Most failures are temporary, so a later attempt usually works, but careless retries make things worse: thousands of clients retrying at once keep an overloaded service overloaded.

In this lab you will:

  1. see a rate-limit response as raw HTTP;
  2. watch the retries the official SDKs already make for you;
  3. write retry.py, a policy you control: bounded attempts, exponential backoff with full jitter, Retry-After, and a time budget;
  4. run it against scripted failures and slow responses;
  5. set timeouts deliberately.

You need the llm-client folder from lesson 2, with the stand-in running in terminal 1 (uvicorn fake_provider:app --port 8100) and its environment variables set in terminal 2. Part 2 of fake_provider.py adds a control endpoint, POST /_fake/plan: the statuses in fail go, in order, to the next model requests, with a Retry-After header if retry_after is set, and delay makes every response late by that many seconds. An empty plan, {}, restores normal service. Tested with the lesson 2 versions plus httpx 0.28.

Terminal 2
python -m pip install httpx
python -c "import httpx; print(httpx.__version__)"
Expected output (your version may be newer)
0.28.1

02. Step 1: See a rate limit on the wire

Script one 429 with a two-second hint, then send a request with curl, as any client would:

Terminal 2
curl -s http://127.0.0.1:8100/_fake/plan -H "Content-Type: application/json" \
  -d '{"fail": [429], "retry_after": 2}'
echo
curl -i -s http://127.0.0.1:8100/v1/messages -H "Content-Type: application/json" \
  -d '{"model": "m", "max_tokens": 5, "messages": [{"role": "user", "content": "Hi"}]}'
echo
Expected output (the date differs)
{"fail":[429],"retry_after":2,"delay":0.0}
HTTP/1.1 429 Too Many Requests
date: Sun, 18 Oct 2026 09:39:24 GMT
server: uvicorn
retry-after: 2
content-length: 73
content-type: application/json

{"type":"error","error":{"type":"rate_limit_error","message":"fake 429"}}

After the accepted plan comes the response a client must handle: status 429, a retry-after header with the seconds to wait, and a JSON body whose error.type names the problem. Real providers send the same status and header; Retry-After can also hold an HTTP date instead of seconds. Anthropic adds anthropic-ratelimit-* headers to every response, with your limits and what remains of them, so you can slow down before a 429.

03. Step 2: Watch the SDK retry for you

Both official SDKs retry by themselves. sdk_retries.py turns on Python logging, so you can see each HTTP attempt and each wait the SDK schedules, and then calls the ask function from lesson 2:

Python · sdk_retries.py
import logging

import anthropic

from ask_claude import ask

# Show the SDK's own log lines: each HTTP attempt and each retry it schedules.
logging.basicConfig(level=logging.INFO, format='%(message)s')
try:
    print(ask(max_tokens=300).splitlines()[0])
except anthropic.APIStatusError as exc:
    print(f'failed after the built-in retries: {type(exc).__name__} {exc.status_code}')
Terminal 2
curl -s http://127.0.0.1:8100/_fake/plan -H "Content-Type: application/json" \
  -d '{"fail": [429, 503], "retry_after": 1}' > /dev/null
python sdk_retries.py
Illustrative output (with Retry-After: 1, both waits are exactly one second)
HTTP Request: POST http://127.0.0.1:8100/v1/messages "HTTP/1.1 429 Too Many Requests"
Retrying request to /v1/messages in 1.000000 seconds
HTTP Request: POST http://127.0.0.1:8100/v1/messages "HTTP/1.1 503 Service Unavailable"
Retrying request to /v1/messages in 1.000000 seconds
HTTP Request: POST http://127.0.0.1:8100/v1/messages "HTTP/1.1 200 OK"
stop_reason=end_turn, stop_sequence=None
usage: input_tokens=37, output_tokens=43
Fake reply to: What should we change first?

Now script three 503 responses without a Retry-After header:

Terminal 2
curl -s http://127.0.0.1:8100/_fake/plan -H "Content-Type: application/json" \
  -d '{"fail": [503, 503, 503]}' > /dev/null
python sdk_retries.py
Illustrative output (the SDK's jittered waits differ on every run)
HTTP Request: POST http://127.0.0.1:8100/v1/messages "HTTP/1.1 503 Service Unavailable"
Retrying request to /v1/messages in 0.394174 seconds
HTTP Request: POST http://127.0.0.1:8100/v1/messages "HTTP/1.1 503 Service Unavailable"
Retrying request to /v1/messages in 0.865646 seconds
HTTP Request: POST http://127.0.0.1:8100/v1/messages "HTTP/1.1 503 Service Unavailable"
failed after the built-in retries: ServiceUnavailableError 503

By default each SDK makes up to two retries, three attempts in all, for connection errors, timeouts and the statuses 408, 409, 429 and 500 or above. It waits as long as a Retry-After header asks (the openai SDK gives up instead if the hint exceeds two minutes); otherwise 0.5 seconds, then 1, doubling up to 8, minus up to a quarter at random (anthropic 2.9 and openai 3.52). Then it raises the error: for a 503 the anthropic SDK raises ServiceUnavailableError, a subclass of InternalServerError. max_retries sets the number, on the client or per call with client.with_options(max_retries=...). Write your own policy when you need what the SDK lacks: a time budget across attempts, per-call-site rules, or one policy for several providers.

04. Step 3: Write a retry policy and check its numbers

Python · retry.py
import email.utils
import random
import time
from collections.abc import Callable

import anthropic
import openai

RETRYABLE_STATUS = {408, 409, 429}  # plus every 5xx, including 529 overloaded
CONNECTION_ERRORS = (anthropic.APIConnectionError, openai.APIConnectionError)
STATUS_ERRORS = (anthropic.APIStatusError, openai.APIStatusError)


def is_retryable(exc: Exception) -> bool:
    if isinstance(exc, CONNECTION_ERRORS):  # includes APITimeoutError
        return True
    if isinstance(exc, STATUS_ERRORS):
        return exc.status_code in RETRYABLE_STATUS or exc.status_code >= 500
    return False


def retry_after(exc: Exception) -> float | None:
    """Seconds the server asked us to wait, from a Retry-After header."""
    response = getattr(exc, 'response', None)
    value = response.headers.get('retry-after') if response is not None else None
    if value is None:
        return None
    try:
        return max(0.0, float(value))  # delay-seconds form, e.g. "2"
    except ValueError:
        pass
    try:  # HTTP-date form, e.g. "Sun, 18 Oct 2026 09:00:00 GMT"
        moment = email.utils.parsedate_to_datetime(value)
    except (TypeError, ValueError):
        return None
    return max(0.0, moment.timestamp() - time.time())


def backoff(attempt: int, base: float = 0.5, cap: float = 20.0) -> float:
    """Full jitter: a random wait between 0 and the exponential ceiling."""
    return random.uniform(0, min(cap, base * 2**attempt))


def call_with_retries[T](
    call: Callable[[], T],
    *,
    max_retries: int = 3,
    deadline: float = 60.0,
    sleep: Callable[[float], None] = time.sleep,
) -> T:
    started = time.monotonic()
    for attempt in range(max_retries + 1):
        try:
            return call()
        except Exception as exc:
            if attempt == max_retries or not is_retryable(exc):
                raise
            asked = retry_after(exc)
            wait = backoff(attempt) if asked is None else asked
            if time.monotonic() - started + wait > deadline:
                raise  # waiting would blow the time budget: fail now
            print(f'attempt {attempt + 1}: {type(exc).__name__}, '
                  f'waiting {wait * 1000:.0f} ms' + (' (Retry-After)' if asked else ''))
            sleep(wait)
    raise AssertionError('unreachable')
  • What to retry. is_retryable accepts connection failures and timeouts (APITimeoutError is a kind of APIConnectionError in both SDKs), 408, 409, 429 and every 5xx, the set the SDKs use. A 400, 401, 403, 404 or 422 is raised at once: the same request would fail again.
  • How long to wait. A Retry-After value, in either form, wins. Otherwise backoff draws a random wait between 0 and a ceiling that doubles with each attempt, up to 20 seconds. Drawing the whole wait at random is called full jitter: clients that failed together spread out instead of returning together.
  • When to stop. At most max_retries retries: four attempts with the default of 3. Before every wait the time budget is checked, and if waiting would pass deadline the call fails now; a 429 asking for 60 seconds while a user watches is better reported than obeyed.
  • Testability. sleep is a parameter, so a test can record the waits instead of sleeping.

Retrying a model request is safe because it changes nothing on the server, but every attempt that reached the model is billed. Never put a call with side effects, such as one that also charges a card, behind a blind retry.

Before trusting the policy, print the waits it would choose. The script seeds the random generator so that your numbers match these:

Python · show_backoff.py
import random

from retry import backoff

random.seed(42)  # only so that your numbers match these; never seed in production
for attempt in range(6):
    ceiling_ms = min(20.0, 0.5 * 2**attempt) * 1000
    wait_ms = backoff(attempt) * 1000
    print(f'attempt {attempt}: ceiling {ceiling_ms:5.0f} ms, wait {wait_ms:5.0f} ms')
Terminal 2
python show_backoff.py
Expected output
attempt 0: ceiling   500 ms, wait   320 ms
attempt 1: ceiling  1000 ms, wait    25 ms
attempt 2: ceiling  2000 ms, wait   550 ms
attempt 3: ceiling  4000 ms, wait   893 ms
attempt 4: ceiling  8000 ms, wait  5892 ms
attempt 5: ceiling 16000 ms, wait 10827 ms

Every wait lies between zero and its ceiling, and the ceilings double. Short waits such as 25 ms are normal with full jitter: waits average half the ceiling, which spreads retries out without making anyone wait the full amount.

05. Step 4: Run the policy against scripted failures

try_retries.py sets a plan on the stand-in, makes one call through call_with_retries, and reports what happened. The client is created with max_retries=0, so that the wrapper is the only layer that retries, and with a timeout for each attempt. It passes its own sleep, which records each wait before sleeping, so the summary line reports the waits the policy chose rather than a stopwatch reading that differs on every machine:

Python · try_retries.py
import os
import random
import sys
import time

import anthropic
import httpx

from retry import call_with_retries

PLAN_URL = 'http://127.0.0.1:8100/_fake/plan'  # the fake's control endpoint
SCENARIOS = {
    'transient': ({'fail': [503, 529]}, 30.0),
    'rate-limit': ({'fail': [429], 'retry_after': 2}, 30.0),
    'persistent': ({'fail': [503, 503, 503, 503]}, 30.0),
    'bad-request': ({'fail': [400]}, 30.0),
    'slow': ({'delay': 3}, 1.0),
}


def ask(client: anthropic.Anthropic) -> str:
    response = client.messages.create(
        model=os.environ['ANTHROPIC_MODEL'],
        max_tokens=50,
        messages=[{'role': 'user', 'content': 'Ping?'}],
    )
    text = ''.join(b.text for b in response.content if b.type == 'text')
    return text.splitlines()[0]


def run(name: str) -> None:
    plan, timeout = SCENARIOS[name]
    # max_retries=0: our wrapper is the only layer that retries.
    # timeout: the limit for each attempt, in seconds.
    client = anthropic.Anthropic(max_retries=0, timeout=timeout)
    waits: list[float] = []

    def sleep(seconds: float) -> None:  # sleeps, and records each wait
        waits.append(seconds)
        time.sleep(seconds)

    httpx.post(PLAN_URL, json=plan)
    print(f'--- {name}: {plan}, timeout {timeout:g} s')
    try:
        print('result:', call_with_retries(lambda: ask(client), sleep=sleep))
    except Exception as exc:
        print(f'gave up: {type(exc).__name__}')
    finally:
        httpx.post(PLAN_URL, json={})  # back to normal
    print(f'retries: {len(waits)}, waited {sum(waits) * 1000:.0f} ms in total')


if __name__ == '__main__':
    random.seed(7)  # only so that your output matches; never seed in production
    run(sys.argv[1])
Terminal 2
python try_retries.py transient
python try_retries.py rate-limit
python try_retries.py persistent
python try_retries.py bad-request
Expected output
--- transient: {'fail': [503, 529]}, timeout 30 s
attempt 1: ServiceUnavailableError, waiting 162 ms
attempt 2: OverloadedError, waiting 151 ms
result: Fake reply to: Ping?
retries: 2, waited 313 ms in total
--- rate-limit: {'fail': [429], 'retry_after': 2}, timeout 30 s
attempt 1: RateLimitError, waiting 2000 ms (Retry-After)
result: Fake reply to: Ping?
retries: 1, waited 2000 ms in total
--- persistent: {'fail': [503, 503, 503, 503]}, timeout 30 s
attempt 1: ServiceUnavailableError, waiting 162 ms
attempt 2: ServiceUnavailableError, waiting 151 ms
attempt 3: ServiceUnavailableError, waiting 1302 ms
gave up: ServiceUnavailableError
retries: 3, waited 1615 ms in total
--- bad-request: {'fail': [400]}, timeout 30 s
gave up: BadRequestError
retries: 0, waited 0 ms in total
  • transient: a 503 and a 529 (the SDK raises ServiceUnavailableError for 503 and OverloadedError for 529, both kinds of InternalServerError), then success. The user waited about a third of a second, 313 ms of backoff plus three quick requests, instead of seeing an error.
  • rate-limit: the wait is exactly the two seconds the server asked for, not a random one.
  • persistent: after three retries, four attempts in all, the wrapper gives up and raises the last error, so the caller can report it.
  • bad-request: a 400 is not retried at all.

06. Step 5: Set timeouts deliberately

The SDKs' default timeout is ten minutes, so a stuck request can hold a user, a worker or a test for a very long time. The slow scenario makes every response three seconds late and gives each attempt one second:

Terminal 2
python try_retries.py slow
Expected output
--- slow: {'delay': 3}, timeout 1 s
attempt 1: APITimeoutError, waiting 162 ms
attempt 2: APITimeoutError, waiting 151 ms
attempt 3: APITimeoutError, waiting 1302 ms
gave up: APITimeoutError
retries: 3, waited 1615 ms in total

Four attempts timed out after one second each, and the three waits added 1.6 seconds, so the call took about 5.6 seconds. A policy can take roughly (max_retries + 1) × timeout plus the waits, which deadline guards against, but only in part: the check runs before each wait, so the last attempt can still run for up to a full timeout past the deadline (with a 30-second timeout and a 60-second deadline, a call whose attempts each take 30 seconds and end in a 429 with Retry-After: 5 gives up at 65 seconds). To bound the call strictly, also skip a retry when the time left is shorter than one attempt timeout, or give that attempt the time left as its timeout with client.with_options(timeout=remaining). Choose them together: for an interactive feature, 30 seconds per attempt and 60 per call are a reasonable start.

SDK timeouts limit each phase of an attempt: connecting, sending, and every wait for data. A non-streamed answer arrives in one piece when the model has finished, so the read timeout effectively limits generation time. A stream sends data every few tokens, resetting the timer, so it also needs an overall deadline (lesson 4). You can set each phase, and override limits for one kind of call:

Python · timeouts.py
import anthropic
import openai

# Each attempt: 5 s to connect, 30 s for any other wait (sending, or reading data).
LIMITS = anthropic.Timeout(30.0, connect=5.0)
claude = anthropic.Anthropic(timeout=LIMITS, max_retries=0)
gpt = openai.OpenAI(timeout=openai.Timeout(30.0, connect=5.0), max_retries=0)
quick = claude.with_options(timeout=10.0)  # a tighter limit for one kind of call
print(claude.timeout, quick.timeout, gpt.max_retries, sep='\n')
Terminal 2
python timeouts.py
Expected output
Timeout(connect=5.0, read=30.0, write=30.0, pool=30.0)
10.0
0

Retry in one layer only. A wrapper with four attempts over the SDK's default of three makes twelve requests per call during an outage, and every further layer multiplies the load again. Retry in the layer that knows the caller's time budget, usually your wrapper or a gateway, and set max_retries=0 everywhere else.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Reason about your retry policy

Three questions about the policy you have just tested.

Q1. Your wrapper allows 3 retries, and the SDK client underneath keeps its default of 2. During an outage every request gets 503. How many HTTP requests does one call make?
Q2. A 429 arrives with Retry-After: 30, and 10 seconds remain of the call's 60-second deadline. What does call_with_retries do?
Q3. With base 0.5 s and full jitter, what can the wait be after the third failure, when the attempt index is 2?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch task

The practice project must retry 429 and 5xx responses up to three times with jittered backoff and enforce a 30-second timeout. Bring the policy in:

  1. Write pytest tests for call_with_retries with a fake sleep that records the waits: success after two failures, giving up after three retries, no retry for a 400, an honoured Retry-After, and the deadline. Construct errors with anthropic.RateLimitError(message, response=httpx2.Response(429, request=...), body=None).
  2. Add a retry budget, a token bucket shared by all calls: each retry takes a token, tokens refill slowly, and an empty bucket means failing at once. Show with twenty scripted 503s that it stops a retry storm.
  3. Read anthropic-ratelimit-requests-remaining from a real response (client.messages.with_raw_response.create(...), then .headers) and warn when it drops below ten per cent of the limit.

10. Review prompt

Without looking back, write call_with_retries from memory: the list of retryable failures, full-jitter backoff, the Retry-After rule and the deadline check. Then explain in three sentences why jitter matters when many clients fail at once, why only one layer should retry, and why a stream needs an overall deadline in addition to its timeouts.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check