Real-time & WebSockets

Request/response is a letter; realtime is a phone call. WebSockets give your FastAPI apps a live wire — streaming LLM tokens, chat, dashboards — and webhooks give the outside world a way to call YOU.

▶ Watch this reel

What you'll learn

  1. WebSockets: the live wire
  2. Building realtime apps
  3. Webhooks: inbound events
  4. Production hardening

Remember this

WebSockets

Patterns

Webhooks

Production

Cross-links

GA-07 (streaming latency), AG-19 (async jobs, idempotency — the same trio), AG-23 (secrets/trust), GA-28 (realtime voice rides these wires), PY-21 (Redis for the backbone and dedupe store).

Code: Realtime, end to end

# The live pipeline:
#   browser ↔ WebSocket ↔ FastAPI ↔ LLM stream
#   world   → webhook  → FastAPI → queue → broadcast

@app.websocket("/live/{room}")
async def live(ws: WebSocket, room: str):
    await manager.join(room, ws)
    beat = asyncio.create_task(heartbeat(ws))
    try:
        async for token in llm.stream(await ws.receive_text()):
            await ws.send_text(token)          # tokens as they're born
        await ws.send_text("[DONE]")
    except WebSocketDisconnect:
        pass
    finally:
        beat.cancel()

# Heartbeat in the background, tokens in the foreground,
# disconnects handled in the finally — a socket that
# survives production is a socket with all three.