A WebSocket is a long-lived two-way connection (used for chat, live updates and token streaming); declare it with @app.websocket, accept the connection, then loop receiving and sending messages until the client disconnects.
For broadcasts to many clients, keep a connection manager that tracks active connections; for multiple server instances, add a message broker such as Redis pub/sub.
from fastapi import WebSocket, WebSocketDisconnect
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
await ws.accept()
try:
while True:
message = await ws.receive_text()
await ws.send_text(f"echo: {message}")
except WebSocketDisconnect:
pass # client left; clean up resources here