Why SSE fits LLM streaming
To stream LLM responses with SSE in FastAPI is the right call for a chat UI: the server produces text in pieces, the browser renders it. WebSockets give you two-way messaging you do not need here, which adds protocol overhead and connection-state code for zero benefit. Polling is worse: the client hammers your server for text that mostly is not there yet. SSE is plain HTTP, reconnects on its own, and every load balancer already speaks it.
| Approach | Direction | Reconnect | Overhead |
|---|---|---|---|
| Server-Sent Events | Server to client | Built in | Low, plain HTTP |
| WebSockets | Two-way | Manual | Medium, upgrade + frames |
| Polling | Client asks repeatedly | n/a | High, wasted requests |
What actually travels over the wire
An SSE response is a normal HTTP response with Content-Type: text/event-stream. The body is a sequence of events separated by blank lines. Each event has a data: field with the payload:
data: {"text":"The quick brown"}
data: {"text":" fox jumps"}
event: done
data: {}
Three details shape the code below. First, one provider event does not equal one token: it can hold half a word or several tokens, and network chunks do not line up with events either. Your UI should append deltas in order and never hunt for word boundaries inside them. Second, lines starting with a colon are comments, which is what we use for heartbeats. Third, a named event: field lets the client route different event types without extra parsing.
Step 1: Stream the LLM provider with httpx
Most LLM providers expose an OpenAI-compatible /chat/completions endpoint with a stream: true option that returns SSE itself. Your server’s job is to open that stream, normalize the chunks, and forward them. Keep the provider call in its own function so swapping models or vendors means editing one place. Use httpx in async streaming mode, because the synchronous requests library blocks the event loop and silently stalls every other request while a token stream is open:
import json
import httpx
LLM_API_URL = "https://api.example.com/v1/chat/completions"
LLM_API_KEY = "sk-your-key-here" # load from env in real code
async def stream_llm(messages: list[dict], model: str):
"""Yield SSE-formatted events from the provider, chunk by chunk."""
async with httpx.AsyncClient(
timeout=httpx.Timeout(60.0, connect=10.0)
) as client:
async with client.stream(
"POST",
LLM_API_URL,
headers={"Authorization": f"Bearer {LLM_API_KEY}"},
json={"model": model, "messages": messages, "stream": True},
) as response:
response.raise_for_status()
async for line in response.aiter_lines():
if not line.startswith("data:"):
continue
payload = line[5:].strip()
if payload == "[DONE]":
break
try:
chunk = json.loads(payload)
delta = chunk["choices"][0]["delta"].get("content")
except (KeyError, IndexError, ValueError):
continue
if delta:
yield f"data: {json.dumps({'text': delta})}nn"
aiter_lines() handles the case where the provider’s TCP chunks split an event in half, so you never emit broken JSON. The [DONE] sentinel ends the loop cleanly. Malformed chunks are skipped rather than crashing the stream, because a 60-second generation is not worth restarting over one garbled delta. And the key lives on the server: the browser never sees the provider URL or credentials.
Step 2: The FastAPI streaming endpoint
Wrap the generator in a StreamingResponse with the SSE content type, and detect dead clients with request.is_disconnected() so you break the loop and stop paying for tokens nobody will read:
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
app = FastAPI()
class ChatRequest(BaseModel):
messages: list[dict]
model: str = "default"
@app.post("/chat/stream")
async def chat_stream(body: ChatRequest, request: Request):
async def event_generator():
try:
async for event in stream_llm(body.messages, body.model):
if await request.is_disconnected():
break # client left; stop burning provider tokens
yield event
except Exception:
yield f"event: errorndata: {json.dumps({'message': 'upstream failed'})}nn"
yield "event: donendata: {}nn"
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no", # tells nginx not to buffer this response
},
)
Notice the endpoint is a POST. Chat requests carry a message history in the body, and GET URLs are too small and too leaky for that. Also note the error event: when the provider fails mid-stream, the client gets a named error event it can react to instead of a connection that just goes silent.
Step 3: Consume the stream in the browser
Most tutorials use the browser’s EventSource API, but it can only issue GET requests. Since the endpoint takes a JSON body, EventSource cannot call it. Use fetch with a ReadableStream reader instead:
async function streamChat(messages) {
const output = document.getElementById("output");
const res = await fetch("/chat/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// One network chunk can hold half an event or five glued together,
// so split on the blank line and keep the remainder for next time.
const events = buffer.split("nn");
buffer = events.pop();
for (const event of events) {
const dataLine = event.split("n").find((l) => l.startsWith("data:"));
if (!dataLine) continue; // heartbeat comment, ignore
const payload = JSON.parse(dataLine.slice(5));
output.textContent += payload.text ?? "";
}
}
}
reader.read() returns whatever bytes arrived, never aligned to event boundaries. Splitting on nn and carrying the remainder across iterations handles both halves and globs.
Step 4: Keep idle connections alive with heartbeats
An LLM can pause for seconds between bursts, and proxies drop connections that look idle. SSE comments (lines starting with :) are ignored by parsers, which makes them good pings. Run the provider stream and a heartbeat timer in parallel, merged into one queue:
import asyncio
async def event_generator_with_heartbeat(body, request):
queue: asyncio.Queue = asyncio.Queue()
stop = asyncio.Event()
async def producer():
try:
async for event in stream_llm(body.messages, body.model):
await queue.put(event)
finally:
stop.set()
async def heartbeat():
while not stop.is_set():
await asyncio.sleep(15)
await queue.put(": pingnn")
prod = asyncio.create_task(producer())
hb = asyncio.create_task(heartbeat())
try:
while not (stop.is_set() and queue.empty()):
if await request.is_disconnected():
break
try:
yield await asyncio.wait_for(queue.get(), timeout=1.0)
except asyncio.TimeoutError:
continue
finally:
prod.cancel()
hb.cancel()
Fifteen seconds is a reasonable ping interval: frequent enough to keep most proxies and load balancers from timing out, quiet enough to add no meaningful traffic. The finally block matters. Without it, a client that closes the tab mid-generation leaves both tasks running against a dead queue.
Production checklist
Streaming works on localhost and breaks behind infrastructure. Run through these before shipping:
- Turn off proxy buffering. nginx buffers upstream responses by default and will hold your whole stream until it finishes, which looks exactly like no streaming at all. Set
proxy_buffering off;andproxy_cache off;in the location block, or send theX-Accel-Buffering: noresponse header like the example above does. The header travels with your app, so it survives config rewrites. - Raise idle timeouts. A long generation with sparse heartbeats still counts as an idle connection to some proxies. Give the stream room:
proxy_read_timeout 300s;on nginx, and match it on anything else in the chain (CDN, ingress). - Run enough workers, then watch them. Each open stream holds a connection and an async task for its whole lifetime. Asyncio handles hundreds of concurrent streams per worker; a sync worker pool starves fast. Size workers for peak concurrent streams, not requests per second, and alert on saturation.
- Handle cancellation end to end. On the client, call
reader.cancel()(or abort the fetch) when the user hits stop. On the server,request.is_disconnected()notices the broken pipe on the next loop iteration, which ends the provider request too. Test the stop button; without it, users close the tab, which is the one case the disconnect check catches last. - Fail loudly, not silently. If the provider times out or returns a 4xx, emit a named
errorevent with a short message before ending the stream. A chat UI that stops mid-sentence with no explanation reads as a broken product; a small error bubble reads as an honest one. - Do not trust content boundaries. Deltas can split words, code fences, or markdown syntax. If you render markdown, re-render the whole accumulated buffer per event rather than appending HTML fragments, or you will ship half-closed tags.
Mistakes that quietly break streaming
| Mistake | Symptom | Fix |
|---|---|---|
Using requests instead of httpx async |
Whole server stalls during long streams | httpx.AsyncClient with client.stream() |
EventSource against a POST endpoint |
Request body never sent; 422 errors | fetch + ReadableStream reader |
| Forgetting proxy buffering | Text arrives all at once at the end | X-Accel-Buffering: no or proxy_buffering off |
| No disconnect detection | Paying for tokens after the user leaves | Check request.is_disconnected() in the loop |
| Appending HTML fragments per delta | Broken markdown, half-closed tags | Re-render the full buffer on each event |
What to build next
You now have a complete loop: an async provider stream, a FastAPI endpoint that forwards it as clean SSE with heartbeats, and a browser client that survives misaligned network chunks. Next upgrades that pay off: retry with backoff on provider errors, per-user rate limiting, and logging time-to-first-token so you spot slowdowns before users do. Start with the checklist above, then measure.