TL;DR
- Use Server-Sent Events (SSE) when a client mainly receives updates and standard HTTP reconnection is useful. Use WebSockets when the client and server both need a persistent bidirectional channel.
- FastAPI connection objects live in a worker process. An in-memory connection list cannot broadcast across multiple replicas.
- Redis Pub/Sub can fan out live messages to connected gateways, but delivery is at-most-once. A disconnected subscriber misses the message. Keep durable state or use Redis Streams when replay is required.
- Use bounded per-client queues, sequence IDs, heartbeats, authentication, origin checks, reconnect jitter, and a catch-up path to handle slow clients and deployments.
Choose a transport from the interaction pattern
Real-time features often start with one requirement: show a user progress or notify them when something changes. The system then grows into presence, chat, collaborative editing, or live operations. Selecting a transport based on the feature name alone can create unnecessary connection state and reliability gaps.
SSE is a unidirectional stream from server to browser over HTTP. The browser's EventSource API reconnects automatically, can include a last event ID, and supports event types and retry hints. It is a good fit for progress updates, notifications, dashboards, and log tails where the browser sends ordinary HTTP requests for commands. MDN Server-Sent Events
WebSockets begin with an HTTP handshake and then provide a persistent, bidirectional connection. Use them when clients need to send frequent messages over the same live session, such as interactive collaboration or low-latency multiplayer state. FastAPI exposes WebSocket endpoints and message methods, but your application still owns authentication, connection lifecycle, backpressure, and cross-replica distribution. FastAPI WebSockets
Neither transport is a durable message broker. A successful socket write does not prove the browser processed an update, and an SSE reconnect does not restore updates that were never stored. The transport keeps a connection open. Your data model must define what can be replayed and how a client knows where to resume.
Design the gateway as a stateless connection tier
A FastAPI worker accepts client connections, authenticates them, subscribes to the topics or entity IDs the actor may access, and forwards authorized events. Several worker processes may each hold their own client sockets. If a publisher notifies only an in-memory list, clients attached to other processes never see the update.
Separate the connection tier from the event source. A domain transaction writes durable state and an event or outbox record. A dispatcher publishes a notification to a Redis channel. Every gateway replica that is currently subscribed receives the live notification and forwards it to its local clients. On reconnect, the client presents its last event ID and the gateway reads missing changes from a durable store before resuming live delivery.
Redis Pub/Sub is useful for best-effort live fan-out, but it is explicitly at-most-once. If a subscriber is disconnected when a message is published, Redis does not retain it for later delivery. Redis recommends Streams when persistence, replay, or stronger delivery behavior is required. Redis Pub/Sub messaging and delivery semantics
A practical reliability split is:
- PostgreSQL or another system of record holds the durable state and sequence.
- An outbox or event stream records changes that need recovery.
- Redis Pub/Sub wakes connected gateway replicas quickly.
- SSE or WebSocket transports deliver to clients that are online.
- Reconnect catch-up reads durable changes after the client's cursor.
If the event itself must be consumed by independent services with retries and replay, use a durable stream or broker as the source. Redis Streams support consumer groups and pending-entry recovery. Pub/Sub can remain a low-latency notification layer over that durable event path. Our guide compares event backbones and replay needs.
Implement SSE with resumable IDs
Each user-visible update should have an ID that lets the client resume from a known point. It can be a monotonically increasing per-tenant sequence, an ordered event-log ID, or an opaque cursor whose ordering is defined by the server. Do not assume wall-clock timestamps are unique or totally ordered across writers.
A minimal FastAPI stream can check disconnection and emit SSE framing. This is illustrative: authorization, cursor lookup, queue management, and event serialization belong in application services.
import json
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
app = FastAPI()
@app.get("/events")
async def events(request: Request, after: str | None = None):
actor = await authenticate_request(request)
await authorize_stream(actor)
async def body():
cursor = after or request.headers.get("last-event-id")
async for item in subscribe_with_catchup(actor, cursor):
if await request.is_disconnected():
break
payload = json.dumps(item.payload, separators=(",", ":"))
yield (
f"id: {item.cursor}\n"
f"event: {item.kind}\n"
f"data: {payload}\n\n"
)
return StreamingResponse(
body(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
In a production implementation, read the cursor from the validated resume mechanism rather than trusting an arbitrary query value. Ensure the cursor is scoped to the authenticated tenant and topic. If the cursor has expired from retention, return a defined reset response or send a snapshot event so the client can rebuild state.
Send periodic comment frames such as : keepalive\n\n when infrastructure idle timeouts require them. They are ignored by the browser event handler but keep intermediaries from treating the connection as dead. Disable response buffering where needed and test the real reverse proxy, load balancer, CDN, and HTTP version path. SSE uses a long-lived HTTP response, so proxy defaults and connection caps matter.
Native EventSource does not provide a general way to attach an arbitrary bearer authorization header. Common patterns use same-site secure cookies, a short-lived signed stream URL, or a fetch-based streaming client when custom headers are required. Avoid putting long-lived credentials in query strings because URLs can appear in logs, browser history, and monitoring. Apply the same origin, CSRF, and cookie protections as other authenticated endpoints.
Implement WebSockets with explicit lifecycle policy
A WebSocket endpoint should authenticate before accepting where practical, validate the requested origin for browser clients, and authorize each requested topic. Authentication at the handshake is not permanent authorization. Recheck access when subscriptions change, a token expires, or a user is removed from a tenant.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
actor = await authenticate_websocket(websocket)
if actor is None:
await websocket.close(code=4401)
return
await websocket.accept()
client = await gateway.attach(actor, websocket)
try:
while True:
message = await websocket.receive_json()
command = validate_client_command(message)
await authorize_command(actor, command)
await handle_command(actor, command)
except WebSocketDisconnect:
pass
finally:
await gateway.detach(client)
This endpoint sketch leaves origin policy and token verification in dedicated functions. Never trust a client-supplied user or tenant ID. Derive identity from verified credentials, then authorize each channel against that identity. A WebSocket connection can outlive the access token used to establish it, so set a maximum session lifetime or send a reauthentication message before credential expiry.
For cookie-authenticated sockets, validate the Origin header against an allowlist to limit cross-site WebSocket hijacking. If using a short-lived connection token, scope it narrowly to the intended user, tenant, and channel. Do not log the full token or message bodies containing secrets. Use TLS in production and define close codes for normal completion, policy violation, and retryable server shutdown.
WebSocket commands should be idempotent when the client may retry after losing an acknowledgement. Include a command ID and store the result for the retry window. Server-to-client messages should include a sequence cursor if the client needs to detect a gap and request catch-up.
Bound queues and slow consumers
Each connected client has finite memory and network capacity. If the server produces updates faster than a client can read them, an unbounded outgoing queue turns a slow tab into growing memory use. Set a maximum queue size or byte budget. When the budget is exceeded, choose a product-specific response: drop replaceable state snapshots, coalesce several updates into the latest state, or disconnect the client and require it to resume from a durable cursor.
Do not silently drop commands or financial events. For these, persist the state transition, send an acknowledgement with a durable ID, and let the client fetch the authoritative state after reconnect. Presence and typing indicators can be transient; document that they expire and may be missed.
Measure open connections per worker, active subscriptions, outgoing queue depth, dropped or coalesced messages, disconnect reason, reconnect rate, event-to-client latency, and catch-up duration. Apply per-user and per-tenant connection limits so one actor cannot exhaust file descriptors or event fan-out capacity. Capacity planning should include worker memory per connection, TLS buffers, event queue sizes, and idle socket timeouts.
Defend against reconnect storms
When a deployment or network incident disconnects thousands of clients at once, immediate reconnect retries can overload authentication, subscription setup, and Redis. Clients should use exponential backoff with randomized jitter. Cap the maximum wait and reset the backoff only after a connection remains stable for a reasonable interval.
For SSE, browsers reconnect according to the event stream retry behavior, and the server can provide a retry interval. A server-directed fixed interval can still synchronize many clients, so add client-side variation where the client implementation permits it. For WebSockets, explicitly implement randomized delay on close and distinguish permanent policy failures from transient network errors.
Protect the server side too. Rate-limit connection establishment per identity and source, bound concurrent authentication work, and shed load before exhausting worker capacity. Roll deployments gradually or stop accepting new connections on a worker before termination, allowing clients to reconnect to healthy replicas. Keep connection draining below the platform's shutdown deadline.
Test gaps, ordering, and authorization changes
Exercise reconnect after the client receives an event but before it records the cursor, and after it records the cursor but before it updates the UI. The client should either safely apply the same event again or refetch a snapshot. Send duplicate live notifications and confirm the UI is idempotent.
Test a gateway replica restarting while Redis Pub/Sub messages are in flight. The expected behavior is a temporary gap followed by durable catch-up, not a promise that Pub/Sub replayed the message. Test cursor expiration, out-of-order publisher completion, a tenant membership revocation while the socket remains open, and a client that stops reading for several minutes.
For ordering, scope sequence numbers to the entity or stream whose order matters. A single global sequence can create contention; independent sequences require the client to merge domains carefully. If a client sees a gap, fetch missing state from the durable source before rendering a derived result as current.
Keep sensitive event payloads minimal. A notification can carry “order status changed” plus an opaque record ID, then the client fetches the authorized view over HTTPS. This reduces exposure to stale connections and avoids making the real-time gateway a second copy of every business record.
Frequently asked questions
Should I use SSE or WebSockets for progress updates?
SSE is usually simpler when the browser only receives updates and sends commands through ordinary HTTP requests. WebSockets fit when both sides exchange frequent messages over a persistent connection. Test proxy behavior, authentication needs, and expected client count before choosing.
Does Redis Pub/Sub replay messages after a FastAPI worker reconnects?
No. Redis Pub/Sub is at-most-once, so a subscriber that is disconnected during publication misses that message. Keep durable event state and catch up from a cursor after reconnect, or use Redis Streams or another retained log when delivery and replay are requirements.
Can an in-memory list of WebSocket connections scale across Uvicorn workers?
No. Each worker process has its own memory and sees only its own connections. Use a cross-process fan-out layer such as Redis Pub/Sub for live delivery, and keep durable state separately if clients need to recover missed updates.
How do I prevent reconnect storms after a deployment?
Use exponential backoff with randomized jitter, cap retries, rate-limit connection setup, and drain workers before shutdown. Avoid a synchronized fixed retry interval, and keep authentication and subscription setup bounded during an incident.
Keep the transport separate from delivery guarantees
SSE and WebSockets solve different connection patterns. SSE is a strong default for server-to-browser updates; WebSockets support interactive bidirectional sessions. Neither replaces durable event storage, per-client authorization, or slow-consumer policy.
Use Redis Pub/Sub to wake connected replicas when missing an ephemeral update is acceptable. Add a durable cursor and catch-up path for state users must recover. If you are designing notifications, collaboration, or streaming progress for a multi-replica FastAPI service, talk with our team about connection lifecycle, delivery boundaries, and capacity testing.
