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

WebSockets vs. SSE in FastAPI

Use SSE for server-to-client event streams and WebSockets when clients need a persistent bidirectional channel with explicit control and backpressure.

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

Mental model

Server-Sent Events (SSE) keep an HTTP response open so a server can push UTF-8 events to a browser; WebSockets upgrade an HTTP connection to a framed, full-duplex protocol. Choose based on message direction and recovery semantics: SSE is simpler for one-way updates with reconnect cursors, while WebSockets suit frequent client-to-server messages and interactive sessions.

Learning outcomes

  • Distinguish SSE's event stream and reconnection model from WebSocket framing and duplex messaging.
  • Estimate outbound bandwidth from concurrent listeners, event rate, payload size, and framing overhead.
  • Configure FastAPI streaming headers and identify proxy behaviors that buffer or close idle connections.
  • Add application-level event IDs, replay, and backpressure instead of assuming a transport guarantees delivery.

Theory

An SSE response uses the text/event-stream media type. Each event is a UTF-8 block terminated by a blank line; fields such as id, event, data, and retry give the browser a cursor and reconnection hint. Native EventSource reconnects after many network failures and sends Last-Event-ID when it has observed an event ID. That header is only a cursor: the application must retain an event log and replay events after the cursor if it needs recovery. SSE is server-to-client; send client commands through ordinary HTTP requests or a separate interactive channel.

WebSockets begin with an HTTP Upgrade handshake and then exchange framed messages in both directions. RFC 6455 defines control frames such as Ping and Pong and requires client-to-server frames to be masked. The protocol does not define your message schema, application acknowledgements, authorization renewal, replay cursor, or reconnect policy. Build those around the socket if a client command must be retried safely or a stream must resume without gaps.

FastAPI exposes SSE naturally through StreamingResponse and WebSocket sessions through a WebSocket route. SSE still depends on every hop flushing chunks: reverse proxies may buffer the response, compression may delay small events, and idle timeouts may close a quiet stream. Disable buffering where appropriate and send comment heartbeats before the shortest idle timeout. WebSockets require Upgrade support through the proxy and load balancer, plus capacity for long-lived per-connection state. Use authenticated principals for rate limits and authorization; do not trust a client-supplied identity header without a trusted proxy boundary.

Neither protocol makes a write durable. A TCP acknowledgement means bytes reached a peer's transport stack, not that an application stored or processed an event. Attach stable IDs to events, acknowledge commands after the application action commits, and make retried commands idempotent. A WebSocket can carry a replay cursor, but the application must define it just as an SSE consumer does with Last-Event-ID.

Worked example

A dashboard has 1,200 active browsers. Each receives an average of 0.25 updates per second, with a 700-byte JSON payload and about 45 bytes of SSE field and delimiter overhead. Its approximate outbound stream rate is 1,200 × 0.25 × 745 = 223,500 bytes per second, or about 0.224 MB/s before HTTP, TLS, and TCP/IP overhead. A quiet comment heartbeat adds bytes but does not create a data event. If the same users issue 80 control messages per second in aggregate, SSE alone cannot carry those commands; use HTTP requests or a WebSocket when persistent, low-latency duplex control is needed.

Quantitative model

For N listeners, event rate λ in events/second, average payload P bytes, and average SSE framing overhead H bytes per event, estimate application payload egress as:

RSSE=Nλ(P+H)R_{SSE}=N\lambda(P+H)

R_SSE is bytes per second. This estimate excludes HTTP headers, TLS records, TCP/IP headers, heartbeats, retransmissions, and compression effects. Measure the actual wire rate and p95 delivery delay at the proxy boundary; a low application payload rate can still create many occupied connections and file descriptors.

Authenticate the session
Choose HTTP stream or Upgrade
Emit event IDs or framed messages
Apply replay and backpressure
Reconnect from an application cursor
Conceptual teaching model synthesized from:fastapi-streaming,fastapi-websockets-docs,sse-html5-spec,rfc6455-websocket-protocol

Trade-offs

