FastAPI SSE Streaming Endpoints: Pushing LLM Tokens to the Frontend
Core concepts
- Native SSE in FastAPI (since 0.135.0):
from fastapi.sse import EventSourceResponse, ServerSentEvent. Declareresponse_class=EventSourceResponseon the route and justyielddata from the function. yielda plain object (dict / Pydantic model) → it's JSON-encoded into thedata:field.yield ServerSentEvent(...)→ lets you setevent,id,retryandcomment;raw_datasends a string without JSON encoding (such as[DONE]) and is an alternative todata.- Works with any HTTP method, including POST (LLM chat usually sends the question via POST).
- Older FastAPI versions don't have this class; the community commonly uses
sse-starletteor a hand-writtenStreamingResponse(media_type="text/event-stream").
How it works
EventSourceResponseis a subclass ofStreamingResponse: the response headers go out first, then eachyieldwrites a chunk to the connection.- When the connection is idle, FastAPI sends a keep-alive comment every 15 seconds so proxies don't drop the connection.
- The docs recommend setting
Cache-Control: no-cacheand usingX-Accel-Buffering: noto stop proxies such as Nginx from buffering. - Disconnects and cancellation: when the client disconnects, Starlette stops iterating and cancels the running generator (it receives
asyncio.CancelledErrorat anawait). So write the upstream LLM call insideasync with: on cancellation the context exits and the upstream stream closes too. You can also checkawait request.is_disconnected()yourself.
In practice
python
from collections.abc import AsyncIterable
from fastapi import FastAPI, Request
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel
app = FastAPI()
class Ask(BaseModel):
question: str
@app.post("/chat", response_class=EventSourceResponse)
async def chat(body: Ask, request: Request) -> AsyncIterable[ServerSentEvent]:
async with client.messages.stream(model=MODEL, max_tokens=1024,
messages=[{"role": "user", "content": body.question}]) as stream:
async for text in stream.text_stream:
if await request.is_disconnected(): # belt and braces: stop when the user closes the page
break
yield ServerSentEvent(data={"text": text}, event="token")
final = await stream.get_final_message()
yield ServerSentEvent(data={"stop_reason": final.stop_reason}, event="done")Progress updates for long tasks: the task runs in a worker and writes progress to Redis Pub/Sub or the database; the SSE endpoint only subscribes and forwards. After a disconnect, the frontend resumes with Last-Event-ID (readable in FastAPI with Header()) or simply fetches the latest state.
Common pitfalls
- Doing a long task's real work inside the SSE generator: if the request disconnects, the task is gone. Run long tasks in a worker; SSE only pushes progress.
- State with multiple workers: if progress lives in process memory, an SSE request that lands on another worker can't see it. Share it via Redis / the database.
- Proxy / CDN buffering: works locally, not streaming once deployed. Usually it's proxy buffering or timeout settings.
- Sync blocking code inside the generator: blocks the event loop (see How async def and def Routes Execute).
Common interview questions
- How do you implement SSE in FastAPI? How does
EventSourceResponserelate toStreamingResponse? - When the client disconnects, how do you make sure the upstream LLM request is cancelled too?
- How do you push progress for long tasks in a multi-instance deployment?
- After deployment, streaming output arrives all at once. What could cause that?
How it relates to my projects
- AI Document Review Pipeline: task progress updates + streaming AI explanations in the review console. For the frontend side, see Streaming UI and Long-Running Task Interaction.
To be verified / may go stale
- The "cancel the generator on disconnect" behavior depends on the Starlette version's implementation, and the official SSE tutorial doesn't cover disconnect handling specifically, which is why the example adds
request.is_disconnected()as a fallback. Verify it on your version by disconnecting a curl request midway.
Sources
- FastAPI Docs: Server-Sent Events (Tutorial) — added in 0.135.0,
ServerSentEventfields, 15-second keep-alive,Cache-ControlandX-Accel-Buffering,Last-Event-ID - FastAPI Reference: SSE —
EventSourceResponseinherits fromStreamingResponse - Starlette Docs: StreamingResponse
- Starlette Docs: Request (is_disconnected)
- MDN: Using server-sent events
