0
0
FastAPIframework~8 mins

Why WebSockets enable real-time communication in FastAPI - Performance Evidence

Choose your learning style9 modes available
Performance: Why WebSockets enable real-time communication
HIGH IMPACT
WebSockets impact the interaction responsiveness and reduce network overhead for real-time data exchange.
Sending frequent updates from server to client in real-time
FastAPI
from fastapi import FastAPI, WebSocket
import asyncio

app = FastAPI()

@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    for i in range(10):
        await websocket.send_text(f'{i}')
        await asyncio.sleep(1)
    await websocket.close()
Keeps a single persistent connection open, reducing handshake overhead and enabling instant message delivery.
📈 Performance GainSingle connection with no repeated handshakes, reducing latency and CPU load
Sending frequent updates from server to client in real-time
FastAPI
import time
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.get('/stream')
async def stream():
    def event_generator():
        for i in range(10):
            yield f'data: {i}\n\n'
            time.sleep(1)
    return StreamingResponse(event_generator(), media_type='text/event-stream')
Uses HTTP streaming which keeps the connection open but can still cause latency and overhead compared to WebSockets.
📉 Performance CostTriggers HTTP overhead and potential latency due to lack of full-duplex communication
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
HTTP Polling or StreamingMultiple connections opened/closedMultiple reflows if UI updates per messageHigher paint cost due to delayed updates[X] Bad
WebSocket Persistent ConnectionSingle connection maintainedMinimal reflows triggered only on data updateLower paint cost with instant updates[OK] Good
Rendering Pipeline
WebSocket communication bypasses repeated HTTP request-response cycles, maintaining an open channel that allows immediate data transfer, improving interaction responsiveness.
Network
JavaScript Execution
Rendering
⚠️ BottleneckNetwork latency and handshake overhead in HTTP polling
Core Web Vital Affected
INP
WebSockets impact the interaction responsiveness and reduce network overhead for real-time data exchange.
Optimization Tips
1Use WebSockets to keep a single open connection for real-time data.
2Avoid repeated HTTP requests to reduce network latency and CPU load.
3Monitor WebSocket frames in DevTools Network panel to ensure persistent connection.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using WebSockets over HTTP polling for real-time updates?
ASends larger data packets to reduce network usage
BMaintains a single persistent connection reducing handshake overhead
CAutomatically caches data on the client to speed up rendering
DUses multiple connections to parallelize data transfer
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by WS to see WebSocket frames and connection status.
What to look for: Look for a single persistent WebSocket connection with frequent small frames instead of many HTTP requests.