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

WebSockets vs Server-Sent Events (SSE)

Duplex WebSocket framing, SSE streaming HTTP responses, and long-polling state machines.

Freshness: current•15 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Distinguish duplex WebSockets from SSE unidirectional streaming
  • ✓Implement resilient reconnection and heartbeat loops
Isometric Diagram LabSystem Design · 10 steps · 11 min

WebSockets, SSE & Real-Time Fan-Out

Compare persistent full-duplex WebSockets, Server-Sent Events, and Redis Pub/Sub connection gateways.

Open Isometric Walkthrough
Full Technical Reference Document

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.

Client HTTP Request
WS 101 Upgrade vs SSE text/event-stream
WS Full Duplex Frames / SSE Server Chunks
Proxy Keep-Alive Heartbeat Comments
Disconnect Cleanup & Reconnect with Cursor
Conceptual teaching model synthesized from:sse-html5-spec,mdn-readable-stream,fastapi-docs

Theory

Evaluating SSE against WebSockets across HTTP transport layers highlights crucial production differences in proxies, auth headers, and connection limits:

Transport DimensionServer-Sent Events (SSE)WebSockets (wss://)Production Architectural Consequence
DirectionalityServer -> 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/2Yes! (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 FrictionMinimal (plain HTTP response; just disable proxy_buffering)Requires explicit HTTP 101 Upgrade + sticky socket/Redis PubSub backplaneFewer dropped enterprise proxy sockets with SSE
Binary Frames & Custom Auth HeadersUTF-8 text only (EventSource cannot send headers -> use fetch + ReadableStream!)Binary ArrayBuffer + UTF-8 cleanlyUse 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:

  1. Disable Upstream Response Buffering (X-Accel-Buffering: no, Cache-Control: no-cache): Without X-Accel-Buffering: no, Nginx accumulates 4–16 KB of SSE token chunks in memory before flushing to the browser, turning live word-by-word LLM streaming into awkward 5-second bursts!
  2. Emit Periodic SSE Comment Heartbeats (: keepalive\n\n): CDNs and cloud LBs sever silent open sockets after 60–100 s of inactivity—common during slow RAG retrieval or reasoning steps before token 1 arrives. Sending : keepalive\n\n every 15 s keeps proxies alive without triggering client message handlers.
  3. Propagate Disconnects Immediately (await request.is_disconnected() / ASGI http.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!
python
import asyncio
from collections.abc import AsyncIterator
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import StreamingResponse
​
app = 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 AbortController
return
await 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 shutdown
raise
​
@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 exchange
except 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 (fetch POST + 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 parallel AbortController + 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

  1. 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 API fetch calls across the whole site! Ensure production serves HTTP/2 cleanly at Traefik/Nginx/Cloudflare.
  2. 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.
  3. Never Closing Upstream LLM Connections When Client Aborts (AbortController): Browser cancels stop reading HTTP responses—yet Python async generators sitting inside await provider.next_chunk() can keep computing forever unless wrapped with request disconnect polling or async task cancellation racing receive().
  4. Assuming Browser EventSource Supports POST Bodies or Authorization Headers: 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! Use fetch() + ReadableStream for authenticated POST SSE endpoints.
Reflect before revealing the guide

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() + ReadableStream beats legacy EventSource for authenticated POST AI streaming endpoints.
  • Configure reverse proxies (X-Accel-Buffering: no, Cache-Control: no-cache, keepalive comments) to avoid chunk buffering and idle drops.
  • Propagate client AbortController cancellations 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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h 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