A FastAPI multi-room chat keeps sockets in an in-memory connection manager; deployed with fastapi run --workers 4, users miss room messages. Why, and what has to change?
answer
- what each worker process imports
- a socket lives where it was accepted
- the docs warn about a single process
- a broker between workers, local fan-out within
basics
~20 sEach worker process builds its own manager, holding only the sockets it accepted, so a broadcast reaches one worker's share of the room. Publish messages to a shared pub/sub broker and have every worker relay them to its own sockets.
solid answer
~50 sThe connection manager in FastAPI's WebSocket docs is a module-level object holding live `WebSocket` instances in a list. `fastapi run --workers 4` starts four processes; each imports the module and builds its own manager, and a client's socket lives in whichever process accepted it. A `broadcast()` in one worker therefore reaches only that worker's members of the room, and the docs say so: the in-memory example works only while the process runs and only with a single process. The fix keeps a local registry per worker but moves fan-out between workers to a shared pub/sub broker: the receiving handler publishes, and a subscriber task in every worker, started in `lifespan`, relays to its local sockets. Harden the local loop too: a send to a peer whose connection has already dropped raises `WebSocketDisconnect` (code 1006) inside the *sender's* handler, so iterate over a copy and drop sockets that fail.
code
python · 43 linesfrom collections import defaultdict
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
class RoomManager:
"""Holds only the sockets accepted by THIS worker process."""
def __init__(self) -> None:
self.rooms: dict[str, set[WebSocket]] = defaultdict(set)
async def join(self, room_id: str, websocket: WebSocket) -> None:
await websocket.accept()
self.rooms[room_id].add(websocket)
def leave(self, room_id: str, websocket: WebSocket) -> None:
self.rooms[room_id].discard(websocket)
async def broadcast_local(self, room_id: str, message: dict) -> None:
for websocket in list(self.rooms[room_id]): # copy: leave() mutates the set
try:
await websocket.send_json(message)
except (WebSocketDisconnect, RuntimeError):
# A peer that vanished must not abort the loop or the sender's handler.
self.leave(room_id, websocket)
manager = RoomManager()
@app.websocket("/rooms/{room_id}/ws")
async def room_socket(websocket: WebSocket, room_id: str):
await manager.join(room_id, websocket)
try:
while True:
text = await websocket.receive_text()
# With several workers, publish to a pub/sub broker here instead and
# let a subscriber task in every worker call broadcast_local.
await manager.broadcast_local(room_id, {"room": room_id, "text": text})
except WebSocketDisconnect:
manager.leave(room_id, websocket)go deeper
Recall the tutorial's warning: an in-memory connection list works only within one process, so several workers each see only their own clients.
Explain that each worker imports the app and builds its own manager, and that a socket can only be sent on by the process that accepted it.
Lay out the broker-plus-local-relay design with the subscriber in lifespan, and harden the local loop against vanished peers, mutation during iteration and slow clients.
Weigh keeping fan-out inside the FastAPI app against a separate connection tier, and own the cost of running a broker as part of the platform.
FastAPI's WebSocket tutorial ends with a small **connection manager**: a class holding `active_connections: list[WebSocket]`, with `connect()` (accept and append), `disconnect()` (remove) and `broadcast()` (loop and `send_text()`). It is created once at module level and used by the endpoint. In development, with one process, every chat member sees every message. ## Why several workers break it 1. `fastapi run --workers 4` starts four Uvicorn worker processes. They share the listening socket, not memory. 2. Each process imports the application module and so builds **its own** manager object. 3. When a client connects, whichever worker accepts the upgrade holds that `WebSocket`; no other process can send on it. 4. A message arriving at worker 2 is broadcast by worker 2's manager, which knows only worker 2's sockets. 5. Members connected to the other three workers never see it; with random placement, each message reaches roughly a quarter of the room. The tutorial says this outright: because everything lives in memory in a single list, the example works only while the process is running and only with a single process. ## What does not fix it - **Sticky sessions.** They keep one client on one worker, but members of the same room still land on different workers. - **A global variable or class attribute.** It is still per process; nothing in Python shares objects across processes for you. - **More workers.** Adding capacity spreads a room over more processes and makes the problem worse. - **One worker.** It is correct again, but caps the app at one process and leaves the same problem waiting for the next replica. ## Reproducing it before production does The bug hides in development because `fastapi dev` runs one process and every test client runs in-process. To see it locally, start the app with `fastapi run --workers 2`, open several clients in the same room, and send messages until some clients miss them; the misses follow whichever worker accepted each client. A load test against a multi-worker deployment shows the same pattern as a delivery rate that drops as workers are added. ## The shape that works | Responsibility | Where it lives | |---|---| | live `WebSocket` objects for this process | a per-worker registry, keyed by room | | moving a message between processes | a shared pub/sub broker, one channel per room | | relaying broker messages to local sockets | one subscriber task per worker | | starting and stopping that task | the app's `lifespan` | 1. The endpoint accepts, registers the socket locally, and loops on `receive_text()`. 2. Each received message is **published** to the broker under the room's channel, not broadcast locally. 3. Each worker's subscriber task receives every published message and calls the local broadcast for that room. 4. On `WebSocketDisconnect`, the endpoint removes the socket from the local registry. Choosing and operating the broker is covered with messaging; scaling a dedicated connection tier is a system design question. The FastAPI part is the boundary: sockets stay local, messages cross processes. ## Hardening the local broadcast loop The tutorial's loop is fine for a demo and fragile in production: - **A vanished peer raises in the sender's handler.** If a socket's client dropped and its own handler has not yet seen the disconnect, `send_text()` to it raises `WebSocketDisconnect` (Starlette converts the server's write error into code 1006). Uncaught, that exception aborts the loop for the remaining members and ends the *broadcasting* client's handler. - **Sending after a close raises too.** If your code has already closed a socket, a later send raises a `RuntimeError`. - **Mutation during iteration.** Removing members while looping over the same collection skips sockets (a list) or raises (a set or dict); iterate over a copy. - **One slow client stalls the room.** `broadcast()` awaits each send in turn, so a backed-up connection delays every member after it. Concurrent sends, or one outgoing queue and task per connection with a size limit, isolate it. - **Cleanup on every path.** Remove the socket in `except WebSocketDisconnect` or in a `finally`, so errors other than a disconnect do not leave dead entries. ## What to say in an interview Explain why per-process state cannot see sockets in other processes, cite the tutorial's own single-process warning, sketch the broker-plus-local-relay shape with the subscriber in `lifespan`, and then show you know the local loop's failure modes. That last part is what separates having run it from having read the tutorial.
- Would sticky sessions at the load balancer fix the missing messages?No. Stickiness keeps one client on one worker, but the members of a single room are still spread across workers, and the in-memory manager in one worker still cannot see sockets held by another. It solves reconnecting to the same process, not fan-out across processes.
- Where should the broker subscriber run in a FastAPI app?As a background task owned by the app's `lifespan`: start it before the app begins serving, keep a reference, and cancel it on shutdown, so each worker process runs exactly one subscriber feeding its own registry. Started inside a WebSocket handler, it would live and die with one client's connection; started at import time, it would run outside any managed lifecycle.
- Why can one slow client delay a whole room in the tutorial's broadcast loop?`broadcast()` awaits each `send_text()` in turn, and a send can wait when that client's connection is backed up. Every member later in the loop waits with it. Sending to each socket concurrently, or giving each connection its own bounded outgoing queue drained by its own task, isolates the slow client; dropping clients whose queue overflows protects memory.
Four receptionists in four separate buildings each keep a guest list for their own lobby. An announcement read out in one lobby never reaches the guests in the other three; a shared public-address system that every receptionist listens to and repeats locally does.
- A module-level manager is shared by all Uvicorn workers like any global variable.
- Sticky sessions make an in-memory room registry correct across workers.
- send_text() silently skips a client that has already gone away.
- Adding more workers fixes missed messages by adding capacity.
- WebSocket objects can be handed to another worker through the broker.