RequirementSSEWebSocket
Server pushes progress or notificationsNative HTTP stream and browser EventSourceWorks, but requires message and reconnect conventions
Client sends occasional commandsPair the stream with POST or fetchSend on the same full-duplex connection
Browser reconnect behaviorBuilt-in retry and Last-Event-ID cursor supportApplication must reconnect and negotiate a resume cursor
Proxy and observabilityOrdinary HTTP path; buffering and idle timeout still matterUpgrade support, long-lived state, and frame-level telemetry matter
BackpressureSlow response can block or accumulate generator workSend queues can grow unless bounded and slow clients are handled

SSE is often a good fit for generation tokens, job status, and alert feeds where messages flow mainly from server to browser. A WebSocket is useful for collaborative editing, presence, or a control session with frequent messages in both directions. If a user sends one cancellation request during a long generation, an HTTP POST /cancel plus SSE output is often easier to route, secure, and observe than adding a socket protocol.

Failure modes and misconceptions

  • Proxy buffering: The application yields chunks, but a proxy holds them and the browser sees a burst at the end. Test through the deployed proxy chain, set the SSE media type, disable response buffering where supported, and measure first-event delay.
  • Reconnect without replay: EventSource reconnects, but the server ignores Last-Event-ID; the UI silently misses updates. Keep a bounded durable cursor log or tell the client when it must resnapshot.
  • Unbounded slow-client queues: A disconnected or stalled client keeps consuming memory. Bound each queue, detect disconnects, close or shed lagging listeners, and replay from durable storage on reconnect.
  • Socket delivery mistaken for commit: send_json returning does not mean a command committed. Return an application acknowledgement only after durable processing, and make retries idempotent.
  • Infrastructure mismatch: A proxy rejects Upgrade or enforces a shorter idle timeout than the app expects. Exercise reconnect, heartbeat, and shutdown behavior through the same ingress and load balancer used in production.

Decision scenario

A FastAPI inference endpoint streams token updates for several minutes, and users may cancel once or submit a revised prompt occasionally. Keep progress on SSE with event IDs and a Last-Event-ID replay path; submit cancel and revise actions as authenticated, idempotent HTTP requests. If product requirements change to rapid bidirectional collaboration, introduce WebSockets with explicit acknowledgements, reconnect cursors, and bounded send queues. Compare first-token delay, delivery lag, connection count, reconnect loss, and command completion before moving traffic.

Implementation pattern

This small single-process example demonstrates SSE replay, bounded fanout, heartbeat comments, and a duplex command route. Replace the in-memory event log with shared durable storage and authenticate both endpoints before deployment across multiple workers.

python
import asyncio, json
from collections import deque
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import StreamingResponse
class EventBus:
def __init__(self):
self.history, self.listeners = deque(maxlen=1000), set()
self.lock, self.next_id = asyncio.Lock(), 1
async def subscribe(self, cursor):
queue = asyncio.Queue(maxsize=64)
async with self.lock:
self.listeners.add(queue)
replay = [item for item in self.history if item["id"] > cursor]
return queue, replay
async def publish(self, payload):
async with self.lock:
event = {"id": self.next_id, "payload": payload}
self.next_id += 1; self.history.append(event)
for queue in tuple(self.listeners):
try: queue.put_nowait(event)
except asyncio.QueueFull: queue.get_nowait(); queue.put_nowait(None)
return event
async def unsubscribe(self, queue):
async with self.lock: self.listeners.discard(queue)
app, bus = FastAPI(), EventBus()
@app.get("/events")
async def events(request: Request):
try: cursor = int(request.headers.get("last-event-id", "0"))
except ValueError: cursor = 0
queue, replay = await bus.subscribe(cursor)
async def stream():
try:
for event in replay:
yield f"id: {event['id']}\ndata: {json.dumps(event['payload'])}\n\n"
while not await request.is_disconnected():
try: event = await asyncio.wait_for(queue.get(), 15)
except asyncio.TimeoutError: yield ": keepalive\n\n"; continue
if event is None: break
yield f"id: {event['id']}\ndata: {json.dumps(event['payload'])}\n\n"
finally: await bus.unsubscribe(queue)
return StreamingResponse(stream(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
@app.websocket("/control")
async def control(socket: WebSocket):
await socket.accept()
try:
while True:
event = await bus.publish(await socket.receive_json())
await socket.send_json({"accepted_event_id": event["id"]})
except WebSocketDisconnect: pass
Reflect before revealing the guide

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