Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
The whole answer shows nothing for 2.67 s; the stream shows its first words after 0.60 s. Build the server side: a generator of sources, token and done events, an SSE endpoint with two no-buffering headers and a disconnect check, a fetch reader in the page, and a WebSocket that sends the same events.
What you will learn
- Turn a RAG answer into a stream of sources, token and done events
- Serve the events as Server-Sent Events with buffering off and a disconnect check
- Read a POST stream in the browser with fetch and a buffer for half-arrived events
- Choose between SSE and a WebSocket for an AI feature
Before you start
- Streaming and Error Handling for LLM Calls
- FastAPI for AI Services
Chat apps write their answers word by word. That isn't decoration. With a normal endpoint the page shows an empty box until the whole answer is ready, and users think the app froze. In this article we stream an answer from a FastAPI service to the browser: the sources first, then the words over Server-Sent Events, then the same events over a WebSocket. And we stop the work when the user closes the tab.
The project is docs-answer, a help-centre RAG service, now with a small web page. It runs with a stand-in test model, so you need no key. The stand-in waits 600 ms before the first word, like a model thinking, then gives one word every 60 ms. Client-side streaming from an SDK is covered in Streaming and Error Handling for LLM Calls; here we build the server.
Waiting for the whole answer
python demo.py timing
stand-in: 600 ms before the first word, 60 ms per word
/api/ask first words 2.67s whole answer 2.67s
/api/ask/stream first words 0.60s whole answer 2.67s
Streaming doesn't make the model faster. Both answers end at 2.67 s. It makes the wait feel much shorter, because the user starts reading straight away.
The answer as a list of events
def prepare(question: str, retriever: KeywordRetriever, k: int) -> tuple[str, list[Source]]:
hits = retriever.search(question, k)
sources = [Source(source=h.chunk.source, heading=h.chunk.heading, score=h.score) for h in hits]
return build_prompt(question, hits), sources
def stream_answer(question: str, retriever: KeywordRetriever, model: Model, k: int = 3) -> Iterator[dict]:
"""The same pipeline as events: the sources first (they are ready at once), then each piece, then done."""
prompt, sources = prepare(question, retriever, k)
yield {"type": "sources", "sources": [s.model_dump() for s in sources]}
for piece in model.stream(prompt):
yield {"type": "token", "text": piece}
yield {"type": "done", "model": model.name}
prepare does the retrieval and builds the prompt; the normal answer and the stream share it. Retrieval is quick, so the first event is the sources, and the page can show where the answer comes from before the model has written a word. Then one token event per piece, and a done event with the model name. It's a generator, so every event goes out the moment it exists.
The pieces come from the model. For the real model in services/llm.py we pass stream=True, and each chunk carries a delta:
def stream(self, prompt: str) -> Iterator[str]:
chunks = self.client.chat.completions.create(
model=self.name, temperature=0, stream=True, messages=[{"role": "user", "content": prompt}])
for chunk in chunks:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
The SSE endpoint
"""Server-Sent Events: one HTTP response that stays open and carries the answer piece by piece."""
import json
from collections.abc import AsyncIterator
from fastapi import APIRouter, Request
from fastapi.responses import StreamingResponse
from starlette.concurrency import iterate_in_threadpool
from ..schemas import AskRequest
from ..services import rag
from .ask import LLM, Retriever
router = APIRouter(prefix="/api", tags=["stream"])
# Without these, a proxy (nginx) or the browser may hold the pieces back and deliver them all at the end.
NO_BUFFERING = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
def sse(event: dict) -> str:
"""One Server-Sent Event: "event: name", "data: json", then a blank line."""
return f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"
@router.post("/ask/stream")
async def ask_stream(body: AskRequest, request: Request, retriever: Retriever, model: LLM) -> StreamingResponse:
async def events() -> AsyncIterator[str]:
# The model call blocks, so each next() runs in a worker thread and the event loop stays free.
async for event in iterate_in_threadpool(rag.stream_answer(body.question, retriever, model, body.top_k)):
if await request.is_disconnected(): # the user closed the tab: stop paying for tokens
break
yield sse(event)
return StreamingResponse(events(), media_type="text/event-stream", headers=NO_BUFFERING)
Four details make this work:
- Two headers turn buffering off. Without them, a proxy like nginx may collect all the pieces and send them at the end, and you're back to waiting.
- The format is tiny. An
event:line, adata:line with the JSON, and a blank line to end it. iterate_in_threadpoolruns each step of the blocking generator in a worker thread, so the server stays free for other users. It's the streaming version of the plain-defrule from FastAPI for AI Services.- Before each event we ask, is the client still there? If the user closed the tab, we stop, and we stop paying for tokens.
What goes over the wire
python demo.py sse "Where do you ship?"
=== sse: The raw Server-Sent Events, timed ===
[stand-in test model, help-centre docs]
200 text/event-stream; charset=utf-8
0.03s event: sources
0.03s data: {"type": "sources", "sources": [{"source": "shipping.md", "heading": "Where we ship", "score": 4.251}, {
0.63s event: token
0.63s data: {"type": "token", "text": "We "}
0.69s event: token
0.69s data: {"type": "token", "text": "ship "}
â‹®
2.45s event: done
2.45s data: {"type": "done", "model": "stand-in"}
The response is a 200 with the content type text/event-stream. The sources event arrives at 0.03 s, pointing at shipping.md, "Where we ship". After the stand-in's 600 ms come the token events, one word each, and at the end the done event. That's 30 token events, and the sources came before any of them.
Reading the stream in the page
async function askSSE(question) {
const response = await fetch("/api/ask/stream", {
method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ question }),
});
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const events = buffer.split("\n\n"); // a blank line ends one event
buffer = events.pop(); // keep a half-arrived event for the next read
for (const block of events) {
const data = block.split("\n").find((line) => line.startsWith("data: "));
if (data) show(JSON.parse(data.slice(6)));
}
}
}
The browser has EventSource for SSE, but it only does GET, and we want to POST a question. So we use fetch and read the body piece by piece as text. A network piece doesn't line up with an event, so we split on the blank line, and the last part may be half an event, so it stays in the buffer until the next read. Each complete event goes to show, which adds the words to the answer box.
The same events over a WebSocket
"""WebSocket: one connection that stays open both ways, so a chat can ask question after question on it."""
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from pydantic import ValidationError
from starlette.concurrency import iterate_in_threadpool
from ..schemas import AskRequest
from ..services import rag
router = APIRouter(tags=["stream"])
@router.websocket("/ws/ask")
async def ws_ask(websocket: WebSocket) -> None:
await websocket.accept()
retriever, model = websocket.app.state.retriever, websocket.app.state.model
try:
while True:
try:
body = AskRequest.model_validate(await websocket.receive_json())
except ValidationError as error: # same rules as the HTTP endpoint, but no 422 here: send an event
await websocket.send_json({"type": "error", "detail": error.errors(include_url=False)[0]["msg"]})
continue
async for event in iterate_in_threadpool(rag.stream_answer(body.question, retriever, model, body.top_k)):
await websocket.send_json(event)
except WebSocketDisconnect:
pass # the browser went away; nothing to clean up
We accept the connection, and it stays open in both directions. In a loop we receive a question as JSON and check it with the same AskRequest schema. There's no 422 on a socket, so an invalid question gets an error event and the loop keeps listening. A valid one gets the same events as before. When the browser goes away, WebSocketDisconnect ends the loop.
python demo.py ws
python demo.py tests
=== ws: Three messages on one WebSocket ===
[stand-in test model, help-centre docs]
you: Where do you ship?
30 token events -> We ship to all 50 United States, to military addresses (APO and FPO) and to Canada. A PO box works for standard shipping only. See "International shipping" below for Canada.
you: How do I reset my password?
35 token events -> On the sign-in page choose "Forgot password" and enter the email address you used to register. We send a reset link to that address. The link works for 30 minutes and can be used once.
you: hi
0 token events -> {'type': 'error', 'detail': 'String should have at least 3 characters'}
7 passed in 1.75s
Three questions on one connection: two answers (test model replies taken from the help centre) and, for "hi", zero tokens and the error event. The seven offline tests pass.
SSE or WebSocket?
| Server-Sent Events | WebSocket | |
|---|---|---|
| Direction | Server to browser | Both ways |
| Protocol | A plain HTTP response | An upgraded connection |
| Proxies, auth | Just work | Need the upgrade allowed all the way through |
| Bad input | 422 before the stream | An error event |
| Use it for | Chat answers (the default) | Stop buttons, voice, live edits |
The events are the same either way: sources, token, done. Use a WebSocket when the client also talks while it listens.
Common mistakes
- Forgetting the no-buffering headers. Locally it streams; behind nginx everything arrives at the end.
- Iterating a blocking generator directly in an async endpoint. It holds the event loop. Wrap it in
iterate_in_threadpool. - Never checking for disconnect. The model keeps generating, and you keep paying, for a tab nobody is looking at.
- Parsing each network read as one event. Pieces split events anywhere. Buffer until the blank line.
Quick recap
| Rule | Why |
|---|---|
| Send the sources first | They're ready at once (0.03 s) |
| Stream token events, one per piece | First words at 0.60 s instead of 2.67 s |
| Turn buffering off with two headers | Proxies would hold the pieces back |
| Stop when the client goes away | No tokens paid for a closed tab |
Try it yourself
- Start the service with
python demo.py web, open the page, click all three buttons and compare "first words after" for each. - Slow the stand-in down with
STANDIN_WORD_MSand watch the words come in. - Send "hi" over the WebSocket and read the error event.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.