Skip to content

Lesson 24 of 59Async and background work

WebSockets in FastAPI

Build real-time features with FastAPI WebSockets, rooms and Redis pub/sub across workers, authenticate connections, and know when SSE is simpler.

17 min read0/4 questions

Chat messages, live dashboards, "your report is ready" notifications and multiplayer cursors all need the server to send data the moment something happens, without the browser asking first. Plain HTTP cannot do that: the client asks, the server answers, and the conversation is over. This lesson compares the options, builds a WebSocket chat room in FastAPI, then solves the problem that catches everyone in production: a message sent on one worker has to reach users connected to another. Finally, it shows when a simpler tool, Server-Sent Events, is the better choice.

Three ways to push data

PollingServer-Sent Events (SSE)WebSockets
HowClient asks every few secondsOne long HTTP response the server keeps writing toA persistent two-way connection
DirectionClient to serverServer to client onlyBoth ways
DelayUp to the polling intervalImmediateImmediate
ReconnectsNot neededAutomatic in the browserYou write it
Good forRare updates, simple jobsNotifications, live feeds, streaming AI responsesChat, games, collaborative editing

Polling is fine more often than people admit: checking a job status every five seconds is simple and works everywhere. But it wastes requests when nothing changed and is never instant. Long polling is the old workaround: the server holds each request open until it has news or a timeout passes, and the client immediately asks again. SSE and WebSockets replaced it for most uses, but you will still meet it in older systems. WebSockets start life as an HTTP request and then switch protocols:

Opening a WebSocket
BrowserUvicornYour endpointGET /ws + Upgrade: websocketcall with WebSocketawait websocket.accept()101 Switching Protocolsframe: "hello"frame: broadcast

The browser sends a normal HTTP request with Upgrade: websocket headers. Cookies for the site go along with it.

1/6

A WebSocket endpoint

FastAPI supports WebSockets directly, using the websockets library that comes with fastapi[standard]:

app/api/echo.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
 
