Sub topic 14
Timeouts, Input Limits, and Observability
This chapter covers the last concept in the plan: the limits and signals that keep a streaming LLM endpoint safe to run in production. It assumes you can read async Python, you know a basic FastAPI route and Pydantic model, and you have built the streaming /chat endpoint from the earlier chapters. It also assumes you have seen how the endpoint handles client disconnects and errors after the response has started.
Why an LLM endpoint needs limits
A streaming endpoint holds a connection open for as long as the model keeps producing tokens. Each open stream uses a worker task, a socket, an upstream connection to the model provider, and money. Without limits, three things can go wrong:
- A slow or stalled upstream call keeps a stream open forever.
- A very large prompt, or a very long answer, costs more than you planned.
- When something fails, you have no record of what happened.
The fixes fall into three groups: timeouts (bound time), input and output limits (bound size), and observability (see what happens). Each group maps to a place in the code you already have.
Input limits
The cheapest limit is the one you apply before streaming starts. Once the first byte of a streaming response is sent, the status code is fixed at 200, so a bad request must be rejected earlier. Pydantic does this for you.
The request model from earlier already has min_length=1 and max_length=4000 on prompt. Those bounds are in characters, not tokens. Characters are a rough stand-in for cost, which is usually good enough as a first guard.
Two more limits are worth adding:
- Request body size. Pydantic validates the body after it is parsed, so a huge body is still read into memory first. Enforce a maximum body size at the reverse proxy (for example
client_max_body_sizein nginx) so oversized requests never reach Python. - Output size. Pass
max_tokensto the model call so that a single request cannot generate an unbounded answer.
A failed validation returns a normal 422 response with details, because no streaming has begun. That is the right behavior. Do not move validation inside the generator, where it could only be reported as an error event.
Timeouts
There are three different timeouts, and they protect against different problems.
| Timeout | What it bounds | Where to set it |
|---|---|---|
| Connect or request timeout on the LLM client | Time to reach the provider and receive response headers | `AsyncOpenAI(timeout=...)` |
| Idle (per-chunk) timeout | Time between two chunks while streaming | Your generator |
| Total stream deadline | Whole life of one response | Your generator |
The first one is a client setting. The OpenAI Python client accepts a timeout argument, which can be a number of seconds or an httpx.Timeout object. For a streaming call, the read timeout applies between received chunks, so a provider that goes silent for too long raises an error instead of hanging.
The second and third are your responsibility. A provider can keep sending tiny chunks forever, which never trips a read timeout. A total deadline stops that.
An idle timeout and total deadline in the generator
Python 3.11 added asyncio.timeout(), which cancels the code inside its block when the deadline passes. You can wrap the whole stream in one. For the per-chunk wait, asyncio.wait_for around __anext__() works.
import asyncio
import json
import logging
import os
import time
from functools import lru_cache
import httpx
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
logger = logging.getLogger("chat")
logging.basicConfig(level=logging.INFO)
app = FastAPI()
IDLE_TIMEOUT_S = 15.0
TOTAL_TIMEOUT_S = 60.0
MAX_OUTPUT_TOKENS = 800
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI(
timeout=httpx.Timeout(connect=5.0, read=IDLE_TIMEOUT_S, write=10.0, pool=5.0)
)
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def token_events(client: AsyncOpenAI, prompt: str):
started = time.monotonic()
chunks = 0
outcome = "ok"
try:
async with asyncio.timeout(TOTAL_TIMEOUT_S):
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
stream=True,
max_tokens=MAX_OUTPUT_TOKENS,
)
iterator = stream.__aiter__()
while True:
try:
chunk = await asyncio.wait_for(
iterator.__anext__(), timeout=IDLE_TIMEOUT_S
)
except StopAsyncIteration:
break
if chunk.choices and chunk.choices[0].delta.content:
chunks += 1
yield sse("token", {"text": chunk.choices[0].delta.content})
yield sse("done", {})
except TimeoutError:
outcome = "timeout"
yield sse("error", {"message": "generation timed out"})
except asyncio.CancelledError:
outcome = "disconnected"
raise
except Exception:
outcome = "error"
logger.exception("generation failed")
yield sse("error", {"message": "generation failed"})
finally:
logger.info(
"chat_stream outcome=%s chunks=%d duration_s=%.2f",
outcome,
chunks,
time.monotonic() - started,
)
@app.post("/chat")
async def chat(body: ChatRequest, client: AsyncOpenAI = Depends(get_client)):
return StreamingResponse(
token_events(client, body.prompt),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)Read the generator in order:
asyncio.timeout(TOTAL_TIMEOUT_S)sets the deadline for the whole stream. When it passes, the block is cancelled and the context manager raisesTimeoutError.asyncio.wait_for(..., timeout=IDLE_TIMEOUT_S)bounds the wait for each chunk. It also raisesTimeoutError(an alias ofasyncio.TimeoutErrorsince Python 3.11).StopAsyncIterationis how an async iterator signals the end, so the loop catches it and breaks.- Each failure path sets
outcomeand, for timeouts and errors, yields anerrorevent. A client that is still connected learns what happened. - The
finallyblock runs on every path and writes one log line.
Note that asyncio.timeout() needs Python 3.11 or newer. On older versions, use asyncio.wait_for on a helper coroutine, or the async-timeout package.
Why `CancelledError` is re-raised
When a client disconnects, Starlette cancels the task running your generator. That arrives as asyncio.CancelledError at the current await. You should record it, then re-raise it. If you swallow it, the task may keep running work nobody is waiting for. In Python 3.8 and later, CancelledError derives from BaseException, so the broad except Exception does not catch it by accident. The explicit branch is there so you can label the outcome.
Observability
You cannot tune limits you cannot see. A streaming endpoint has some measurements that an ordinary endpoint does not, because "how long did the request take" is no longer one number.
Useful measurements for each stream:
- Time to first token. The delay between the request arriving and the first
tokenevent. This is the number streaming exists to improve, so it deserves its own metric. - Total duration. Time from start to the end of the stream.
- Chunk count. A rough proxy for output length.
- Outcome. One of
ok,timeout,error, ordisconnected.
The generator above logs outcome, chunk count, and duration in the finally block. To add time to first token, record the clock when the first chunk is yielded:
import time
class StreamStats:
def __init__(self) -> None:
self.started = time.monotonic()
self.first_token_s: float | None = None
self.chunks = 0
def on_token(self) -> None:
self.chunks += 1
if self.first_token_s is None:
self.first_token_s = time.monotonic() - self.started
def summary(self) -> dict:
return {
"chunks": self.chunks,
"ttft_s": self.first_token_s,
"duration_s": time.monotonic() - self.started,
}
stats = StreamStats()
stats.on_token()
stats.on_token()
print(stats.summary())In the generator, call stats.on_token() just before each yield sse("token", ...) and log stats.summary() in finally. Because finally runs for success, error, timeout, and disconnect alike, every request produces exactly one summary.
What to log and what to leave out
Log metadata, not content. Prompts and answers often contain personal or confidential text, and logs are copied to many systems with weaker access control than your database. Log lengths, counts, durations, and a request ID. If you must log prompts for debugging, do it behind a flag, redact, and set a short retention period.
Two other habits help:
- Use
logger.exceptioninside the error handler so the traceback is kept, while the client sees only a generic message. Do not send exception text to the client, since it may reveal internals. - Attach a request ID to each log line so you can follow one stream across the proxy, your app, and the provider.
Common mistakes
- Putting the only timeout on the client. A browser or script that disconnects stops the work only if your server notices. Keep server-side deadlines.
- Relying on a read timeout alone. A provider that trickles one chunk every few seconds never trips it. Add a total deadline.
- Validating inside the generator. By then the status is already 200. Validate in the request model.
- Counting characters and calling it tokens. Character limits are a cheap guard, not a cost guarantee. Set
max_tokenson the call too. - Logging full prompts by default. This is a privacy risk and fills logs quickly.
- Forgetting the
finallyblock. Without it, disconnects and exceptions produce no record.
Exercise
A stream stays open for ten minutes because the provider sends one small chunk every ten seconds. The client has a 15-second read timeout. Why does the read timeout not stop it, and what do you add to the endpoint to fix this?
Show answer
The read timeout only measures the gap between chunks, and each gap here is ten seconds, which is under 15 seconds, so it never fires. Add a total deadline for the whole stream, for example async with asyncio.timeout(60): around the streaming loop, and catch TimeoutError to send an error event and log the outcome as timeout. Setting max_tokens on the model call also bounds how long the answer can get.
Exercise
Why should prompt length be enforced by the Pydantic request model and not inside the async generator?
Show answer
Pydantic validation runs before the response starts, so a bad request gets a normal 422 status with details. Inside the generator, the 200 status and headers have already been sent, so the only option is an error event on a response that looks successful, and the request has already used server resources.