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
On this page
- Goal and setup
- Step 1: See a rate limit on the wire
- Step 2: Watch the SDK retry for you
- Step 3: Write a retry policy and check its numbers
- Step 4: Run the policy against scripted failures
- Step 5: Set timeouts deliberately
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of LLM API Integration
- Anatomy of a Request: Messages, Parameters and Media Concept · 15 min
- First Calls: Parameters, Usage, Images and Audio Worked example · 25 min
- Lab: Retries, Backoff and Timeouts Lab · 25 min
- Streaming and Cancellation Worked example · 20 min
- Lab: One Client for Hosted, Local and Mock Models Lab · 30 min
- Check: Diagnose Failing API Calls Knowledge check · 10 questions
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:
- see a rate-limit response as raw HTTP;
- watch the retries the official SDKs already make for you;
- write
retry.py, a policy you control: bounded attempts, exponential backoff with full jitter, Retry-After, and a time budget; - run it against scripted failures and slow responses;
- 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.
python -m pip install httpx
python -c "import httpx; print(httpx.__version__)"0.28.102. 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:
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{"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:
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}')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.pyHTTP 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:
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.pyHTTP 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 503By 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
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_retryableaccepts connection failures and timeouts (APITimeoutErroris a kind ofAPIConnectionErrorin 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-Aftervalue, in either form, wins. Otherwisebackoffdraws 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_retriesretries: four attempts with the default of 3. Before every wait the time budget is checked, and if waiting would passdeadlinethe call fails now; a 429 asking for 60 seconds while a user watches is better reported than obeyed. - Testability.
sleepis 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:
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')python show_backoff.pyattempt 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 msEvery 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:
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])python try_retries.py transient
python try_retries.py rate-limit
python try_retries.py persistent
python try_retries.py bad-request--- 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
ServiceUnavailableErrorfor 503 andOverloadedErrorfor 529, both kinds ofInternalServerError), 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:
python try_retries.py slow--- 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 totalFour 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:
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')python timeouts.pyTimeout(connect=5.0, read=30.0, write=30.0, pool=30.0)
10.0
0Retry 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
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:
- Write pytest tests for
call_with_retrieswith a fakesleepthat 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 withanthropic.RateLimitError(message, response=httpx2.Response(429, request=...), body=None). - 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.
- Read
anthropic-ratelimit-requests-remainingfrom 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.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.