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.
Learning outcomes
- Contrast the browser's native
EventSource(GET-only, auto-reconnect, no customAuthorizationheaders) cleanly against@microsoft/fetch-event-sourceor manualfetch().body.getReader()ReadableStreamSSE clients (POSTbodies + Bearer headers). - Prevent browser HTTP/1.1 6-connection-per-origin exhaustion by terminating edge proxies cleanly on
HTTP/2orHTTP/3stream multiplexing. - Implement server-side disconnect detection (
request.is_disconnected()), clean ReactuseEffectabort cleanup, and idempotentLast-Event-IDresume 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 Pattern | HTTP Methods & Custom Headers | Reconnect & Cursor (Last-Event-ID) | HTTP/1.1 Connection Limit Risk | Best Production Use Case |
|---|---|---|---|---|
Native Browser EventSource | GET only; cookie/session auth only (zero custom headers) | Built-in automatic reconnect + Last-Event-ID | Hits 6 sockets/origin quickly across open tabs unless HTTP/2 active | Lightweight notification feeds, live build/eval logs, single-cookie dashboards |
fetch + ReadableStream (POST SSE Parser) | Supports POST JSON conversation histories + Bearer headers + AbortSignal | Explicit client cursor tracking & exponential retry hook | Shared cleanly over HTTP/2+ multiplexed channels | Multi-turn streaming LLM chat completions requiring Bearer auth & large context bodies |
WebSockets (ws://) | Full bi-directional sockets after Upgrade handshake | Manual ping/pong & reconnect backoff required everywhere | Separate persistent proxy routing / sticky sessions needed | Low-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:
pythonimport asyncioimport jsonfrom fastapi import FastAPI, Requestfrom sse_starlette.sse import EventSourceResponseapp = 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_idfor token in ["Initializing index", "Scanning vectors", "Verification passed"]:if await request.is_disconnected():# Stop upstream work immediately cleanly when React unmounts or user abortsbreakseq += 1yield {"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:
typescriptimport { 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 cleanlysetStatus("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
EventSourcetabs or widgets cleanly over HTTP/1.1 silently freezes every extra XHR/fetch click across the same hostname untilHTTP/2/HTTP/3multiplexing 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 ontofetch()POST readers carrying standardAuthorizationheaders cleanly instead. - Forgetting React Cleanup & Server Disconnect Breaks: Omitting
es.close()orcontroller.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.
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?