Skip to content
cabby

FastAPI

When FastAPI streams an AI reply straight from a StreamingResponse, a dropped signal or a page reload cuts the stream in half. Put Cabby in front instead: FastAPI runs generation in BackgroundTasks and posts each chunk over HTTP with httpx, while Cabby holds the Server-Sent Events connection and keeps the stream's history in SQLite so clients can reconnect or reload and pick up every missed chunk, without Redis.

1. Run Cabby

Install Cabby, then start it in standalone mode with SSE and the SQLite broker:

cabby --norpc --noauth --sse --secret=change-me --broadcast_key=change-me-too \
  --broadcast_adapter=http --broker=sqlite --sqlite_path=./cabby.db \
  --allowed_origins=localhost:8000
  • --norpc and --noauth run Cabby standalone; signed stream names decide what each visitor can read.
  • --sse enables the Server-Sent Events endpoint at /events.
  • --broker=sqlite and --sqlite_path=./cabby.db store recent stream history in one local file. By default Cabby keeps the last 100 messages per stream for 5 minutes; adjust --history_limit and --history_ttl for longer replies (Configuration).
  • --allowed_origins limits browser connections to pages served by your FastAPI app. The value is the page's host and port, without http://.

2. Add a small helper module

Install FastAPI, Uvicorn and httpx:

pip install fastapi uvicorn httpx

Add a cabby.py helper that signs stream names and broadcasts asynchronously. CABBY_SECRET and CABBY_BROADCAST_KEY match --secret and --broadcast_key, and CABBY_BROADCAST_URL points at Cabby's HTTP broadcast endpoint:

# cabby.py
import base64
import hashlib
import hmac
import json
import os

import httpx

CABBY_SECRET = os.environ.get("CABBY_SECRET", "change-me")
CABBY_BROADCAST_KEY = os.environ.get("CABBY_BROADCAST_KEY", "change-me-too")
CABBY_BROADCAST_URL = os.environ.get("CABBY_BROADCAST_URL", "http://localhost:8080/_broadcast")

client = httpx.AsyncClient(timeout=5.0)


def sign_stream(name: str) -> str:
    encoded = base64.b64encode(json.dumps(name).encode()).decode()
    digest = hmac.new(CABBY_SECRET.encode(), encoded.encode(), hashlib.sha256).hexdigest()
    return f"{encoded}--{digest}"


async def broadcast(stream: str, data: dict) -> None:
    response = await client.post(
        CABBY_BROADCAST_URL,
        json={"stream": stream, "data": json.dumps(data)},
        headers={"Authorization": f"Bearer {CABBY_BROADCAST_KEY}"},
    )
    response.raise_for_status()

3. Stream from a background task

In main.py, POST /runs starts generation in BackgroundTasks and returns the signed stream name and start timestamp right away. Generation keeps running even if the visitor closes the tab or loses connectivity:

# main.py
import asyncio
import time
import uuid
from contextlib import asynccontextmanager

from fastapi import BackgroundTasks, FastAPI
from pydantic import BaseModel

from cabby import broadcast, client, sign_stream


@asynccontextmanager
async def lifespan(_app: FastAPI):
    yield
    await client.aclose()


app = FastAPI(lifespan=lifespan)


class PromptRequest(BaseModel):
    prompt: str


async def generate_reply(stream: str, prompt: str) -> None:
    # Replace this loop with your model SDK's async token stream.
    words = f"Streaming a reply for: {prompt}".split()
    for index, word in enumerate(words):
        prefix = "" if index == 0 else " "
        await broadcast(stream, {"delta": f"{prefix}{word}"})
        await asyncio.sleep(0.15)
    await broadcast(stream, {"done": True})


@app.post("/runs")
async def create_run(body: PromptRequest, tasks: BackgroundTasks):
    run_id = uuid.uuid4().hex
    stream = f"runs/{run_id}"
    started_at = int(time.time())
    tasks.add_task(generate_reply, stream, body.prompt)
    return {
        "run_id": run_id,
        "signed_stream": sign_stream(stream),
        "started_at": started_at,
    }

4. Subscribe and resume in the browser

Connect with the browser's built-in EventSource — no client package needed:

const params = new URLSearchParams({
  signed_stream: signedStream,
  raw: "true",
  history_since: String(startedAt),
})

const events = new EventSource(`http://localhost:8080/events?${params}`)

events.onmessage = (event) => {
  const payload = JSON.parse(event.data)
  if (payload.done) {
    events.close()
    return
  }
  output.textContent += payload.delta
}

Both kinds of interruption recover automatically:

  • Network drop: EventSource reconnects on its own and sends the Last-Event-ID header that Cabby attached to each event. Cabby uses that position ahead of history_since and replays only the chunks the browser missed.
  • Page reload or second device: opening a fresh EventSource with the same signed_stream and history_since replays every chunk from the start of the run, then switches to live tokens.
  • raw=true: omits protocol events (welcome, confirm_subscription) and sends keepalives as SSE comments (: ping), so onmessage only sees your JSON payloads.

5. Long streams, Durable Streams and WebSockets

  • Long LLM replies: raise --history_limit and --history_ttl, or group tokens into small chunks every 50–100 ms so a full reply stays well inside the history window.
  • Explicit cursors over HTTP: turn on Durable Streams with --ds and --ds_skip_auth, then read GET /ds/runs/<run_id>?offset=-1&live=sse&signed=<signed_stream> to replay from the start and track each streamNextOffset yourself.
  • WebSockets: the same sign_stream and broadcast helpers also work with @anycable/web over WebSockets, as in the Django guide.
  • Multiple Cabby nodes: swap --broker=sqlite for Redis, PostgreSQL or NATS when you scale past one server.