On this page

FastAPI WebSockets – Real-Time Task Updates

Published on August 16, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

An HTTP request follows a fixed shape: the client asks, the server answers, and the connection closes — every new piece of information requires the client to ask again. That works poorly for anything the server needs to push out unprompted, a task update another user just made, a notification, a chat message arriving from someone else. WebSockets solve this by keeping a single connection open in both directions for as long as the session lasts, so either side can send a message the moment it has one, with no request required first. Building this into a Task Manager API means adding a WebSocket endpoint that broadcasts a structured JSON event to every connected client the instant a task is created or updated.


Installing the websockets Package​

FastAPI's WebSocket support depends on the websockets Python library, which isn't bundled by default:


pip install websockets

Without it installed, a WebSocket endpoint fails at runtime with an import error the first time it's reached.


WebSockets vs. HTTP​

An HTTP request follows a strict pattern: the client opens a TCP connection, sends a request, receives a response, and the connection closes — every subsequent interaction requires a brand new request from the client.

A WebSocket connection begins the same way, as an HTTP request, but carries an Upgrade: websocket header. Once the server accepts that upgrade, the connection is promoted to a persistent, full-duplex TCP channel, and from that point forward both sides can send messages independently at any time, with no request-response ceremony at all. The connection stays open until one side closes it explicitly or a network failure ends it.

The direct consequence for FastAPI: a WebSocket endpoint never returns a response the way an HTTP route does. It runs an infinite async loop instead, waiting for messages and sending them, until a WebSocketDisconnect exception signals that the client is gone.


The WebSocket Connection Lifecycle​

Every FastAPI WebSocket endpoint follows the same four-stage pattern. Accept: await websocket.accept() completes the HTTP Upgrade handshake, and the connection isn't actually established until this runs. Communicate: an async loop reads incoming messages and sends responses for as long as the connection stays open. Disconnect: once the client disconnects, the next read or write operation raises WebSocketDisconnect, which has to be caught explicitly rather than left to propagate. Clean up: the except WebSocketDisconnect block is where the connection gets removed from whatever tracking structure holds it.


A Simple Echo Endpoint​

A minimal WebSocket endpoint that echoes every received message straight back to the sender:


from fastapi import FastAPI, WebSocket, WebSocketDisconnect



app = FastAPI()



@app.websocket("/ws/echo")

async def websocket_echo(websocket: WebSocket):

    await websocket.accept()

    try:

        while True:

            data = await websocket.receive_text()

            await websocket.send_text(f"Echo: {data}")

    except WebSocketDisconnect:

        pass  # Client disconnected cleanly — nothing to clean up here

WebSocketDisconnect is imported from fastapi and needs to be caught by name specifically. A bare except: clause catches everything, including SystemExit and KeyboardInterrupt — signals the interpreter itself uses to shut down cleanly — and swallowing those silently is what makes a server hard or impossible to stop normally, on top of masking any real application bug underneath it.


The ConnectionManager Class​

Encapsulating connection tracking in a dedicated ConnectionManager class, rather than a bare module-level list, keeps every operation on that list going through one controlled interface instead of being modifiable from anywhere in the codebase — a habit that makes bugs in connection handling far easier to trace back to their source.

routers/ws.py:


from fastapi import APIRouter, WebSocket, WebSocketDisconnect

import asyncio



router = APIRouter(prefix="/ws", tags=["WebSockets"])





class ConnectionManager:

    def __init__(self):

        self.active_connections: list[WebSocket] = []

        self._lock = asyncio.Lock()



    async def connect(self, websocket: WebSocket):

        await websocket.accept()

        async with self._lock:

            self.active_connections.append(websocket)



    async def disconnect(self, websocket: WebSocket):

        async with self._lock:

            if websocket in self.active_connections:

                self.active_connections.remove(websocket)



    async def broadcast(self, message: dict):

        """

        Send a JSON message to every connected client.

        Connections that fail mid-broadcast are removed automatically.

        """

        stale: list[WebSocket] = []



        async with self._lock:

            targets = list(self.active_connections)  # iterate over a copy



        for connection in targets:

            try:

                await connection.send_json(message)

            except Exception:

                stale.append(connection)



        if stale:

            async with self._lock:

                for ws in stale:

                    if ws in self.active_connections:

                        self.active_connections.remove(ws)





