FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Server-Sent Events with FastAPI EventSourceResponse

Implementing reliable Server-Sent Events subscriptions in React components using native EventSource or custom headers fetch.

Freshness: current•14 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Server-Sent Events (SSE) establish a lightweight, unidirectional server-to-browser push stream directly over standard HTTP using Content-Type: text/event-stream rather than upgrading sockets into full-duplex WebSockets. Every packet follows discrete line-delimited fields (event:, id:, retry:, data: terminated by \n\n), letting FastAPI EventSourceResponse push incremental LLM tokens, typed progress milestones, or live job telemetry smoothly onto React hooks.

Client opens HTTP/2 SSE stream
FastAPI yields typed event dicts
Chunked text/event-stream wire frames
Parse event name, id & Last-Event-ID
Cleanup AbortController on React unmount
Conceptual teaching model synthesized from:Server-Sent Events - W3C Recommendationsse-starlette python module source repository

Learning outcomes

  • Contrast the browser's native EventSource (GET-only, auto-reconnect, no custom Authorization headers) cleanly against @microsoft/fetch-event-source or manual fetch().body.getReader() ReadableStream SSE clients (POST bodies + Bearer headers).
  • Prevent browser HTTP/1.1 6-connection-per-origin exhaustion by terminating edge proxies cleanly on HTTP/2 or HTTP/3 stream multiplexing.
  • Implement server-side disconnect detection (request.is_disconnected()), clean React useEffect abort cleanup, and idempotent Last-Event-ID resume cursors cleanly.

Theory

Teams routinely adopt raw new EventSource("/api/chat") on day one of building an AI frontend, only to hit three immediate walls when hardening authentication and multi-tab traffic: no HTTP POST JSON payload (forcing large multi-turn conversation histories into truncated GET query params), no custom Authorization: Bearer ... headers (tempting developers into insecure ?token= URL parameters captured inside load-balancer access logs!), and HTTP/1.1 6-tab connection stalls.

SSE Client PatternHTTP Methods & Custom HeadersReconnect & Cursor (Last-Event-ID)HTTP/1.1 Connection Limit RiskBest Production Use Case
Native Browser EventSourceGET only; cookie/session auth only (zero custom headers)Built-in automatic reconnect + Last-Event-IDHits 6 sockets/origin quickly across open tabs unless HTTP/2 activeLightweight notification feeds, live build/eval logs, single-cookie dashboards
fetch + ReadableStream (POST SSE Parser)Supports POST JSON conversation histories + Bearer headers + AbortSignalExplicit client cursor tracking & exponential retry hookShared cleanly over HTTP/2+ multiplexed channelsMulti-turn streaming LLM chat completions requiring Bearer auth & large context bodies
WebSockets (ws://)Full bi-directional sockets after Upgrade handshakeManual ping/pong & reconnect backoff required everywhereSeparate persistent proxy routing / sticky sessions neededLow-latency bi-directional audio/voice streams & collaborative CRDT canvases

On the Python/FastAPI backend, sse-starlette (EventSourceResponse) handles async generator serialization, periodic ping keepalive frames preventing idle Nginx proxy drops cleanly, and cancellation when clients close tabs (await request.is_disconnected() or asyncio.CancelledError), saving expensive downstream LLM decode work immediately when a user clicks Stop Generating:

python
import asyncio
import json
from fastapi import FastAPI, Request
from sse_starlette.sse import EventSourceResponse
​
app = FastAPI()
​
@app.get("/api/jobs/{job_id}/stream")
async def stream_job_events(job_id: str, request: Request) -> EventSourceResponse:
last_event_id = int(request.headers.get("last-event-id", "0"))
​
async def event_generator():
seq = last_event_id
for token in ["Initializing index", "Scanning vectors", "Verification passed"]:
if await request.is_disconnected():
# Stop upstream work immediately cleanly when React unmounts or user aborts
break
seq += 1
yield {
"event": "progress",
"id": str(seq),
"retry": 3000,
"data": json.dumps({"jobId": job_id, "step": token, "seq": seq}),
}
await asyncio.sleep(0.05)
​
return EventSourceResponse(event_generator(), ping=15)

In React, pair EventSource strictly with useEffect cleanup (es.close())—and for POST-based LLM completions sending Bearer tokens or large context payloads, use a line-buffered fetch parser wired directly to AbortController:

typescript
import { useEffect, useState } from "react";
​
export function useJobProgressSse(jobId: string) {
const [events, setEvents] = useState<Array<{ step: string; seq: number }>>([]);
const [status, setStatus] = useState<"connecting" | "open" | "closed">("connecting");
​
useEffect(() => {
const es = new EventSource(`/api/jobs/${encodeURIComponent(jobId)}/stream`, {
withCredentials: true,
});
es.onopen = () => setStatus("open");
es.addEventListener("progress", (ev) => {
const payload = JSON.parse((ev as MessageEvent).data) as { step: string; seq: number };
setEvents((prev) => [...prev, payload]);
});
es.onerror = () => {
if (es.readyState === EventSource.CLOSED) setStatus("closed");
};
return () => {
es.close(); // Mandatory cleanup stops leaked browser/HTTP connections cleanly
setStatus("closed");
};
}, [jobId]);
​
return { events, status };
}

Trade-offs

Using SSE over standard HTTPS (EventSourceResponse + native EventSource or POST fetch) inherits edge CDN TLS termination, standard HTTP header auth/cookies, compression/load balancing, and clean browser reconnection semantics natively cleanly without stateful WebSocket sticky-session infrastructure. It trades away raw binary server-to-client / client-to-server full-duplex framing (relevant primarily for sub-50ms audio WebRTC or shared whiteboard sockets) and demands strict proxy buffering off switches (X-Accel-Buffering: no) alongside HTTP/2+ enabled end-to-end cleanly.

Failure modes and misconceptions

  • HTTP/1.1 Six-Connection-Per-Origin Deadlock: Opening 6 concurrent EventSource tabs or widgets cleanly over HTTP/1.1 silently freezes every extra XHR/fetch click across the same hostname until HTTP/2/HTTP/3 multiplexing activates cleanly.
  • Nginx Proxy Buffering Hiding Streaming Tokens: Default reverse-proxy response buffers hold SSE frames up to 4KB–32KB cleanly in RAM until complete response EOF—ruining interactive TTFT unless headers explicitly configure streaming (X-Accel-Buffering: no, Cache-Control: no-cache).
  • Passing Bearer JWTs via Query Params for Native EventSource: Putting ?token=eyJ... directly on GET URLs writes raw bearer credentials straight into access logs, CDN analytics, and browser history; switch onto fetch() POST readers carrying standard Authorization headers cleanly instead.
  • Forgetting React Cleanup & Server Disconnect Breaks: Omitting es.close() or controller.abort() on component unmount leaks active server worker generators running wasted upstream LLM tokens long after users closed pages cleanly.

Decision scenario

A developer dashboard renders a read-only CI pipeline trace log reusing session cookies cleanly across tabs alongside an authenticated AI SQL generator accepting large multi-table JSON schemas via POST. Use native EventSource with Last-Event-ID over HTTP/2 cleanly for read-only log subscriptions while switching the SQL copilot endpoint cleanly onto an AbortController-backed fetch ReadableStream SSE client carrying Bearer headers without ?token= query leaks cleanly.

Reflect before revealing the guide

What concurrent stream limit breaks native EventSource apps across multiple browser tabs under legacy HTTP/1.1, and why do AI chat interfaces frequently use fetch ReadableStream instead?

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next