Decide whether another attempt can help
Inspect the provider’s documented status and error body. Correct an invalid request or permission problem before sending it again. A rate limit or temporary server error may justify a bounded later attempt. A timeout or broken connection can leave the first request’s outcome uncertain.
For the Claude Python SDK, automatic retries are enabled by default for selected failures. When you implement an outer retry loop, disable SDK retries so the two policies do not multiply attempts. The example below retries only the selected HTTP status failures. It lets connection and timeout exceptions reach the caller for an explicit decision. SDK retries and errors.
Backoff, with jitter, and why jitter is not optional
import random
import time
from anthropic import APIStatusError
RETRYABLE = {429, 500, 502, 503, 529}
def create_with_retries(
client, request, attempts=4, budget_s=25
):
if attempts < 1 or budget_s <= 0:
raise ValueError(
"Attempts and time budget "
"must be positive"
)
api = client.with_options(max_retries=0)
expires = time.monotonic() + budget_s
for attempt in range(attempts):
remaining = expires - time.monotonic()
if remaining <= 0:
raise TimeoutError(
"No time remains for another attempt"
)
try:
return api.messages.create(
**request, timeout=remaining
)
except APIStatusError as error:
if error.status_code not in RETRYABLE:
raise
if attempt == attempts - 1:
raise
header = error.response.headers.get("retry-after")
try:
wait = max(0.0, float(header))
except (TypeError, ValueError):
wait = min(2 ** attempt, 8) * (
0.5 + random.random()
)
if wait >= expires - time.monotonic():
raise TimeoutError(
"Retry would exceed the time budget"
) from error
time.sleep(wait)Pass the helper a request dictionary containing the model, messages and output cap, as in the earlier examples. The helper checks the remaining budget before each attempt and wait, and passes that remaining time as the request timeout. This is client-side scheduling, not a guarantee that server execution stops at that instant. SDK HTTP timeouts also have transport-level semantics, so measure elapsed time and enforce any stricter outer deadline in the application.
The example handles a numeric retry-after value in seconds. A production adapter should also support an HTTP-date header when the provider uses that form. Its fallback uses exponential backoff with jitter. Keep the total attempt and elapsed-time policy visible in logs.
The retry storm that is your fault
Here is the failure mode worth internalising, because it is self-inflicted.
Suppose a provider slows from two seconds to twenty. If a ten-second client timeout triggers another request while the first is still running, work can overlap. Repeated across many users, extra attempts can exhaust your concurrency or rate limits. Whether the first call continues and is billed depends on its outcome and the provider. Log uncertain outcomes and avoid treating a dropped connection as proof that no generation occurred.
The defences are all boring:
- A concurrency cap: a semaphore around outbound calls. Above it, queue or shed load. A number you chose beats a number your connection pool chose for you.
- A circuit breaker. After N consecutive failures, stop calling for 30 seconds and fail fast. This is counter-intuitive and correct: when a dependency is unhealthy, the kindest thing you can do is stop sending it traffic.
- A total budget per user request: attempts and seconds, both capped.
- Shed the retry on non-interactive paths. A background job can wait a minute. A user cannot.
Timeouts on a streaming call
A stream may need both an inactivity timeout and a total elapsed-time budget. The inactivity limit catches a stalled connection. The total budget limits how long the task may occupy resources. Select both for the task and the deployed infrastructure.
Retries and duplicates
A retry can create another generation and another charge when the provider accepts and processes it. The returned text can differ. Before retrying an uncertain outcome, consider whether the original request or a tool it triggered could already have changed external state.
So: keep side effects out of the retried region, or make them idempotent. If your loop retries an entire agent turn, and step three of that turn charged a card, a network blip has now charged it twice. Give every externally visible action a key derived from the request, store the key, and make the second attempt a no-op. This is ordinary distributed-systems hygiene, and putting a model in the loop does not exempt you from it: it makes it more likely, because agent loops retry more.
Check your understanding
A service retries slow requests while the original calls may still be running. Which mechanism can raise its own error rate?
Pick the one you would defend. Your answer stays private.
Your place and first choices stay on this browser. Classroom credit is recorded separately.
Every lesson here is open. Your progress is recorded once you pass the Python, from Zero, for AI exam.
Stuck on something?Ask Sayali, your AI tutor