manager = ConnectionManager()





@router.websocket("/tasks")

async def task_updates(websocket: WebSocket):

    await manager.connect(websocket)

    try:

        while True:

            # receive_text() keeps the connection alive.

            # Messages from the client are discarded — this endpoint is

            # server-to-client only. A future iteration could process

            # client commands here.

            await websocket.receive_text()

    except WebSocketDisconnect:

        await manager.disconnect(websocket)

Why send_json instead of send_text​

send_json serializes a Python dictionary directly into a JSON string and sends it in a single call. A structured event like {"event": "task_created", "task_id": 42, "title": "Write tests"} gives a client everything it needs to update its UI without any additional parsing logic on its end — building the same string manually through send_text is fragile and pushes formatting concerns onto whatever's consuming it.

Why the broadcast loop uses a copy​

Removing a stale connection from self.active_connections while a for loop is actively iterating over that exact list raises RuntimeError: list changed size during iteration. broadcast avoids this by taking a snapshot of the current connections under the lock, iterating that snapshot, and only removing stale entries afterward, in a separate pass.

Why asyncio.Lock is used​

FastAPI runs on a single async event loop where multiple coroutines can be mid-execution at once. Two simultaneous requests that each trigger a broadcast can end up reading and writing active_connections in an interleaved order, corrupting the list's internal state. asyncio.Lock ensures only one coroutine modifies the list at a time — distinct from a threading lock, since it coordinates coroutines within a single event loop thread rather than actual OS threads.


Broadcasting Task Events from the Task Router​

The broadcast has to happen after the task is successfully committed to the database, never before — broadcasting first and having the database operation fail afterward would inform every connected client about a task that was never actually saved.

routers/tasks.py (updated create and update endpoints):


from fastapi import APIRouter, Depends

from sqlmodel import Session

from db import get_session

from models.task import Task

from models.user import User

from services import task_service

from core.dependencies import require_active_user

from routers.ws import manager   # import the shared ConnectionManager instance



router = APIRouter(prefix="/tasks", tags=["Tasks"])





@router.post("/", status_code=201)

