Mental model
WebSockets (wss://) upgrade a standard HTTP handshake (101 Switching Protocols) into a persistent full-duplex binary/text TCP frame socket, whereas Server-Sent Events (SSE, text/event-stream) keep communication strictly inside standard unidirectional HTTP server-to-client responses. For modern LLM interfaces, status feeds, and live progress logs, SSE (especially streamed over standard fetch() POST ReadableStream when prompts require request bodies and Authorization headers!) delivers dramatically simpler proxy compatibility, HTTP/2 stream multiplexing, and lower protocol overhead than WebSockets—reserving WebSockets specifically for low-latency bi-directional traffic like live collaborative editing, voice audio chunks, or multiplayer cursors.
Theory
Evaluating SSE against WebSockets across HTTP transport layers highlights crucial production differences in proxies, auth headers, and connection limits:
| Transport Dimension | Server-Sent Events (SSE) | WebSockets (wss://) | Production Architectural Consequence |
|---|---|---|---|
| Directionality | Server -> Client stream (GET native EventSource or POST via fetch) | Full-duplex bi-directional (send / recv concurrently) | SSE suffices cleanly whenever client talks per-turn via HTTP POST |
| Multiplexing Over HTTP/2 | Yes! (Hundreds of SSE streams share 1 TCP connection over TLS) | No cleanly across browsers (each ws:// opens separate TCP tunnel; HTTP/1.1 6-tab limit risks SSE too!) | Ensure HTTPS + HTTP/2 so multi-tab users never stall at the 6-connection HTTP/1.1 cap |
| Reverse Proxy & Corporate Firewall Friction | Minimal (plain HTTP response; just disable proxy_buffering) | Requires explicit HTTP 101 Upgrade + sticky socket/Redis PubSub backplane | Fewer dropped enterprise proxy sockets with SSE |
| Binary Frames & Custom Auth Headers | UTF-8 text only (EventSource cannot send headers -> use fetch + ReadableStream!) | Binary ArrayBuffer + UTF-8 cleanly | Use fetch() POST + TextDecoderStream for Bearer-auth LLM prompt streaming |
Preventing Proxy Buffering, Idle Drops, and Wasted GPU Tokens on Client Cancel
Deploying FastAPI StreamingResponse(..., media_type="text/event-stream") behind Nginx, Traefik, or Cloudflare breaks subtly without three mandatory headers and generator patterns:
- Disable Upstream Response Buffering (
X-Accel-Buffering: no,Cache-Control: no-cache): WithoutX-Accel-Buffering: no, Nginx accumulates4–16 KBof SSE token chunks in memory before flushing to the browser, turning live word-by-word LLM streaming into awkward5-secondbursts! - Emit Periodic SSE Comment Heartbeats (
: keepalive\n\n): CDNs and cloud LBs sever silent open sockets after60–100 sof inactivity—common during slow RAG retrieval or reasoning steps before token 1 arrives. Sending: keepalive\n\nevery15 skeeps proxies alive without triggering client message handlers. - Propagate Disconnects Immediately (
await request.is_disconnected()/ ASGIhttp.disconnect): If a mobile user closes their tab mid-stream and FastAPI ignores disconnect cancellation, the upstream LLM generation keeps burning expensive GPU tokens to completion!
pythonimport asynciofrom collections.abc import AsyncIteratorfrom fastapi import FastAPI, Request, WebSocket, WebSocketDisconnectfrom fastapi.responses import StreamingResponseapp = FastAPI()async def stream_llm_sse(request: Request, prompt: str) -> AsyncIterator[str]:try:for idx in range(20):if await request.is_disconnected():# Stop upstream token generation cleanly when browser aborts Fetch AbortControllerreturnawait asyncio.sleep(0.1)yield f"id: {idx}\nevent: delta\ndata: {{\"chunk\": \"tok_{idx}\"}}\n\n"yield "event: done\ndata: {\"finish_reason\": \"stop\"}\n\n"except asyncio.CancelledError:# Release upstream httpx.AsyncClient stream locks on abrupt ASGI shutdownraise@app.post("/v1/chat/stream")async def chat_stream(request: Request, prompt: str) -> StreamingResponse:headers = {"Cache-Control": "no-cache, no-transform","X-Accel-Buffering": "no", # Prevent Nginx/reverse proxy chunk buffering}return StreamingResponse(stream_llm_sse(request, prompt),media_type="text/event-stream",headers=headers,)@app.websocket("/v1/voice-ws")async def voice_duplex_ws(ws: WebSocket) -> None:await ws.accept()try:while True:audio_frame = await ws.receive_bytes()await ws.send_bytes(audio_frame) # Full-duplex binary frame exchangeexcept WebSocketDisconnect:pass
Notice in React/TypeScript clients: native new EventSource(url) only issues GET requests, cannot carry custom Authorization: Bearer ... headers cleanly, and automatically retries non-2xx/401 connections blindly unless explicitly closed—whereas fetch() + AbortController + response.body.getReader() (or @microsoft/fetch-event-source) handles POST JSON bodies, bearer tokens, clean cancel propagation, and custom retry backoff natively.
Alternatives and trade-offs
- SSE (
fetchPOST +text/event-stream): Standard HTTP auth headers (Authorization), clean CDN/Nginx debugging, automatic HTTP/2 stream multiplexing across browser tabs, native line/event framing (id:,event:,data:); strictly server-to-client UTF-8 text per request (user interrupts fire a tiny parallelAbortController+POST /cancel). - WebSockets (
wss://): Essential when clients continuously push rapid events back (real-time PCM audio streaming, collaborative CRDT ops, cursor presence) at microsecond frame overhead; complicates horizontal scaling across API replicas (requires sticky load balancing or Redis Pub/Sub cross-pod fan-out) and lacks native HTTP compression/caching ergonomics. - gRPC-Web / HTTP Polling: Polling (
GET /jobs/{id}) wins every resilience battle when async tasks take minutes (5–30 min) across flaky mobile networks where persistent streams drop constantly.
Failure modes and misconceptions
- HTTP/1.1 Six-Connection-Per-Origin Browser Hang Using
EventSource: Over HTTP/1.1 (frequent in un-proxied local dev or misconfigured proxies), browsers allow at most 6 simultaneous TCP connections per domain—opening 6 background tabs running SSE deadlocks normal APIfetchcalls across the whole site! Ensure production serves HTTP/2 cleanly at Traefik/Nginx/Cloudflare. - Nginx / Cloudflare Response Buffering Breaking Real-Time Token Feel: Omitting
X-Accel-Buffering: no(and disabling gzip buffering on dynamic SSE chunks) makes AI text stream stall in big multi-kilobyte blocks rather than crisp token-by-token pacing. - Never Closing Upstream LLM Connections When Client Aborts (
AbortController): Browser cancels stop reading HTTP responses—yet Python async generators sitting insideawait provider.next_chunk()can keep computing forever unless wrapped with request disconnect polling or async task cancellation racingreceive(). - Assuming Browser
EventSourceSupportsPOSTBodies orAuthorizationHeaders: Sending huge chat histories or secret bearer tokens in URL query parameters (?token=jwt...&prompt=...) leaks credentials cleanly into Nginx access logs and proxy telemetry! Usefetch()+ReadableStreamfor authenticatedPOSTSSE endpoints.
Decision scenario
Your SaaS platform ships two real-time endpoints: (1) an AI Copilot chat workflow streaming text deltas, citations, and tool-call updates after sending large JSON prompt histories with Authorization: Bearer tokens; and (2) a low-latency live voice assistant sending 20 ms binary PCM microphone chunks while receiving concurrent synthesized audio frames. Build (1) with POST + text/event-stream SSE consumed via browser fetch() AbortController + ReadableStream over HTTP/2 (X-Accel-Buffering: no, 15 s : keepalive heartbeats, upstream cancellation on disconnect), and build (2) exclusively on WebSockets (wss://) for true full-duplex binary audio frames backed by Redis Pub/Sub connection tracking.
Learning outcomes
- Contrast WebSockets full-duplex binary framing against HTTP Server-Sent Events (SSE) across HTTP/1.1 and HTTP/2 constraints.
- Explain why
fetch()+ReadableStreambeats legacyEventSourcefor authenticatedPOSTAI streaming endpoints. - Configure reverse proxies (
X-Accel-Buffering: no,Cache-Control: no-cache, keepalive comments) to avoid chunk buffering and idle drops. - Propagate client
AbortControllercancellations cleanly to abort wasted upstream LLM token generation.
Trade-offs
SSE provides HTTP-native security, multiplexing, and effortless debugging for unidirectional server-push streams without sticky socket infrastructure, while WebSockets remain indispensable wherever sustained low-latency bi-directional binary traffic is required.