← Back to FastAPI, page 3

fastapi-0042 · Hard senior

How do you stream responses from FastAPI, for example large CSV exports or live progress with Server-Sent Events?

StreamingResponse sends chunks from a generator as they are produced, so large exports start immediately and use constant memory. For live server-to-client updates, Server-Sent Events use the text/event-stream format over normal HTTP; recent FastAPI versions provide EventSourceResponse and ServerSentEvent in fastapi.sse, where the endpoint yields events. Handle client disconnects, add heartbeats, and disable proxy buffering for streams.

Full answer

Streaming large responses

Building a 300 MB CSV in memory and then returning it is slow to start and can crash a worker. Stream instead:

python
def rows():
    yield "roll_no,marks\n"
    for r in iterate_from_db_in_batches():
        yield f"{r.roll_no},{r.marks}\n"

return StreamingResponse(rows(), media_type="text/csv",
                         headers={"Content-Disposition": 'attachment; filename="marks.csv"'})
  • Sync generators are iterated in the thread pool; async generators on the event loop.
  • The status code and headers are sent before the body, so errors halfway through cannot change the status. Validate inputs before starting.
  • The database cursor must stay open while streaming. With yield dependencies in current FastAPI (exit after the response, scope="request"), the session lives until the stream ends.

Server-Sent Events (SSE)

SSE is a one-way stream from server to browser over HTTP, with automatic reconnection in the browser's EventSource API. Good for progress bars, notifications, and streaming LLM tokens. Wire format: lines like event: progress, data: {...}, id: 7, separated by blank lines.

Recent FastAPI releases include fastapi.sse.EventSourceResponse: set it as response_class and yield dicts, models or ServerSentEvent(data=..., event=..., id=...) objects; FastAPI encodes them (data as JSON). On older versions use StreamingResponse with media_type="text/event-stream" and format lines yourself, or the sse-starlette package.

Operational details:

  • Proxies buffer by default; send X-Accel-Buffering: no for Nginx or disable buffering, or clients see nothing until the end.
  • Send periodic heartbeat comments (: ping) so idle connections are not closed by load balancers.
  • Check await request.is_disconnected() in long loops to stop work for clients that left.
  • Each open stream holds a connection; plan limits per worker.
  • Choose WebSockets when the client must also send messages frequently; SSE is simpler for server-to-client only.
python
import asyncio
from collections.abc import AsyncIterable

from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from fastapi.sse import EventSourceResponse, ServerSentEvent
from fastapi.testclient import TestClient

app = FastAPI()


def marks_csv():
    yield "roll_no,marks\n"
    for roll in range(1, 6):              # in real code: read the database in batches
        yield f"R{roll:03d},{50 + roll * 7}\n"


@app.get("/exports/marks.csv")
def export_marks():
    return StreamingResponse(marks_csv(), media_type="text/csv",
                             headers={"Content-Disposition": 'attachment; filename="marks.csv"'})


@app.get("/reports/{report_id}/progress", response_class=EventSourceResponse)
async def progress(report_id: int, request: Request) -> AsyncIterable[ServerSentEvent]:
    for step, pct in enumerate((25, 50, 75, 100), start=1):
        if await request.is_disconnected():
            break
        await asyncio.sleep(0.01)          # work happens here
        yield ServerSentEvent(data={"report": report_id, "percent": pct}, event="progress", id=str(step))
    yield ServerSentEvent(data="done", event="complete")


c = TestClient(app)
with c.stream("GET", "/exports/marks.csv") as r:
    print(r.headers["content-type"], r.headers["content-disposition"])
    print([chunk for chunk in r.iter_text()][:3])

with c.stream("GET", "/reports/42/progress") as r:
    print(r.headers["content-type"])
    print(r.read().decode().strip())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. fastapi.sse needs a recent FastAPI release (verified on 0.165); older versions can use StreamingResponse with media_type='text/event-stream'. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): text/csv; charset=utf-8 attachment; filename="marks.csv" ['roll_no,marks\n', 'R001,57\n', 'R002,64\n'] text/event-stream; charset=utf-8 event: progress data: {"report": 42, "percent": 25} id: 1 event: progress data: {"report": 42, "percent": 50} id: 2 event: progress data: {"report": 42, "percent": 75} id: 3 event: progress data: {"report": 42, "percent": 100} id: 4 event: complete data: "done"

Key points

  • StreamingResponse sends generator chunks with constant memory
  • Status and headers go first; validate before streaming
  • SSE: text/event-stream, one-way, browser auto-reconnect
  • Recent FastAPI has EventSourceResponse in fastapi.sse
  • Disable proxy buffering, add heartbeats, detect disconnects

Common mistakes

  • Building huge responses in memory instead of streaming
  • Expecting to change the status code after streaming has started
  • Forgetting proxy buffering, so SSE events arrive all at once
  • Not handling client disconnects and doing work for nobody
  • Choosing WebSockets for purely server-to-client updates where SSE is simpler

Follow-ups

  • How would you stream an LLM response token by token to a browser?
  • What happens if the database fails halfway through a CSV stream?
  • SSE or WebSockets for a live attendance dashboard, and why?

Tips

  • Show both a file stream and SSE
  • Mention the headers-first limitation
  • Cover the proxy and heartbeat operational details