Real-Time WebSockets in FastAPI: Python Backend Guide

Real Time WebSockets Server Connection Python FastAPI Architecture

Polling an HTTP REST API every second introduces massive header overhead and latency bottlenecks for live chat, stock tickers, and multiplayer apps.

WebSockets (RFC 6455) provide a persistent, bidirectional, full-duplex TCP channel established through a standard HTTP 101 Switching Protocols handshake.


Step 1: Environment Setup & Dependency Installation

uvicorn[standard] includes uvloop for ultra-high performance asynchronous I/O event loops.

Create an isolated virtual environment and install the required dependencies:

# Create and activate virtual environment
python -m venv fastapi-ws-env
# Windows (PowerShell): .\fastapi-ws-env\Scripts\Activate.ps1
# Linux/macOS: source fastapi-ws-env/bin/activate

# Install project packages
pip install fastapi "uvicorn[standard]" websockets

Step 2: Architecture & HTTP vs. WebSockets Architecture

WebSockets maintain an open TCP socket between client and server, allowing either side to push messages with only 2 to 6 bytes of framing overhead.

FastAPI handles WebSocket connections natively within its AsyncIO event loop.

HTTP REST vs. Long-Polling vs. WebSockets Comparison

ProtocolChannel StateHeader OverheadDirectionalityIdeal Use Case
HTTP RESTStateless (Closed after response)High (~800 bytes per request)Client-to-Server onlyStandard CRUD database operations
Long-PollingSemi-persistent (Held until event)High (Frequent reconnects)Server-to-Client responseLegacy notifications behind strict firewalls
WebSocketsPersistent open TCP socketMinimal (2-6 bytes per message frame)Full-Duplex (Bidirectional simultaneous)Live trading charts, games, real-time chat

Step 3: Building the Real-Time WebSocket Hub

Step 3.1: Centralized Connection & Room Manager

Create an in-memory connection manager that tracks connected client sockets by room ID:

# server.py
from typing import List, Dict
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import json
import time

app = FastAPI(title="iLab Real-Time Telemetry Hub")

class ConnectionManager:
    """Manages active client sockets and room broadcasts."""
    def __init__(self):
        self.active_rooms: Dict[str, List[WebSocket]] = {}

    async def connect(self, websocket: WebSocket, room_id: str):
        await websocket.accept()
        if room_id not in self.active_rooms:
            self.active_rooms[room_id] = []
        self.active_rooms[room_id].append(websocket)
        print(f"[Connect] Client joined room '{room_id}' (Total: {len(self.active_rooms[room_id])})")

    def disconnect(self, websocket: WebSocket, room_id: str):
        if room_id in self.active_rooms:
            if websocket in self.active_rooms[room_id]:
                self.active_rooms[room_id].remove(websocket)
            if not self.active_rooms[room_id]:
                del self.active_rooms[room_id]
        print(f"[Disconnect] Client left room '{room_id}'")

    async def broadcast_to_room(self, room_id: str, message: dict):
        if room_id in self.active_rooms:
            payload_str = json.dumps(message)
            for connection in self.active_rooms[room_id]:
                try:
                    await connection.send_text(payload_str)
                except Exception:
                    pass

manager = ConnectionManager()

Step 3.2: WebSocket Endpoint with Disconnect Handling

Attach the websocket endpoint to FastAPI and listen asynchronously for message frames:

@app.websocket("/ws/{room_id}/{client_id}")
async def websocket_endpoint(websocket: WebSocket, room_id: str, client_id: str):
    await manager.connect(websocket, room_id)
    await manager.broadcast_to_room(room_id, {
        "event": "USER_JOIN",
        "client_id": client_id,
        "timestamp": time.time()
    })
    
    try:
        while True:
            data = await websocket.receive_text()
            message_obj = {
                "event": "MESSAGE",
                "sender": client_id,
                "text": data,
                "timestamp": time.time()
            }
            await manager.broadcast_to_room(room_id, message_obj)
            
    except WebSocketDisconnect:
        manager.disconnect(websocket, room_id)
        await manager.broadcast_to_room(room_id, {
            "event": "USER_LEAVE",
            "client_id": client_id,
            "timestamp": time.time()
        })

Step 4: Running & Testing the Application

Execute the application from your terminal:

uvicorn server:app --host 127.0.0.1 --port 8000 --reload

Expected terminal output verification:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process
INFO:     ('127.0.0.1', 54321) - "WebSocket /ws/dev-room/alex" [accepted]
[Connect] Client joined room 'dev-room' (Total: 1)

Step 5: Production Hardening, Edge Cases & Security

  • Horizontal Scaling via Redis Pub/Sub: When deploying across multiple server nodes behind a load balancer, use Redis Pub/Sub so messages on server A reach clients on server B.
  • Heartbeat Ping/Pong Frames: Configure 30-second ping/pong heartbeats to detect disconnected mobile clients and prevent gateway timeouts.
  • Token Authentication: Validate JWT tokens during the initial HTTP upgrade handshake before calling websocket.accept().

Step 6: Frequently Asked Questions & Troubleshooting

Q: How do I authenticate WebSocket connections in FastAPI?
A: Accept a token query parameter (/ws/{room}?token=jwt) and verify the signature in a FastAPI dependency before calling await websocket.accept().

Q: Does WebSockets work through NGINX?
A: Yes. Add 'proxy_set_header Upgrade $http_upgrade;' and 'proxy_set_header Connection upgrade;' in your NGINX configuration.

Post a Comment

0 Comments