Skip to content
Goal: Deep understanding✓ Sources verified 2026-11-24FastAPISSEEventSourceResponse

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. Declare response_class=EventSourceResponse on the route and just yield data from the function.
  • yield a plain object (dict / Pydantic model) → it's JSON-encoded into the data: field.
  • yield ServerSentEvent(...) → lets you set event, id, retry and comment; raw_data sends a string without JSON encoding (such as [DONE]) and is an alternative to data.
  • 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-starlette or a hand-written StreamingResponse(media_type="text/event-stream").

How it works ​

  • EventSourceResponse is a subclass of StreamingResponse: the response headers go out first, then each yield writes 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-cache and using X-Accel-Buffering: no to 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.CancelledError at an await). So write the upstream LLM call inside async with: on cancellation the context exits and the upstream stream closes too. You can also check await 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 ​

  1. 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.
  2. 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.
  3. Proxy / CDN buffering: works locally, not streaming once deployed. Usually it's proxy buffering or timeout settings.
  4. Sync blocking code inside the generator: blocks the event loop (see How async def and def Routes Execute).

Common interview questions ​

  1. How do you implement SSE in FastAPI? How does EventSourceResponse relate to StreamingResponse?
  2. When the client disconnects, how do you make sure the upstream LLM request is cancelled too?
  3. How do you push progress for long tasks in a multi-instance deployment?
  4. After deployment, streaming output arrives all at once. What could cause that?

How it relates to my projects ​

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 ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section