WebSocket giữ kết nối lâu dài hai chiều, phù hợp chat, collaboration, realtime dashboard hoặc stream trạng thái. HTTP endpoint là request/response ngắn hạn.
Ví dụ cơ bản:
python
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
await ws.accept()
while True:
message = await ws.receive_text()
await ws.send_text(message)Production cần authentication khi connect, heartbeat, giới hạn connection, backpressure, broadcast layer như Redis pub/sub và cleanup khi disconnect.