Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. AI System Design

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.

Chaand Sheikh

·27 November 2026AI System Design

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
Whole answer vs streamed answer /api/ask blank box answer at 2.67 s /api/ask/stream thinking words flow in first words 0.60 s sources event at 0.03 s 0 s2.67 s
Same total time. The stream lets the user start reading after 0.60 s.

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, a data: line with the JSON, and a blank line to end it.
  • iterate_in_threadpool runs 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-def rule 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 EventsWebSocket
DirectionServer to browserBoth ways
ProtocolA plain HTTP responseAn upgraded connection
Proxies, authJust workNeed the upgrade allowed all the way through
Bad input422 before the streamAn error event
Use it forChat 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

RuleWhy
Send the sources firstThey're ready at once (0.03 s)
Stream token events, one per pieceFirst words at 0.60 s instead of 2.67 s
Turn buffering off with two headersProxies would hold the pieces back
Stop when the client goes awayNo tokens paid for a closed tab

Try it yourself

  1. Start the service with python demo.py web, open the page, click all three buttons and compare "first words after" for each.
  2. Slow the stand-in down with STANDIN_WORD_MS and watch the words come in.
  3. Send "hi" over the WebSocket and read the error event.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 78 of 89

Previous
FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
Next post
Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline

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.

On this page

  • Waiting for the whole answer
  • The answer as a list of events
  • The SSE endpoint
  • What goes over the wire
  • Reading the stream in the page
  • The same events over a WebSocket
  • SSE or WebSocket?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.