async def create(

    task: Task,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    created = task_service.create_task(task, session, user)

    # Broadcast only after the task is persisted

    await manager.broadcast({

        "event":   "task_created",

        "task_id": created.id,

        "title":   created.title,

        "user_id": created.user_id,

    })

    return created





@router.put("/{task_id}")

async def update(

    task_id: int,

    updated: Task,

    session: Session = Depends(get_session),

    user: User = Depends(require_active_user),

):

    task = task_service.update_task(task_id, updated, session, user)

    # Broadcast only after the update is persisted

    await manager.broadcast({

        "event":     "task_updated",

        "task_id":   task.id,

        "title":     task.title,

        "completed": task.completed,

        "user_id":   task.user_id,

    })

    return task

Both endpoints are declared async def specifically because their bodies now contain await manager.broadcast(...) — Python requires async def on any function containing an await expression. FastAPI itself handles def and async def route functions identically otherwise; this change is required by the language, not by anything FastAPI-specific about routing or dependency injection.


Registering the WebSocket Router in main.py​


from routers.ws import router as ws_router



app.include_router(ws_router)

Testing the WebSocket Endpoint​

With a browser console​

Pasting the following into any page's developer console connects directly and logs every event received:


const ws = new WebSocket("ws://localhost:8000/ws/tasks");

ws.onmessage = (event) => console.log("Received:", JSON.parse(event.data));

ws.onopen = () => console.log("Connected");

ws.onclose = () => console.log("Disconnected");

Creating or updating a task through the REST API — Swagger UI at /docs, or curl — logs the corresponding JSON event to the console in real time.

With websocat (command-line)​

websocat is a lightweight command-line WebSocket client:


# macOS

brew install websocat



# Linux

cargo install websocat

websocat ws://localhost:8000/ws/tasks

Any task creation or update through the REST API prints its JSON event directly to the terminal.

With FastAPI's TestClient​

TestClient provides websocket_connect for testing a WebSocket endpoint without a separate client:


from fastapi.testclient import TestClient

from main import app



client = TestClient(app)



def test_websocket_receives_task_event():

    with client.websocket_connect("/ws/tasks") as ws:

        # Trigger a task creation via the REST API

        client.post(

            "/tasks/",

            json={"title": "Test task", "completed": False},

            headers={"Authorization": "Bearer <valid_token>"},

        )

        data = ws.receive_json()

        assert data["event"] == "task_created"

        assert data["title"] == "Test task"

WebSocket Message Reference​

MethodDirectionDescriptionawait websocket.accept()ServerCompletes the HTTP Upgrade handshakeawait websocket.send_text(str)Server → ClientSend a plain text messageawait websocket.send_json(dict)Server → ClientSerialize and send a JSON messageawait websocket.send_bytes(bytes)Server → ClientSend raw binary dataawait websocket.receive_text()Client → ServerWait for a text messageawait websocket.receive_json()Client → ServerWait for and deserialize a JSON messageawait websocket.receive_bytes()Client → ServerWait for binary dataawait websocket.close(code)ServerClose the connection with an optional status code

WebSocketDisconnect is raised on any receive_* or send_* call once the client has already disconnected, and is imported directly from fastapi.


Authenticating WebSocket Connections​

Browsers can't set custom HTTP headers on a WebSocket connection, which rules out sending a JWT through an Authorization header the way a normal REST request would. The standard workaround is passing the token as a query parameter at connection time, then validating it inside the endpoint before the connection is ever accepted.

FastAPI's own current documentation shows WebSocketException, raised before accept() is called, as the way to reject a connection cleanly — FastAPI catches it internally and closes the connection with the code provided, without the route needing to call close() and return manually:


from fastapi import APIRouter, WebSocket, WebSocketDisconnect, WebSocketException, Query, status

from core.jwt import decode_access_token



@router.websocket("/tasks")

async def task_updates(

    websocket: WebSocket,

    token: str = Query(...),

):

    payload = decode_access_token(token)

    if not payload or "sub" not in payload:

        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)



    await manager.connect(websocket)

    try:

        while True:

            await websocket.receive_text()

    except WebSocketDisconnect:

        await manager.disconnect(websocket)

The client connects as ws://localhost:8000/ws/tasks?token=<jwt_token>. WS_1008_POLICY_VIOLATION is a standard WebSocket close code meaning the connection was closed because it violated a policy the server enforces — appropriate here for a missing or invalid token. One current limitation worth knowing about either approach, WebSocketException or a manual close() call: the close reason isn't reliably surfaced to every kind of client, particularly non-Python ones, since a standardized way to expose a rejection reason during the WebSocket handshake itself is still an evolving part of the surrounding specification.

Query parameters land in server access logs by default, which is worth keeping in mind for a highly sensitive token — passing credentials through the first message sent immediately after connection, validated before anything else is processed, avoids that specific exposure at the cost of slightly more connection-setup code.


Scaling Considerations​

The ConnectionManager built here stores every connection in a single Python process's memory, which is entirely correct for a single-process deployment.

Running the application with multiple worker processes — uvicorn main:app --workers 4 — changes this: each worker is a separate Python interpreter with its own memory space and its own independent ConnectionManager instance. A broadcast issued inside worker 1 only reaches clients that happen to be connected to worker 1; clients connected to workers 2, 3, or 4 receive nothing at all, with no error indicating the message never reached them.

Fixing this for a multi-process or multi-instance deployment requires a shared message broker — Redis pub/sub is the most common choice. Every worker subscribes to the same Redis channel, and when any worker needs to broadcast, it publishes to that channel instead of iterating its own local connection list directly; every worker, including the one that published, then relays the message to whichever clients are connected to it locally. This turns the broadcast from "reaches whichever worker happens to hold the connection" into "reaches every connection across every worker," at the cost of introducing Redis as a new piece of infrastructure the deployment now depends on.


Common Mistakes to Avoid​

