← Blog
A lavender tabletop intercom with an ivory speaker grille and an orange talk button.
Published on
2026-11-19

FastAPI WebSockets: authentication, limits, and disconnects

FastAPI WebSockets let a client and server exchange messages over a connection that stays open. Use a WebSocket endpoint when the interaction needs messages in both directions, such as an application control channel or collaborative activity. The endpoint also needs rules for who may connect, which messages it accepts, and how it releases resources when the connection ends.

This guide builds an authenticated local service with a Python client. It tests the actual network connection, including rejection, message limits, disconnects, and shutdown. The example is deliberately small: it acknowledges valid text and stores no application data.

Define the interaction before opening the connection

A WebSocket keeps a communication channel available after the initial handshake. That can support ongoing interaction, but an open connection does not provide durable message delivery, replay, or shared state across application workers. If you only need a stream from server to client, the SSE and WebSockets comparison explains that earlier protocol choice.

Our contract accepts one JSON object with exactly two fields: type, which must be echo, and text, a string of 1 to 200 characters. It replies with an ack object containing that text. Each connection receives its own response. There is no room broadcast or queue of work to resume later.

The FastAPI WebSocket tutorial covers route declaration and message exchange. Here, the useful addition is a complete connection policy that we can exercise with real clients.

Authenticate before accepting the handshake

The example requires one Authorization: Bearer … header and one exact Origin value. It rejects missing, incorrect, or duplicate credentials before calling accept(). It also rejects an absent or unexpected Origin. The Python client supplies that header itself, which shows why Origin is a policy check rather than proof of identity.

This is service-client authentication using a shared demonstration token. It does not implement user accounts, token expiry, revocation, or per-user permissions. In a real application, resolve the credential to an identity and authorize each operation against the resources that identity may use. A successful handshake does not grant permission to every subsequent action.

A browser’s native WebSocket API cannot set an arbitrary Authorization header the way this Python client does. A browser application needs a separately designed and tested credential flow, such as an authenticated session with suitable origin checks. Avoid putting durable credentials in a query string. The websockets authentication guide explains the client differences and URL exposure risk.

In this stack, calling close() before acceptance rejects the handshake with HTTP 403. It does not deliver a WebSocket close frame to an already connected client. This behavior is documented by Starlette and was checked in the running example.

Build a bounded FastAPI endpoint

Create an isolated Python environment and install these versions. The example was tested with Python 3.12.14 on Windows.

python -m pip install fastapi==0.163.1 starlette==1.10.0 uvicorn==0.54.0 websockets==17.3

Save the following as ws_app.py. The application allows two connections in this process, checks each message’s UTF-8 byte length, and removes its registration in a finally block. The two-connection limit is chosen to make rejection easy to test; it is not a capacity recommendation.

import asyncio
import json
import logging
import secrets
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

ORIGIN = "http://localhost:3000"
MAX_BYTES = 1024
MAX_TEXT = 200
MAX_CONNECTIONS = 2
logger = logging.getLogger("ws_demo")


def acknowledge(text):
    return {"type": "ack", "text": text}


async def close_connection(ws, code, reason):
    try:
        await asyncio.wait_for(ws.close(code=code, reason=reason), timeout=1)
    except (WebSocketDisconnect, OSError, RuntimeError, TimeoutError):
        pass


def create_app(token, idle_seconds=15, transform=acknowledge):
    if not isinstance(token, str) or len(token) < 32 or not token.isascii():
        raise ValueError("Supply an ASCII demo token of at least 32 characters")
    app = FastAPI()
    active = set()
    app.state.active = active

    @app.websocket("/ws")
    async def endpoint(ws: WebSocket):
        headers = ws.headers.getlist("authorization")
        if (len(headers) != 1 or not secrets.compare_digest(
                headers[0].encode("utf-8"), ("Bearer " + token).encode("ascii"))
                or ws.headers.getlist("origin") != [ORIGIN]
                or len(active) >= MAX_CONNECTIONS):
            await ws.close(code=1008)
            return
        marker = object()
        active.add(marker)
        try:
            await ws.accept()
            while True:
                message = await asyncio.wait_for(ws.receive(), idle_seconds)
                if message["type"] == "websocket.disconnect":
                    break
                raw = message.get("text")
                if raw is None:
                    await close_connection(ws, 1003, "Text messages only")
                    break
                if len(raw.encode("utf-8")) > MAX_BYTES:
                    await close_connection(ws, 1009, "Message too large")
                    break
                try:
                    data = json.loads(raw)
                except (ValueError, RecursionError):
                    await close_connection(ws, 1007, "Invalid JSON")
                    break
                if (not isinstance(data, dict) or set(data) != {"type", "text"}
                        or data["type"] != "echo" or not isinstance(data["text"], str)
                        or not 1 <= len(data["text"]) <= MAX_TEXT):
                    await close_connection(ws, 1008, "Invalid message fields")
                    break
                response = transform(data["text"])
                await asyncio.wait_for(ws.send_json(response), timeout=5)
        except TimeoutError:
            await close_connection(ws, 1008, "Time limit reached")
        except (WebSocketDisconnect, OSError):
            pass
        except Exception:
            logger.error("WebSocket handler failed; connection closed")
            await close_connection(ws, 1011, "Internal error")
        finally:
            active.discard(marker)

    return app

There are several independent limits. The application accepts at most 1,024 UTF-8 bytes per message and at most 200 characters in the text field. It waits up to 15 seconds for the next application message and applies a five-second wait to sending a response. Those asynchronous waits depend on the event loop continuing to run; they are not a substitute for moving blocking work out of the handler.

