Sub topic 4
Setting timeouts and overall deadlines
This chapter assumes you can write Python functions with exceptions, you know what HTTP status codes and headers are, and you have called an LLM API with an SDK or an HTTP client. It builds on the idea that timeouts are one kind of retryable failure. Backoff, jitter, Retry-After, and attempt limits each get their own chapter, so here they appear only where they affect time.
Why a missing timeout is a bug
A network call with no timeout can wait forever. A hosted LLM call is more exposed than most, because the server may spend many seconds generating before it sends a single byte. If your client has no limit, a stalled connection holds a worker, a thread, or a user's browser tab until something else gives up.
Many HTTP libraries and SDKs ship defaults that are far too generous for an interactive application. The requests library has no timeout at all unless you pass one. The OpenAI Python SDK defaults to 10 minutes. Always choose a value on purpose.
Two different limits
Two limits work together, and they answer different questions.
- A per-attempt timeout limits how long one request may take before you abandon it.
- An overall deadline limits the total time for the whole operation: every attempt, every pause between attempts, and any fallback work.
Retries multiply time. With five attempts of 30 seconds each and a few pauses, a call can run for more than two and a half minutes even though each attempt looks reasonable. The user, or an upstream service with its own timeout, will not wait that long. The deadline is the number you derive from what the caller can tolerate. The per-attempt timeout is then chosen to fit inside it.
The phases of one request
HTTP clients split a request into phases and often let you limit each one. Here is how httpx does it.
| Phase | What it limits | Typical value for LLM calls |
|---|---|---|
| connect | Opening the TCP and TLS connection | 3 to 10 seconds |
| write | Sending the request body | 10 seconds |
| read | Waiting for the next bytes from the server | Depends on the call |
| pool | Waiting for a free connection from the client's pool | 5 seconds |
The read value needs care. In httpx it is a gap timer, not a total timer: it limits the wait between chunks of data. For a non-streaming call, the server sends nothing until the full completion is ready, so the read timeout acts as a limit on total generation time. For a streaming call, tokens arrive continuously, so the same value limits only silence between tokens. A streaming call can run for minutes without ever tripping a 30-second read timeout, so a streaming call needs its own total deadline.
import httpx
# Fail fast when the server is unreachable, but allow a long generation.
timeout = httpx.Timeout(connect=5.0, write=10.0, read=60.0, pool=5.0)
client = httpx.Client(timeout=timeout)If you pass one number, as in httpx.Timeout(30.0), that number applies to each phase separately. A single request can therefore take longer than 30 seconds in total if several phases are each slow. Treat a single number as a rough guide and not as a strict cap. A strict cap needs a deadline that you track yourself.
Choosing the numbers
Work backwards from the caller.
- Decide the longest the user or upstream service will wait. This is your overall deadline.
- Estimate how long one healthy call takes at the 99th percentile for your prompt sizes and
max_tokenssetting. Add some margin. This is your per-attempt timeout. - Check that the deadline allows at least two attempts. If it does not, retries cannot help and you should say so in your design.
Generation time grows with output length, so one value does not suit every request. A call with max_tokens=4000 legitimately takes longer than one with max_tokens=200. If your application mixes both, scale the read timeout with the expected output size. A fixed value either kills long answers or lets short ones hang.
A timeout that is too short is a failure of its own. If your per-attempt limit is below the real latency of healthy requests, every attempt times out, the retries add load, and you pay for tokens that were generated and discarded.
A deadline-aware retry loop
The version below tracks a deadline with time.monotonic(), which is a clock that never jumps backwards when the system time changes. Before each attempt it computes the time remaining and caps the attempt timeout to that value. It also refuses to sleep past the deadline. It reuses the retryable status set from earlier in this tutorial and uses httpx.MockTransport, so you can run it without a network or an API key.
import random
import time
import httpx
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
class DeadlineExceeded(Exception):
"""Raised when the overall time budget is spent."""
def post_with_deadline(
client,
url,
payload,
deadline_s=60.0,
per_attempt_s=30.0,
max_attempts=5,
base=0.5,
cap=10.0,
):
deadline = time.monotonic() + deadline_s
for attempt in range(1, max_attempts + 1):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise DeadlineExceeded(f"budget spent before attempt {attempt}")
attempt_timeout = httpx.Timeout(min(per_attempt_s, remaining))
try:
resp = client.post(url, json=payload, timeout=attempt_timeout)
except httpx.TransportError: # includes every httpx timeout type
if attempt == max_attempts:
raise
else:
if resp.status_code < 400:
return resp
if resp.status_code not in RETRYABLE_STATUS or attempt == max_attempts:
resp.raise_for_status()
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
if delay >= deadline - time.monotonic():
raise DeadlineExceeded(f"no time left to wait after attempt {attempt}")
time.sleep(delay)
calls = {"n": 0}
def handler(request: httpx.Request) -> httpx.Response:
calls["n"] += 1
if calls["n"] < 3:
return httpx.Response(503)
return httpx.Response(200, json={"ok": True})
client = httpx.Client(transport=httpx.MockTransport(handler))
resp = post_with_deadline(client, "https://example.test/v1/chat", {}, base=0.01)
print(resp.status_code, "after", calls["n"], "calls")The first two calls return 503, the third succeeds, and the script prints 200 after 3 calls.
Edge cases to plan for
The server may still be working. When a client timeout fires, the provider often keeps generating and may bill you for the tokens. Your timeout ends your wait. It does not cancel the work. For requests with side effects, such as a tool call that creates a record, a retry after a timeout can run the action twice. The idempotency chapter covers how to make that safe.
Timeouts are not equal to 408. A timeout in the client raises an exception. It produces no status code at all. A 408 or 504 is the server or a proxy telling you it timed out. Your retry logic must handle both forms, which is why the loop above catches httpx.TransportError and also checks the status set.
Async code needs its own cap. In asyncio, wrap the whole operation in asyncio.timeout(deadline_s) (Python 3.11 and later) or asyncio.wait_for. This cancels the task even if a library is stuck somewhere its own timeouts do not reach.
import asyncio
async def with_deadline(coro, seconds: float):
try:
async with asyncio.timeout(seconds):
return await coro
except TimeoutError:
raise TimeoutError(f"operation exceeded {seconds} seconds") from NoneNested deadlines should shrink. If your service is called by another service with a 20-second limit, your own deadline must be shorter than 20 seconds. Pass the remaining time down and never reset it. Otherwise your retries keep running after the caller has already given up and moved on.
Pass the timeout to the SDK. Most provider SDKs accept a timeout value, and many accept an httpx.Timeout object. A later chapter covers SDK retry settings, but the point holds here: SDK retries multiply the SDK timeout in the same way as your own loop.
Summary of the rules
- Set a per-attempt timeout on every call, and set connect separately from read.
- Add an overall deadline that covers all attempts and pauses.
- Cap each attempt to the time remaining, and refuse to sleep past the deadline.
- Give streaming calls a total limit, because the read timeout only measures gaps.
- Remember that a timeout stops your wait but may not stop the provider's work.
Exercise
A streaming chat call is configured with httpx.Timeout(read=30.0). The model streams tokens steadily for 4 minutes and the call completes normally. Why did no timeout fire, and what would you add so the call cannot run past 90 seconds?
Show answer
The read timeout in httpx limits the wait between chunks of data, not the total duration. Tokens arrived more often than every 30 seconds, so the timer reset each time. To enforce a total limit, add an overall deadline: either track time.monotonic() while iterating over the stream and stop once 90 seconds have passed, or wrap the whole streaming operation in asyncio.timeout(90) in async code.
Exercise
Your service must answer within 20 seconds. You use a per-attempt timeout of 15 seconds and up to 4 attempts. Is this configuration sound, and how would you change it?
Show answer
No. A single slow attempt takes 15 of the 20 seconds, so a retry cannot finish, and the worst case is far over budget (4 x 15 seconds plus pauses). Set an overall deadline of about 18 seconds, below the caller's limit, and a per-attempt timeout near the 99th percentile latency of healthy calls, for example 8 seconds. Cap each attempt to the remaining time, so at most two attempts fit. If healthy calls need close to 15 seconds, retries cannot help and you should use a fallback or raise the caller's limit.