Using a bare except: clause swallows everything, including KeyboardInterrupt and SystemExit, which masks real bugs and makes the server difficult to stop cleanly — catching WebSocketDisconnect by name, with a separate except Exception only where genuine recovery logic exists, avoids this. Broadcasting before the database commit means a failed write still notifies every connected client about a task that doesn't actually exist — the broadcast belongs strictly after a confirmed successful commit. Modifying active_connections while directly iterating over it raises RuntimeError; iterating a copy and removing stale entries in a separate pass afterward avoids the crash entirely. Never removing disconnected clients lets active_connections grow without bound, with every subsequent broadcast attempting — and failing — to reach connections that are already gone, degrading performance over time. And assuming multi-worker broadcasts work correctly with purely in-memory state doesn't hold: each worker process is fully isolated from the others, and a shared broker like Redis pub/sub is what's required the moment more than one worker is running.

Frequently Asked Questions​

What are WebSockets and how are they different from HTTP in FastAPI?

HTTP follows a request-response pattern: the client sends a request, the server replies, and the connection closes. WebSockets begin as an HTTP request with an Upgrade header, after which the connection is promoted to a persistent, full-duplex TCP channel. Both client and server can send messages independently at any time without any request-response ceremony. This makes WebSockets suitable for live updates, notifications, and chat where the server must push data to clients unprompted.

How do I create a WebSocket endpoint in FastAPI?

Decorate an async function with @app.websocket("/path") or @router.websocket("/path") and accept a WebSocket parameter. Inside the function, call await websocket.accept() to complete the handshake, then run an async loop calling await websocket.receive_text() or receive_json() to read messages and send_text() or send_json() to respond. Wrap the loop in try/except WebSocketDisconnect to handle client disconnections cleanly.

What is WebSocketDisconnect in FastAPI and why must I catch it?

WebSocketDisconnect is the exception Starlette raises on any receive or send operation when the client has already closed the connection — for example when a user closes a browser tab. It must be caught explicitly so the endpoint can remove the closed connection from any tracking structure. Without catching it, the exception propagates as an unhandled error. It is imported from fastapi: from fastapi import WebSocketDisconnect.

Why should I never use a bare except clause in a FastAPI WebSocket endpoint?

A bare except clause catches everything, including SystemExit, KeyboardInterrupt, and GeneratorExit — signals that Python and the operating system use to stop a process normally. Catching them silently makes the server difficult or impossible to stop, masks application bugs, and hides unexpected exceptions that should propagate. Always catch WebSocketDisconnect by name and use a separate except Exception block only when you have specific recovery logic for unexpected errors.

What is a ConnectionManager in FastAPI WebSockets?

A ConnectionManager is a class that encapsulates the list of active WebSocket connections and all operations on it: connecting a client, disconnecting a client, and broadcasting messages. Keeping connections in a bare module-level list allows any code in the project to modify it directly, which makes bugs hard to trace. A ConnectionManager controls access through defined methods and can incorporate thread-safety primitives like asyncio.Lock.

How do I broadcast a message to all connected WebSocket clients in FastAPI?

Maintain a list of active WebSocket objects in a ConnectionManager. In the broadcast method, iterate over a copy of the list and call await connection.send_json(message) for each client. Catch exceptions on individual sends to identify stale connections, then remove them from the list in a second pass after the loop. Iterating over a copy prevents RuntimeError from modifying the list while iterating it.

Why should broadcast happen after the database commit and not before?

If the broadcast fires before the database operation and the operation subsequently fails, every connected client receives a notification for a task that was never actually saved. The broadcast must happen after a confirmed successful commit so that clients are only informed of state changes that are durable in the database.

Why do the task router endpoints use async def after adding WebSocket broadcasting?

Python requires the async def keyword on any function that contains an await expression. Because the updated create and update endpoints call await manager.broadcast(), they must be declared as async def. FastAPI handles both def and async def route functions correctly — the change in keyword does not affect routing or dependency injection behaviour.

What is the difference between send_text and send_json in FastAPI WebSockets?

send_text sends a raw string to the client. send_json accepts a Python dictionary, serializes it to a JSON string automatically, and sends it. For structured event messages — such as {"event": "task_created", "task_id": 42} — send_json is the correct choice because it produces consistently structured data that clients can parse reliably, without manual string formatting.

