Sub topic 4
Setting timeouts and overall deadlines
This chapter assumes you can call an LLM API from Python with httpx or an SDK, and that you know how exceptions work. Retries are covered in later chapters. Here the goal is to make sure no single call, and no chain of retries, can run forever.
Why a default is not enough
A network call can stall without failing. The server may accept the connection and then say nothing for minutes. Without a timeout, your program waits for as long as the operating system allows. Some HTTP libraries have no timeout by default, and SDK defaults are often long, because LLM responses can legitimately take a while.
A timeout turns a stall into an exception. That exception is a temporary failure, so it is usually retryable.
The kinds of timeout
An HTTP request has several phases, and each can have its own limit.
| Timeout | What it limits | Typical failure |
|---|---|---|
| Connect | Opening the TCP and TLS connection | Network down, host unreachable |
| Write | Sending the request body | Slow upload of a large prompt |
| Read | Waiting for the next bytes from the server | Model is slow to start or stalls |
| Pool | Waiting for a free connection in the client | Too many concurrent requests |
In httpx, the read timeout applies to each wait for data, not to the whole response. A server that sends one byte every few seconds can keep a read timeout from ever firing. For this reason a per-request timeout is not a deadline.
import httpx
timeout = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)
client = httpx.Client(timeout=timeout)Keep connect short, because a healthy network connects in well under a second. Make read longer, because the model may spend a while generating before the first byte arrives. With streaming, the first token usually comes quickly, so you can use a shorter read timeout there.
Overall deadlines
A deadline is the latest moment at which the whole operation must be finished, including every retry and every sleep. Without one, five attempts at 30 seconds each, plus backoff, can take over three minutes. That is longer than most users or upstream services will wait.
Store the deadline as an absolute time on a monotonic clock. Before each attempt, compute how much time remains. Give the attempt no more than that, and stop if too little is left.
import random
import time
import httpx
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
class DeadlineExceeded(Exception):
pass
def post_with_deadline(client, url, payload, deadline_s=60.0, per_try_s=30.0, max_attempts=5):
deadline = time.monotonic() + deadline_s
for attempt in range(1, max_attempts + 1):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise DeadlineExceeded(f"deadline hit before attempt {attempt}")
try:
resp = client.post(url, json=payload, timeout=min(per_try_s, remaining))
if resp.status_code < 400:
return resp
if resp.status_code not in RETRYABLE_STATUS:
resp.raise_for_status()
except httpx.TimeoutException:
pass # a timeout counts as a temporary failure
if attempt == max_attempts:
break
delay = random.uniform(0, min(8.0, 0.5 * 2 ** (attempt - 1)))
if time.monotonic() + delay >= deadline:
raise DeadlineExceeded("not enough time left for another attempt")
time.sleep(delay)
raise DeadlineExceeded("out of attempts")The key line is timeout=min(per_try_s, remaining). Each attempt is capped by both its own limit and the time left in the whole operation.
Common mistakes
- Relying on SDK defaults without checking them. Read the documented values and set your own.
- Using
time.time()for deadlines. System clock changes can break it. Usetime.monotonic(). - Letting a
Retry-Aftervalue push the wait past the deadline. Compare the delay with the remaining time first. - Setting one global timeout for both short classification calls and long generation calls. Choose timeouts per use case.
Exercise
A request uses httpx with read=30. The server sends one small chunk every 20 seconds for ten minutes. Does the read timeout fire, and what would you add to bound the total time?
Show answer
No. Each chunk arrives before the 30 second read limit, so the timer resets every time. Add an overall deadline, stored as a monotonic timestamp. Check it while reading, or wrap the call in an enclosing limit such as asyncio.timeout in async code, and cancel the request when the deadline passes.
Exercise
Why should the sleep before a retry be checked against the deadline, instead of only checking the deadline at the start of each attempt?
Show answer
If the delay is longer than the time left, the program would sleep past the deadline and then have no time to make the attempt. Checking before sleeping lets you fail immediately with a clear error instead of wasting the remaining time.