The handler accepts text frames only. Malformed JSON closes with code 1007, invalid fields with 1008, unsupported binary messages with 1003, and an oversized message with 1009. Unexpected handler exceptions produce a generic 1011 close and a log entry that excludes the payload and credential. The test deliberately injects an exception to check that path; normal client text cannot request it.

Notice that TimeoutError is handled before OSError, because it is a subclass of it. The first version of the example caught the broader error too early and ended the connection without the intended timeout close message. A real-client test caught that behavior.

Run the server and connect a Python client

Save this as server.py beside the application. It binds only to the local loopback address. The selected Uvicorn WebSocket implementation is explicit, and its transport message limit is 4,096 bytes. The lower application limit still applies after a message reaches the handler. See the Uvicorn settings reference when choosing limits for another implementation or version.

import os
import uvicorn
from ws_app import create_app


def server_config(app, port=8765):
    return uvicorn.Config(
        app, host="127.0.0.1", port=port, loop="asyncio", http="h11",
        ws="websockets-sansio", ws_max_size=4096,
        proxy_headers=False, access_log=False, log_level="warning",
        timeout_graceful_shutdown=3,
    )


if __name__ == "__main__":
    app = create_app(os.environ["WS_DEMO_TOKEN"])
    uvicorn.Server(server_config(app)).run()

Save the client as client.py in the same directory. It uses a context manager to close its connection, and separate timeouts for opening, receiving, and closing.

import json
import os
from websockets.sync.client import connect


def exchange(uri="ws://127.0.0.1:8765/ws"):
    token = os.environ["WS_DEMO_TOKEN"]
    with connect(uri, origin="http://localhost:3000",
                 additional_headers={"Authorization": "Bearer " + token},
                 proxy=None, open_timeout=3, close_timeout=2,
                 max_size=4096) as ws:
        ws.send(json.dumps({"type": "echo", "text": "Hello"}))
        return json.loads(ws.recv(timeout=3))


if __name__ == "__main__":
    print(exchange())

In two terminals using the same Python environment, set WS_DEMO_TOKEN to the same newly generated random ASCII secret of at least 32 characters. A password manager can generate it. Start python server.py in one terminal, then run python client.py in the other. The client exchange returns {'type': 'ack', 'text': 'Hello'}. Stop the local server when finished.

The client’s http://localhost:3000 Origin is a deliberate test value; no browser or HTTP page needs to run there. The ws:// address is for this local demonstration. Use an authenticated, encrypted wss:// path for remote traffic and verify that path separately.

Check failures and connection cleanup

The exact application and client passed 45 functional checks over real loopback TCP connections with FastAPI 0.163.1, Starlette 1.10.0, Uvicorn 0.54.0, and websockets 17.3. These checks did not use an in-process HTTP test client.

CaseObserved result
Missing, incorrect, or duplicate authorization; invalid OriginHTTP 403 before upgrade; no active registration left behind
Two accepted clients, then a thirdTwo independent responses; third handshake rejected
Repeated exchanges, 200-character text and UnicodeExpected acknowledgments on the same connection
Application and transport size boundaries1,024 bytes accepted; 1,025 rejected; oversized single and fragmented transport messages closed with 1009
Malformed JSON, binary messages and invalid fieldsExpected 1007, 1003 or 1008 close; registration released
Graceful close and abrupt TCP disconnectActive-connection state returns to zero
Idle connection and injected handler exception1008 or 1011 close; state released; error log omits payload and credential
Graceful Uvicorn shutdown with an active client1012 close received; registration removed; server thread finishes

The idle test shortened the configured wait to 0.25 seconds. The handler-error test supplied a failing function through the application factory. Shutdown used Uvicorn’s graceful server-stop path. Those controlled conditions should not be read as a browser test, a slow-consumer saturation test, a Linux deployment, or a load benchmark.

A connection’s Ping/Pong exchange checks the transport; it does not mean your application received a useful message. Keep transport health, application inactivity, and business completion separate in monitoring. The example’s cleanup releases process-local registration. It does not undo a database write or cancel an external job.

Decide what reconnecting and multiple workers mean

Reconnecting creates a new connection. This example has no record of the old session’s messages, so it cannot resume missed work. If a client must recover after interruption, define message identifiers, acknowledgments, retention, and replay rules. For operations with side effects, decide how a repeated message is recognized before adding automatic retries.

The active-connection set belongs to one Python process. Starting more workers creates more independent sets and changes the effective limit. A global admission policy or cross-worker broadcast needs shared coordination; adding workers alone supplies neither. The FastAPI tutorial also calls out the single-process scope of its in-memory connection example.

This handler performs only small parsing and response work. If a message starts a long calculation or blocking call, separate that work from the connection loop and define how cancellation and results are delivered. The Python asyncio guide explains the event-loop constraints. Message-size and connection-count limits also do not impose a messages-per-second rate limit.

Verify the hosting path before exposing the service

A working local connection leaves deployment questions to answer. Check TLS, the public reverse proxy’s WebSocket forwarding, trusted proxy headers, idle timeouts, connection limits, and what clients observe during a restart. The Caddy and Nginx comparison helps with proxy selection, but the configuration for your actual WebSocket route still needs its own test.

The FastAPI deployment guide provides the broader application-hosting steps and states which deployment checks remain untested. This article has not exercised a public proxy, TLS termination, browser credentials, or a cloud deployment.

For a service you operate on a VM, CPU instances from Compute with Hivenet are a hosting option. You manage the application, TLS and proxy path, access controls, updates, limits, and monitoring. Use the API hosting guide to compare that responsibility with managed platforms and serverless services before choosing an operating model.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.