The Problem: "It Streams on My Machine"
A very common sequence when adding an AI chat feature to an internal tool goes like this. Locally, the answer types itself out token by token and feels instant. Then it's deployed behind nginx and a load balancer, and users report that nothing happens for ten seconds, then the whole answer appears at once. A few days later the bill shows tokens being generated for people who had already closed the tab, and someone notices that half-finished code blocks make the chat UI flicker.
A large language model (LLM) can take ten seconds or more to write a long answer. Streaming fixes the perceived latency: the first words appear in a few hundred milliseconds and the rest flows in as the model generates it. But streaming touches every layer between the model and the browser, and each layer has its own way of breaking it.
This guide builds a streaming endpoint with FastAPI and Server-Sent Events (SSE), then covers the parts that matter in production: errors mid-stream, client disconnects, proxies that buffer, idle timeouts, saving the final answer and counting tokens.
Why Server-Sent Events?
You have three main options for pushing data to a browser:
| Option | Direction | Best for |
|---|---|---|
| Long response (chunked HTTP) | Server → client | Simple streams for scripts and CLIs |
| Server-Sent Events | Server → client | Token streams, progress updates, notifications |
| WebSockets | Both directions | Chat rooms, collaborative editing, games |
LLM output only flows one way, so SSE is usually the right fit. It runs over plain HTTP, works through most proxies, and has a tiny wire format. If you do need two-way communication, see real-time features with WebSockets.
The SSE wire format
An SSE stream is text with Content-Type: text/event-stream. Each event is one or more field: value lines followed by a blank line:
event: token
data: {"text": "Hello"}
event: token
data: {"text": " world"}
event: done
data: {}
That's the whole protocol. data carries the payload, event names the event type, and a blank line ends each event.
A Minimal Streaming Endpoint
# app/main.py
import json
import os
from collections.abc import AsyncIterator
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
app = FastAPI()
client = AsyncOpenAI()
MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini")
class ChatRequest(BaseModel):
message: str = Field(min_length=1, max_length=8000)
def sse(event: str, data: dict) -> str:
"""Format one Server-Sent Event."""
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def generate(message: str) -> AsyncIterator[str]:
stream = await client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": message}],
stream=True,
)
async for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content
if delta:
yield sse("token", {"text": delta})
yield sse("done", {})
@app.post("/chat/stream")
async def chat_stream(req: ChatRequest) -> StreamingResponse:
return StreamingResponse(
generate(req.message),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no", # tell nginx not to buffer the stream
},
)
Test it with curl. The -N flag disables curl's own buffering:
curl -N -X POST http://localhost:8000/chat/stream \
-H "Content-Type: application/json" \
-d '{"message": "Explain HTTP caching in three sentences."}'
You should see event: token lines arrive one after another.
Handling Errors Mid-Stream
Once streaming starts, the HTTP status code has already been sent as 200. You can't switch to a 500 halfway through. Instead, send an error event and close the stream so the client can show a useful message.
import logging
logger = logging.getLogger(__name__)
async def generate(message: str) -> AsyncIterator[str]:
try:
stream = await client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": message}],
stream=True,
)
async for chunk in stream:
if chunk.choices and (delta := chunk.choices[0].delta.content):
yield sse("token", {"text": delta})
yield sse("done", {})
except Exception:
logger.exception("LLM stream failed")
yield sse("error", {"message": "The model stopped responding. Please try again."})
Validate everything you can before the stream starts: authentication, input size, rate limits. Those failures should still return proper 4xx status codes. The rate limiting guide is especially relevant here, because streaming endpoints are expensive.
Stopping Work When the Client Disconnects
If a user closes the tab, you want to stop paying for tokens nobody will read. Check request.is_disconnected() inside the generator:
from fastapi import Request
async def generate(message: str, request: Request) -> AsyncIterator[str]:
stream = await client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": message}],
stream=True,
)
try:
async for chunk in stream:
if await request.is_disconnected():
logger.info("Client disconnected, stopping generation")
break
if chunk.choices and (delta := chunk.choices[0].delta.content):
yield sse("token", {"text": delta})
else:
yield sse("done", {})
finally:
await stream.close() # release the upstream HTTP connection
@app.post("/chat/stream")
async def chat_stream(req: ChatRequest, request: Request) -> StreamingResponse:
return StreamingResponse(
generate(req.message, request),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
The for ... else sends done only when the loop finishes normally, not after a break.
Keeping Connections Alive
Some proxies and load balancers close connections that stay silent for 30 to 60 seconds. That can happen while a reasoning-heavy model "thinks" before producing its first token. SSE supports comment lines that start with a colon. Clients ignore them, but they keep the connection busy.
import asyncio
async def with_heartbeat(source: AsyncIterator[str], interval: float = 15.0) -> AsyncIterator[str]:
"""Interleave SSE comment heartbeats into a stream."""
queue: asyncio.Queue[str | None] = asyncio.Queue()
async def pump() -> None:
try:
async for item in source:
await queue.put(item)
finally:
await queue.put(None)
task = asyncio.create_task(pump())
try:
while True:
try:
item = await asyncio.wait_for(queue.get(), timeout=interval)
except asyncio.TimeoutError:
yield ": keep-alive\n\n"
continue
if item is None:
break
yield item
finally:
task.cancel()
Wrap your generator with with_heartbeat(generate(...)) when you return the StreamingResponse.
Consuming the Stream in the Browser
The browser's built-in EventSource only supports GET requests. For a POST with a JSON body, read the stream with fetch and parse events yourself. It's only a few lines:
type StreamHandlers = {
onToken: (text: string) => void;
onDone?: () => void;
onError?: (message: string) => void;
};
export async function streamChat(message: string, handlers: StreamHandlers, signal?: AbortSignal) {
const res = await fetch("/chat/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message }),
signal,
});
if (!res.ok || !res.body) throw new Error(`Request failed: ${res.status}`);
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
// Events are separated by a blank line
let boundary: number;
while ((boundary = buffer.indexOf("\n\n")) !== -1) {
const raw = buffer.slice(0, boundary);
buffer = buffer.slice(boundary + 2);
let event = "message";
let data = "";
for (const line of raw.split("\n")) {
if (line.startsWith("event:")) event = line.slice(6).trim();
else if (line.startsWith("data:")) data += line.slice(5).trim();
}
if (!data) continue; // heartbeat comment
const payload = JSON.parse(data);
if (event === "token") handlers.onToken(payload.text);
else if (event === "done") handlers.onDone?.();
else if (event === "error") handlers.onError?.(payload.message);
}
}
}
Pass an AbortController's signal so a "Stop generating" button can cancel the request. On the server, that shows up as a disconnect and the generation stops.
Tip: Append tokens to a buffer and render with
requestAnimationFrameinstead of updating the DOM for every token. At high token rates, per-token re-renders get expensive. The React performance guide covers the general techniques.
Deployment Gotchas
Streaming works perfectly locally and then "doesn't stream" in production more often than you'd expect. The usual culprits:
- Proxy buffering. nginx buffers responses by default. The
X-Accel-Buffering: noheader disables it per response, or setproxy_buffering off;for the location. - Compression middleware. GZip middleware can hold data until it has a full block. Exclude
text/event-streamfrom compression. - Serverless timeouts. Some platforms cap response duration. Check the limits before you deploy. The deployment guide compares common hosts.
- Worker count. Each open stream holds a connection for its whole duration. Async workers handle this well, but load-test with realistic stream lengths.
Production Gotchas (and What to Do About Them)
Save the answer, including partial ones
The stream is ephemeral, but your conversation history isn't. Accumulate tokens on the server while you stream, and persist the full text when the stream ends. If the client disconnects halfway, save what was generated with a flag, so reloading the page shows a clear "response interrupted" state instead of nothing.
async def generate(message: str, request: Request, conversation_id: str) -> AsyncIterator[str]:
parts: list[str] = []
completed = False
try:
async for event, text in stream_tokens(message, request): # your streaming loop
parts.append(text)
yield sse(event, {"text": text})
completed = True
yield sse("done", {})
finally:
await save_assistant_message(conversation_id, "".join(parts), completed=completed)
Count tokens for streamed responses
Usage numbers usually arrive with a non-streamed response. When streaming, many providers can include usage in a final chunk if you ask. With the OpenAI SDK that's stream_options={"include_usage": True}, and the last chunk then carries usage with an empty choices list. That's also why the loop above checks if not chunk.choices. Without this, cost tracking and per-user quotas quietly undercount.
Half-rendered Markdown
Mid-stream, the text often contains an opened code fence with no closing fence yet, or half a table. Rendering that as Markdown on every token makes the UI jump around. Close any unclosed fence before rendering, and only re-render on animation frames:
function renderableMarkdown(partial: string): string {
const fences = (partial.match(/```/g) || []).length;
return fences % 2 === 1 ? partial + "\n```" : partial;
}
Idle timeouts are not just nginx
Load balancers have idle timeouts too. For example, an AWS Application Load Balancer defaults to 60 seconds. Reasoning models can stay silent longer than that before the first token. The heartbeat from earlier covers it, as long as the interval is comfortably shorter than every timeout in the chain.
Testing streaming endpoints
Use httpx.AsyncClient with client.stream(...) in tests and assert on the sequence of events, including the error and done events. Mock the LLM client with an async generator so tests are fast and deterministic.
Conclusion
Streaming is one of the highest-impact UX improvements you can make to an LLM feature, and with FastAPI it's only a few dozen lines. Use SSE for one-way token streams, validate before you start streaming, send errors as events, stop work when clients leave, and check your proxy configuration before launch.
Resources:
Related Articles:
