0
0
FastAPIframework~8 mins

WebSocket endpoint creation in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: WebSocket endpoint creation
MEDIUM IMPACT
This affects the responsiveness and resource usage of real-time communication on the page, impacting interaction speed and server load.
Creating a WebSocket endpoint to handle multiple client connections efficiently
FastAPI
from fastapi import FastAPI, WebSocket
from fastapi.websockets import WebSocketDisconnect
app = FastAPI()

class ConnectionManager:
    def __init__(self):
        self.active_connections: list[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.broadcast(f"Client says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
Manages connections efficiently, broadcasts messages to all clients, and handles disconnects gracefully, reducing resource leaks and improving responsiveness.
📈 Performance GainReduces memory leaks and CPU spikes, improving INP by handling multiple clients concurrently and cleanly.
Creating a WebSocket endpoint to handle multiple client connections efficiently
FastAPI
from fastapi import FastAPI, WebSocket
app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")
This endpoint handles each connection sequentially without managing connections or limiting resource use, which can cause high memory and CPU usage under many clients.
📉 Performance CostCan cause high CPU usage and memory growth with many clients, increasing server response time and INP delays.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Basic WebSocket endpoint without connection management0 (server-side)00[X] Bad
WebSocket endpoint with connection manager and broadcast0 (server-side)00[OK] Good
Rendering Pipeline
WebSocket endpoints do not directly affect browser rendering but impact interaction responsiveness by maintaining open connections for real-time data exchange.
Network
JavaScript Execution
⚠️ BottleneckServer resource management and message handling can bottleneck responsiveness if not optimized.
Core Web Vital Affected
INP
This affects the responsiveness and resource usage of real-time communication on the page, impacting interaction speed and server load.
Optimization Tips
1Always manage WebSocket connections to avoid resource leaks.
2Avoid blocking operations inside WebSocket handlers to keep responsiveness high.
3Reuse WebSocket connections instead of opening new ones for each message.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a key performance benefit of managing WebSocket connections with a connection manager in FastAPI?
AIt automatically compresses WebSocket data to speed up transmission.
BIt reduces the size of the WebSocket messages sent over the network.
CIt prevents memory leaks by tracking and cleaning up disconnected clients.
DIt eliminates the need for asynchronous code in WebSocket handlers.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by WS (WebSocket), and observe the open WebSocket connection and message frames.
What to look for: Check if the WebSocket connection stays open without errors and messages are sent/received promptly without delays.