app = FastAPI()
 
 
@app.websocket("/ws/echo")
async def echo(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            text = await websocket.receive_text()
            await websocket.send_text(f"you said: {text}")
    except WebSocketDisconnect:
        pass                       # the client closed the tab

The function runs for as long as the connection is open: one long-lived coroutine per connected user. That is why WebSocket handlers must be async def and must never block. A single blocking call freezes every socket on that worker, not just one request. There are also receive_json() and send_json(), and a while True loop is the normal shape. When the client disconnects, the next receive_* raises WebSocketDisconnect.

You can test it in the browser console with new WebSocket("ws://localhost:8000/ws/echo"), and in pytest with TestClient(app).websocket_connect("/ws/echo").

Rooms with a connection manager

For chat, each server needs to know which sockets are in which room. A small connection manager keeps that map:

app/realtime/manager.py
from collections import defaultdict
 
from fastapi import WebSocket
 
 
class ConnectionManager:
    def __init__(self) -> None:
        self.rooms: dict[str, set[WebSocket]] = defaultdict(set)
 
    async def connect(self, room: str, websocket: WebSocket) -> None:
        await websocket.accept()
        self.rooms[room].add(websocket)
 
    def disconnect(self, room: str, websocket: WebSocket) -> None:
        self.rooms[room].discard(websocket)
 
    async def broadcast_local(self, room: str, message: str) -> None:
        for websocket in list(self.rooms[room]):
            try:
                await websocket.send_text(message)
            except Exception:
                self.disconnect(room, websocket)     # a dead connection
 
 
manager = ConnectionManager()
app/api/chat.py
@app.websocket("/ws/rooms/{room}")
async def chat(websocket: WebSocket, room: str):
    await manager.connect(room, websocket)
    try:
        while True:
            text = await websocket.receive_text()
            await manager.broadcast_local(room, text)
    except WebSocketDisconnect:
        manager.disconnect(room, websocket)

Two small details in broadcast_local matter. It loops over a copy of the set, because sockets can be removed while it is sending, and changing a set during iteration raises an error. And it treats a failed send as a disconnect, because a client that vanished without a clean close (a phone losing signal, say) is only discovered when you try to write to it.

This works perfectly on your laptop. Then you deploy with four workers, and half the messages vanish.

Quick check
The chat above runs with fastapi run --workers 4. Ada and Sam are in the same room but connected to different workers. What happens when Ada sends a message?
Need a nudge? A hint rules out a wrong answer.

Broadcasting across workers with Redis

The fix: instead of broadcasting locally, a worker publishes each message to Redis. Every worker subscribes, and when a message arrives, sends it to its own local sockets. Run this simulation to see both versions:

Pythonpubsub_fanout.py
from collections import defaultdict class FakeSocket: def __init__(self, user): self.user = user def send(self, text): print(f" {self.user} receives: {text}") class ConnectionManager: # one per worker process def __init__(self, name): self.name = name self.rooms = defaultdict(set) def connect(self, room, ws): self.rooms[room].add(ws) def broadcast_local(self, room, text): for ws in sorted(self.rooms[room], key=lambda w: w.user): ws.send(text) class PubSub: # stands in for Redis def __init__(self): self.subscribers = [] def subscribe(self, callback): self.subscribers.append(callback) def publish(self, room, text): for callback in self.subscribers: callback(room, text) worker_a, worker_b = ConnectionManager("A"), ConnectionManager("B")worker_a.connect("general", FakeSocket("ada"))worker_b.connect("general", FakeSocket("sam"))worker_b.connect("general", FakeSocket("lin")) print("Local broadcast from worker A:")worker_a.broadcast_local("general", "hi from ada") redis = PubSub()redis.subscribe(worker_a.broadcast_local)redis.subscribe(worker_b.broadcast_local) print("Publish through pub/sub:")redis.publish("general", "hi from ada")
Output
Press Run (⌘ Enter) to see what happens.
Chat across workers with Redis pub/sub
AdaAdaSamSamWorker A: Ada's socketWorker AAda's socketWorker B: Sam's socketWorker BSam's socketRedis: channel room:generalRedischannel room:generalsendPUBLISHmessagesend_text

Ada's message arrives on worker A, the only process holding her socket.

1/4

In FastAPI, start one subscriber task per worker in the lifespan handler:

app/main.py
import asyncio
from contextlib import asynccontextmanager
 
import redis.asyncio as redis
 
 
async def relay_messages(r: redis.Redis) -> None:
    pubsub = r.pubsub()
    await pubsub.psubscribe("room:*")                  # every room channel
    async for message in pubsub.listen():
        if message["type"] == "pmessage":
            room = message["channel"].removeprefix("room:")
            await manager.broadcast_local(room, message["data"])
 
 
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.redis = redis.Redis.from_url(settings.redis_url, decode_responses=True)
    relay = asyncio.create_task(relay_messages(app.state.redis))
    yield
    relay.cancel()
    await app.state.redis.aclose()

The chat endpoint now calls await app.state.redis.publish(f"room:{room}", text) instead of broadcast_local. Remember that Redis pub/sub is fire-and-forget: a user who is offline misses messages, so store chat history in Postgres and load the recent messages when someone joins. If you need guaranteed delivery, look at Redis Streams.

Put it in order5 steps

Order what happens when Ada sends a chat message with the Redis setup.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Messages with a shape

Raw strings get messy fast once you have typing indicators, joins, leaves and edits. Send JSON with a type field and validate everything that comes in with Pydantic, exactly like a request body, because a WebSocket is just another input from an untrusted client:

app/realtime/messages.py
from typing import Literal
 
from pydantic import BaseModel, Field
 
 
class ChatMessage(BaseModel):
    type: Literal["message"]
    text: str = Field(min_length=1, max_length=2000)
 
 
class Typing(BaseModel):
    type: Literal["typing"]

In the endpoint, parse with ChatMessage.model_validate_json(text) and send an error frame back on a ValidationError instead of crashing the connection. Put a per-connection limit on how many messages a client may send per second, too. An HTTP rate limiter does not see individual frames, and one misbehaving client can otherwise flood a whole room.

Authenticating WebSockets

This is where many implementations go wrong. A browser's new WebSocket(url) cannot set custom headers, so the Authorization: Bearer header your HTTP API uses is not available. The common options:

  • Cookies. The browser sends the site's cookies with the handshake, so a session cookie works naturally. Because of that, also check the Origin header, otherwise any website could open a socket using your user's cookies (cross-site WebSocket hijacking).
  • A short-lived ticket. The client calls an authenticated HTTP endpoint to get a single-use token valid for a minute, then connects with ?ticket=.... Avoid putting long-lived JWTs in the URL, because URLs end up in server and proxy logs.
  • First message. Accept, then require the first message to be the token, and close if it is not. Simple, but unauthenticated sockets are briefly open.
app/api/chat.py
from fastapi import Query, WebSocketException, status
 
 
@app.websocket("/ws/rooms/{room}")
async def chat(websocket: WebSocket, room: str, ticket: str = Query()):
    user = await redeem_ticket(ticket)                   # deletes it: single use
    if user is None or not can_join(user, room):
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    await manager.connect(room, websocket)
    ...

Raising WebSocketException before accept() rejects the handshake. Code 1008 means "policy violation", the standard close code for "not allowed". Authorise per room too: being logged in does not mean you may read every room.

Match the pairs0/5 matched

Match each problem to its fix.

Choose an item, then its match on the other side.

When SSE is simpler

If data only flows from server to client, you probably do not need WebSockets. Server-Sent Events are a plain HTTP response with the text/event-stream content type that the server keeps writing to:

app/api/notifications.py
import asyncio
import json
 
from fastapi.responses import StreamingResponse
 
 
@app.get("/notifications/stream")
async def notifications(user: CurrentUser):
    async def events():
        while True:
            for note in await fetch_new_notifications(user.id):
                yield f"data: {json.dumps(note)}\n\n"
            await asyncio.sleep(2)
 
    return StreamingResponse(events(), media_type="text/event-stream")

In the browser, new EventSource("/notifications/stream") reconnects automatically if the connection drops. Because it is ordinary HTTP, your normal cookie auth, middleware, proxies and load balancers handle it without special configuration. Many AI chat interfaces stream tokens this way.

Two SSE details are worth knowing. Each event can carry an id: line, and when the browser reconnects it sends the last id it saw in a Last-Event-ID header, so your endpoint can resend whatever the client missed. And over HTTP/1.1, browsers allow only about six open connections per domain, shared across tabs, so a user with many tabs open can run out; HTTP/2, which most production setups use, lifts that limit. The client still sends messages with regular POST requests. Reach for WebSockets when the client sends frequent messages too, like chat typing indicators, games or collaborative editing.

Quick check
You need to show users a live progress bar while their export runs on a Celery worker. Which is the simplest good fit?
Need a nudge? A hint rules out a wrong answer.

Production notes

Long-lived connections change a few things. Deploys and scaling work differently: a normal HTTP request finishes in milliseconds, but a socket may stay open for hours, so a rolling deploy has to close connections on old workers, and the clients reconnect to new ones. Plan for that rather than treating it as an error. Load balancers and proxies have idle timeouts (often around 60 seconds) and need WebSocket upgrades enabled; Uvicorn sends protocol pings by default, which keeps connections alive. Clients will disconnect during every deploy, so the frontend must reconnect with backoff and fetch missed messages. Each connection holds memory on the server, so watch the number of open sockets per worker. And a slow client should not slow down a broadcast for everyone: for big rooms, give each connection its own outgoing queue.

A minimal reconnecting client in the browser looks like this:

chat.js
let delay = 1000;
 
function connect() {
  const ws = new WebSocket(`wss://${location.host}/ws/rooms/general?ticket=${ticket}`);
  ws.onopen = () => { delay = 1000; loadMissedMessages(); };
  ws.onmessage = (event) => render(JSON.parse(event.data));
  ws.onclose = () => {
    setTimeout(connect, delay + Math.random() * 1000);   // backoff with jitter
    delay = Math.min(delay * 2, 30000);
  };
}
 
connect();

The jitter matters for the same reason it does with task retries: after a deploy, thousands of clients reconnect at once, and spreading them out keeps your servers from being flattened by the reconnect wave. In a real client, fetch a fresh ticket before each reconnect, since tickets are single use.

Key terms
WebSocket
A persistent two-way connection that starts as an HTTP request and upgrades with 101 Switching Protocols.
Server-Sent Events
A long HTTP response of text/event-stream events, server to client only, with automatic browser reconnects.
connection manager
An object in each worker that tracks which local sockets belong to which room.
pub/sub fan-out
Publishing each message to a shared channel so every worker can deliver it to its own sockets.
close code 1008
The WebSocket close code for a policy violation, used to reject unauthorised connections.
cross-site WebSocket hijacking
Another site opening a socket with your user's cookies. Prevented by checking the Origin header.