Sub topic 11
Stopping work when the client disconnects
This chapter assumes you have the streaming /chat endpoint from the previous chapters: an async generator wrapped in StreamingResponse, SSE framing, and an async LLM client injected with Depends. It also assumes you know try/finally and basic asyncio task cancellation.
Why disconnects matter
A user closes the tab halfway through an answer. If your server keeps reading chunks from the model, you pay for tokens nobody will read. You also hold an open connection to the provider, and under load these abandoned requests add up.
What happens on disconnect
Starlette, the framework under FastAPI, watches for the client closing the connection while it iterates your generator. When the client leaves, Starlette stops the response. Your generator is then cancelled at the await where it is currently suspended, or it is closed with aclose(). The exact mechanism varies by Starlette and server version, but your code sees the same thing: a asyncio.CancelledError or a generator close at an await or yield.
Clean up in finally
Cancellation only helps if the upstream request stops too. Close the provider stream in a finally block, and let the cancellation propagate.
import asyncio
import json
import logging
import os
from functools import lru_cache
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
app = FastAPI()
logger = logging.getLogger("chat")
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI()
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def token_events(client: AsyncOpenAI, prompt: str):
stream = None
try:
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield sse("token", {"text": chunk.choices[0].delta.content})
yield sse("done", {})
except asyncio.CancelledError:
logger.info("client disconnected, stopping generation")
raise
except Exception:
logger.exception("generation failed")
yield sse("error", {"message": "generation failed"})
finally:
if stream is not None:
await stream.close()
@app.post("/chat")
async def chat(body: ChatRequest, client: AsyncOpenAI = Depends(get_client)):
return StreamingResponse(
token_events(client, body.prompt),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)Three details matter here.
- Re-raise
CancelledError. Log it if you like, but alwaysraise. Swallowing it leaves the task running after the client has gone. - Do not yield after cancellation. Sending an
errorevent to a closed connection is pointless. In Python 3.8 and later,CancelledErrorderives fromBaseException, soexcept Exceptiondoes not catch it. Keep theCancelledErrorbranch first anyway, so the intent is clear. - Close the upstream stream.
stream.close()ends the HTTP request to the provider, so the provider can stop generating.
Checking for disconnects explicitly
Cancellation only reaches your code at an await. If the loop does long CPU work between chunks, or you must stop work that is not a stream, poll the request instead:
from fastapi import Request
async def guarded(request: Request, source):
async for item in source:
if await request.is_disconnected():
break
yield itemUse this as a backup. For the normal case, cancellation plus finally is simpler and has no polling cost.
Common mistakes
- Catching
BaseExceptionor using a bareexcept:, which swallows cancellation. - Starting background tasks with
asyncio.create_taskinside the generator. Cancelling the generator does not cancel those tasks, so keep a reference and cancel them infinally. - Testing only with a client that reads to the end. Close the connection early, for example with Ctrl+C in
curl, and confirm your log line appears.
Exercise
A teammate wraps the loop in try: ... except BaseException: yield sse("error", {"message": "failed"}). After users close their tabs, provider usage stays high. Why, and what is the fix?
Show answer
BaseException also catches asyncio.CancelledError, so the cancellation raised on disconnect is swallowed and the generator keeps going. Catch asyncio.CancelledError first and re-raise it, or catch only Exception. Also close the upstream stream in finally.