Sub topic 14
Timeouts, input limits, and observability
This chapter hardens the streaming endpoint from the previous chapters. It assumes you can read the /chat endpoint, its SSE helper, and the Depends client provider. It also assumes you know how the endpoint handles disconnects and mid-stream errors. It needs Python 3.11 or newer for asyncio.timeout.
Why a streaming endpoint needs limits
A stream can stay open for a long time. Each open stream holds a connection, a task, and an upstream LLM request that costs money. Without limits, one huge prompt, one stalled provider, or one runaway answer can use up your capacity. You can't see any of this unless you log it.
There are three kinds of limit:
| Limit | What it protects against | Where it lives |
|---|---|---|
| Input size | Huge prompts that cost money and slow the first token | Pydantic model, proxy body limit |
| Output size | Very long answers | `max_tokens` on the LLM call |
| Time | Stalled or slow upstream calls | Client timeout and an overall deadline |
Input and output limits
The ChatRequest model already rejects prompts longer than 4000 characters or shorter than one. FastAPI returns a 422 response before the stream starts, so the LLM is never called. Pair this with a body size limit at your reverse proxy, such as client_max_body_size in nginx, so oversized bodies are rejected before they reach Python.
Limit the output too. Pass max_tokens to the LLM call. Without it, the model decides how long to talk.
Two kinds of timeout
The first kind is a timeout on the LLM client. The OpenAI SDK accepts timeout= when you create the client. It guards against a provider that connects but never answers.
The second kind is an overall deadline for the whole stream. A provider can send one chunk every few seconds forever, so the client timeout never fires. asyncio.timeout cancels the block when time runs out and raises TimeoutError. You can then send an error event, as you did for other mid-stream failures.
Logging what happened
Log one line per request, written in a finally block so it runs on success, error, timeout, and disconnect. Include:
- a request ID, so one line can be matched to a client report
- the outcome:
ok,timeout,error, ordisconnected - time to first chunk, which is the number users feel
- total duration and chunk count
- the prompt length, not the prompt itself, so you don't write user text into logs
The complete endpoint
import asyncio
import json
import logging
import os
import time
import uuid
from functools import lru_cache
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("chat")
DEADLINE_SECONDS = 60
MAX_OUTPUT_TOKENS = 500
app = FastAPI()
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI(timeout=30.0, max_retries=1)
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, request_id: str):
start = time.monotonic()
first_chunk = None
chunks = 0
outcome = "ok"
try:
async with asyncio.timeout(DEADLINE_SECONDS):
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
max_tokens=MAX_OUTPUT_TOKENS,
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
if first_chunk is None:
first_chunk = time.monotonic() - start
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 request_id=%s", request_id)
yield sse("error", {"message": "generation failed"})
finally:
logger.info(
"chat request_id=%s outcome=%s prompt_chars=%d chunks=%d "
"first_chunk_s=%s total_s=%.2f",
request_id,
outcome,
len(prompt),
chunks,
"none" if first_chunk is None else f"{first_chunk:.2f}",
time.monotonic() - start,
)
@app.post("/chat")
async def chat(body: ChatRequest, client: AsyncOpenAI = Depends(get_client)):
request_id = uuid.uuid4().hex[:8]
return StreamingResponse(
token_events(client, body.prompt, request_id),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)Common mistakes
- Setting only the client timeout. A slow trickle of chunks never trips it, so you also need the overall deadline.
- Catching
ExceptionbeforeTimeoutError. HereTimeoutErroris listed first, so timeouts get their own outcome. - Swallowing
CancelledError. Re-raise it so the disconnect still stops the task. - Logging only at the start. Without the
finallyblock, failed and cancelled streams leave no record. - Treating
chunksas a token count. A chunk usually holds one token, but not always. Use the provider's usage data if you need exact numbers.
Exercise
A provider sends one token every 20 seconds, and your client timeout is 30 seconds. Which setting stops this stream, and what outcome does the log line show?
Show answer
The 30-second client timeout never fires, because data keeps arriving. The overall deadline (asyncio.timeout(DEADLINE_SECONDS)) stops the stream. It raises TimeoutError, the endpoint sends an error event, and the log line shows outcome=timeout.