How do I install WebSocket support for FastAPI?

Install the websockets Python package: pip install websockets. FastAPI does not bundle this dependency by default. Without it, WebSocket endpoints will fail at runtime with an import error.

How do I test a FastAPI WebSocket endpoint?

Use FastAPI TestClient with the websocket_connect context manager: with client.websocket_connect("/ws/tasks") as ws: data = ws.receive_json(). Alternatively, use a browser JavaScript console with new WebSocket("ws://localhost:8000/ws/tasks") and an onmessage handler, or use the websocat command-line tool. Swagger UI does not support WebSocket endpoints natively.

How do I authenticate a WebSocket connection in FastAPI?

Browsers cannot set custom HTTP headers on WebSocket connections, so the JWT cannot be sent in an Authorization header. The standard approach is to pass the token as a query parameter: ws://localhost:8000/ws/tasks?token=<jwt>. Inside the endpoint, decode and validate the token before calling websocket.accept(). If validation fails, raise WebSocketException(code=...) rather than calling accept() at all — FastAPI closes the connection with the given code automatically.

What happens if I do not remove disconnected clients from active_connections?

The connections list grows indefinitely over time as clients connect and disconnect. Every broadcast attempts to send to all entries including closed connections, which raises exceptions on every stale socket. This degrades broadcast performance, produces unhandled errors, and eventually causes memory growth proportional to the total number of connections ever made rather than the number currently active.

Why is asyncio.Lock needed in the ConnectionManager?

FastAPI runs on an async event loop where multiple coroutines can execute concurrently. Two simultaneous HTTP requests that each trigger a broadcast can both read and write active_connections in an interleaved fashion, corrupting the list. asyncio.Lock ensures only one coroutine modifies the connections list at a time, preventing race conditions. Note that asyncio.Lock is not the same as a threading lock — it is non-blocking and works within a single event loop thread.

Why does iterating active_connections directly during broadcast cause a RuntimeError?

Python raises RuntimeError: list changed size during iteration when a list is modified while a for loop is iterating over it. If a stale connection is removed from active_connections during the broadcast loop, the iterator loses its position and crashes. The solution is to iterate over a copy of the list — list(self.active_connections) — and remove stale entries in a separate pass after the loop completes.

Do FastAPI WebSocket broadcasts work with multiple Uvicorn workers?

No. Each worker process runs its own Python interpreter with its own memory space and its own ConnectionManager instance. A broadcast issued by worker 1 only reaches clients connected to worker 1. Clients connected to other workers receive nothing. For multi-process or multi-instance deployments, a shared message broker such as Redis pub/sub is required so that all workers publish to and subscribe from a shared channel.

How does the receive_text keep-alive pattern work in the WebSocket endpoint?

The server-side task updates endpoint does not process messages from clients — it only broadcasts outbound events. However, the async loop must keep running to hold the connection open and detect disconnection. Calling await websocket.receive_text() in an infinite loop achieves this: it suspends the coroutine until either a message arrives (which is discarded) or the client disconnects (which raises WebSocketDisconnect and triggers cleanup). Without this loop, the endpoint function would return immediately and the connection would close.

What is the WebSocket connection lifecycle in FastAPI?

The lifecycle has four stages. First, accept: await websocket.accept() completes the HTTP Upgrade handshake and establishes the persistent connection. Second, communicate: an async loop exchanges messages using receive and send methods. Third, disconnection: when the client closes the connection, the next receive or send call raises WebSocketDisconnect. Fourth, cleanup: the except WebSocketDisconnect block removes the connection from any tracking structures and releases resources.

Should I use websocket.close() or raise WebSocketException to reject a connection?

WebSocketException, raised before calling accept(), is the pattern shown in FastAPI's own current documentation and is generally the cleaner choice — FastAPI catches it internally and closes the connection with the given code. Calling websocket.close(code=...) manually still works and remains valid. One current limitation worth knowing either way: the reason text isn't reliably visible to every WebSocket client, particularly non-Python ones, since a standardized way to surface a rejection reason over the WebSocket handshake itself is still an evolving part of the ASGI specification.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Background Tasks and Asynchronous Operations

Next

Testing FastAPI Applications