How WebSockets Work
A persistent two-way connection for server-pushed updates
Reviewed by Abhijith N M · 24 October 2026 · Editorial standards
A WebSocket starts as an HTTP request with an Upgrade header, then switches to a persistent connection. Both sides can send messages at any time without a new request. That is useful for chat, collaborative editing, live scores and dashboards. It is not automatically better than HTTP. You lose ordinary request/response semantics, caching and simple load balancing. You also need heartbeats, reconnect logic, backpressure and a plan for proxies that drop idle connections.
How WebSockets Work — Visual Breakdown
# FastAPI WebSocket example
from fastapi import WebSocket
@app.websocket("/ws/chat/{room_id}")
async def chat(websocket: WebSocket, room_id: str):
await websocket.accept() # Open the connection
try:
while True:
# Wait for a message from the client
data = await websocket.receive_text()
# Broadcast to everyone in the room
await broadcast(room_id, f"Message: {data}")
except WebSocketDisconnect:
print(f"Client left room {room_id}")Quick Concept Check
Test your understanding in 15 seconds
What HTTP status code signals a successful WebSocket upgrade?
Related Concepts
Want hands-on practice building this end-to-end?
Check out the full structured learning path with guided projects and code evaluations.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.