Full answer
Why a plain connection manager is not enough
A common tutorial class keeps active_connections: list[WebSocket] and loops over it. With 4 workers, a client on worker 1 sends a message and only the clients on worker 1 receive it. Sticky sessions do not fix this; users in the same room land on different workers.
Pattern
- Each worker keeps a local registry: room -> set of WebSockets.
- When a client sends a message, the worker publishes it to the bus (
PUBLISH room:10A payload), instead of sending directly. - Each worker runs one subscriber task (started in lifespan) listening to the bus. For every message it sends to the local sockets of that room.
- Local clients on the publishing worker also receive through the bus, so ordering and logic stay the same everywhere.
Choosing the bus
- Redis pub/sub: simple and fast, but fire-and-forget. A worker that is disconnected or slow misses messages.
- Redis Streams, NATS JetStream, Kafka: persisted, so a reconnecting client or worker can replay from an ID. Needed for chat history or exactly-once-ish delivery.
- A database
LISTEN/NOTIFYworks for small systems.
Details that matter in production
- Slow consumers: sending to one stalled socket must not block others. Use a bounded per-connection queue and drop or disconnect when full.
- Auth and authorisation per room, checked before accept and on every publish.
- Heartbeats (ping/pong) to remove dead sockets; remove sockets in
finally. - Reconnect with a last-seen message ID from the client.
- Connection limits per worker and a memory budget per socket.
- Presence ("who is online") needs shared state with TTLs, not local lists.
- Proxies need upgrade headers and long idle timeouts.
Libraries (broadcaster, fastapi-websocket-pubsub) wrap this pattern, but knowing the shape matters more than the package.
import asyncio
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.testclient import TestClient
class Bus:
"""In-process stand-in for Redis pub/sub, shared by several 'workers' in this demo."""
def __init__(self):
self.subscribers = []
async def publish(self, room, message):
for worker in self.subscribers:
await worker.deliver(room, message)
class Worker:
def __init__(self, name, bus):
self.name, self.bus = name, bus
self.rooms: dict[str, set[WebSocket]] = {}
bus.subscribers.append(self)
async def deliver(self, room, message):
for ws in list(self.rooms.get(room, ())):
await ws.send_json({"via": self.name, "message": message})
def make_app(self):
app = FastAPI()
@app.websocket("/ws/{room}")
async def chat(ws: WebSocket, room: str):
await ws.accept()
self.rooms.setdefault(room, set()).add(ws)
try:
while True:
text = await ws.receive_text()
await self.bus.publish(room, text) # not a local loop
except WebSocketDisconnect:
pass
finally:
self.rooms[room].discard(ws)
return app
bus = Bus()
w1, w2 = Worker("worker-1", bus), Worker("worker-2", bus)
c1, c2 = TestClient(w1.make_app()), TestClient(w2.make_app())
with c1.websocket_connect("/ws/10A") as a, c2.websocket_connect("/ws/10A") as b:
a.send_text("Quiz starts at 10")
print("client on worker-1 got:", a.receive_json())
print("client on worker-2 got:", b.receive_json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A Python object replaces Redis so the flow is visible without a server: swap Bus.publish for redis.publish and run one subscriber task per worker in lifespan. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): client on worker-1 got: {'via': 'worker-1', 'message': 'Quiz starts at 10'} client on worker-2 got: {'via': 'worker-2', 'message': 'Quiz starts at 10'}
Key points
- Sockets live in one process; local lists cannot cross workers
- Publish to a shared bus; every worker forwards to its local sockets
- Redis pub/sub is fire-and-forget; streams or Kafka persist
- Protect against slow consumers with bounded queues
- Presence and replay need shared state
Common mistakes
- Keeping a per-process connection list and expecting it to reach all users
- Using Redis pub/sub and assuming no message is ever lost
- Letting one slow client block the broadcast loop
- Skipping authorisation on publish, not only on connect
- Not cleaning up sockets on disconnect
Follow-ups
- How would a reconnecting client receive the messages it missed?
- How would you implement presence (who is online) across workers?
- When would you choose Server-Sent Events plus a normal POST instead?
Tips
- Say plainly why a single-process manager breaks
- Describe the publish/subscribe loop step by step
- Cover delivery guarantees and slow consumers