Sub topic 11
Stopping work when the client disconnects
A user closes the tab halfway through an answer. Your server is still pulling tokens from the model provider for a reader who is gone. This chapter covers how FastAPI and Starlette signal that disconnect, what it takes for your code to stop, and how to test that it does.
This chapter assumes you have the /chat endpoint from the earlier chapters: an async generator that reads chunks from an AsyncOpenAI stream and yields them as Server-Sent Events (SSE) through StreamingResponse. It also assumes you know async/await, try/finally, and the basics of asyncio task cancellation.
Why a disconnect matters
An abandoned stream costs real resources:
- Provider tokens. Generation continues, and you pay for output nobody reads.
- An open upstream connection, which counts against your provider's concurrency limit.
- A server task, memory, and possibly a database connection or a rate-limit slot.
One abandoned request is cheap. Hundreds of impatient users on a slow model are not.
What Starlette does for you
StreamingResponse does not just iterate your generator. While it sends chunks, it also runs a second task that waits on the ASGI receive channel for an http.disconnect message. When that message arrives, Starlette cancels the sending task. Cancellation is delivered to your generator at whatever await it is currently suspended on, usually inside async for chunk in stream.
The following diagram shows the sequence.
Two details depend on your library versions. Older Starlette releases cancel the task. Newer ones, running on servers that implement ASGI spec 2.4 or later, may instead make send raise OSError once the client is gone. In both cases your generator is interrupted or closed, and your code should be ready for either. The rules below cover both.
Rule 1: never swallow cancellation
Since Python 3.8, asyncio.CancelledError inherits from BaseException, not Exception. That is why the endpoint's except Exception clause does not catch it. The cancellation passes through, and no "generation failed" event is produced for a client that cannot receive it.
The common way to break this is a broad handler:
try:
...
except BaseException: # or a bare "except:"
yield sse("error", {"message": "generation failed"})This catches the cancellation and then tries to yield to a dead connection. The task may not stop, or the framework may complain that the generator ignored cancellation. If you need to observe cancellation, catch it, record it, and re-raise it.
Rule 2: release resources in `finally`
Cancellation interrupts your code wherever it happens to be. The reliable place for cleanup is a finally block, which runs on normal completion, on errors, on cancellation, and when the generator is closed with aclose().
Closing the provider stream matters because it closes the HTTP connection to the provider. Most providers stop generating when that connection drops, which stops the billing. Dropping your reference to the stream does not do this reliably.
Here is the generator with cleanup and logging. Save it as streaming.py.
import asyncio
import json
import logging
import os
import anyio
logger = logging.getLogger("chat")
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def token_events(client, prompt: str):
stream = None
sent = 0
outcome = "completed"
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:
sent += 1
yield sse("token", {"text": chunk.choices[0].delta.content})
yield sse("done", {})
except (asyncio.CancelledError, GeneratorExit):
outcome = "client_disconnected"
raise
except Exception:
outcome = "error"
logger.exception("generation failed")
yield sse("error", {"message": "generation failed"})
finally:
if stream is not None:
with anyio.CancelScope(shield=True):
await stream.close()
logger.info("chat finished outcome=%s tokens_sent=%d", outcome, sent)The except clauses behave as follows:
CancelledErroris what a cancelled task sees.GeneratorExitis what a generator sees when something callsaclose()on it, for example when the response is torn down. Neither is an error, so both are labeled as a disconnect and re-raised.Exceptionhandles real failures, as in the earlier chapter, and still logs the traceback on the server.- The log line in
finallyruns once per request, whatever the outcome. Theoutcomeandtokens_sentfields let you count how many requests end in disconnects and how much output is wasted.
Rule 3: shield the cleanup
The anyio.CancelScope(shield=True) around stream.close() is easy to overlook. Starlette runs the response inside an anyio task group. Under anyio, once a scope is cancelled, every await inside it is cancelled again and again. Without the shield, await stream.close() inside finally can be interrupted before it finishes, and the upstream connection stays open. Under plain asyncio you get one cancellation, and the cleanup would work. Under anyio the shield is what makes it reliable.
Keep shielded sections short. A shielded await that hangs cannot be cancelled. If closing a stream could take long, wrap it in anyio.fail_after(...) inside the shield:
with anyio.CancelScope(shield=True), anyio.move_on_after(2):
await stream.close()anyio is already installed as a dependency of Starlette, so you need no extra package.
What cancellation does not stop
Cancellation only interrupts await points in your event loop. The following keep running:
| Work | Why it keeps running | What to do |
|---|---|---|
| Blocking calls such as `time.sleep` or a sync HTTP client | They never yield to the event loop, so cancellation cannot be delivered | Use async libraries |
| Work in a thread (`run_in_threadpool`, `asyncio.to_thread`) | The thread cannot be killed | Check a flag between steps, or avoid threads for long work |
| `BackgroundTasks` and tasks you create with `asyncio.create_task` | They are not children of the response task | Keep references and cancel them in `finally` |
| Generation inside a provider you call synchronously | The provider sees no disconnect until you close the connection | Close the stream, as in Rule 2 |
A common mistake is to start a "save the full answer to the database" task with create_task and forget it. After a disconnect it still runs and writes a partial answer. Decide whether you want that. If not, cancel the task in finally.
Polling for disconnects: a fallback
Sometimes your code is not in a StreamingResponse, or it runs a long loop with few await points. For an ordinary route, Starlette does not cancel anything on disconnect. In those cases you can ask directly:
import asyncio
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.get("/slow")
async def slow(request: Request):
for step in range(20):
if await request.is_disconnected():
return Response(status_code=499)
await asyncio.sleep(0.5) # stand-in for one unit of real work
return {"status": "finished"}Status 499 is a convention from nginx for "client closed request". The client never sees it, but it makes access logs honest.
For streaming endpoints, prefer the cancellation path in the earlier sections. Polling adds code and only checks between steps, while cancellation interrupts a wait in progress, such as the wait for the first token.
Proxies and disconnects
A reverse proxy sits between the browser and your app, so your app only sees the proxy's connection. If the proxy keeps that connection open after the browser leaves, your app never learns about the disconnect. In nginx, proxy_ignore_client_abort is off by default, which means nginx closes the upstream connection when the client aborts. Check that you have not turned it on. Also check that any load balancer in front of the app forwards client closes instead of draining the response.
Testing the cleanup
You can test this without a network. Drive the generator directly, simulate the two ways it gets interrupted, and check that the fake stream was closed. This test uses anext, which needs Python 3.10 or later, and plain asyncio.run, so no pytest plugin is needed.
import asyncio
import contextlib
from types import SimpleNamespace as NS
from streaming import token_events
class FakeStream:
def __init__(self):
self.closed = False
def __aiter__(self):
return self
async def __anext__(self):
await asyncio.sleep(0.01)
return NS(choices=[NS(delta=NS(content="x"))])
async def close(self):
self.closed = True
def make_client(stream):
async def create(**kwargs):
return stream
return NS(chat=NS(completions=NS(create=create)))
def test_stream_closed_on_aclose():
stream = FakeStream()
async def run():
gen = token_events(make_client(stream), "hi")
first = await anext(gen)
assert first.startswith("event: token")
await gen.aclose()
asyncio.run(run())
assert stream.closed
def test_stream_closed_on_cancel():
stream = FakeStream()
async def consume(gen):
async for _ in gen:
pass
async def run():
task = asyncio.create_task(consume(token_events(make_client(stream), "hi")))
await asyncio.sleep(0.05)
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
asyncio.run(run())
assert stream.closedBoth tests fail if you remove the finally block, and that is the point. The fake stream never ends on its own, so the only way closed becomes true is through your cleanup.
Checklist
- Catch
Exception, notBaseException, for error events. - Close the provider stream in
finally, inside a shielded scope. - Re-raise
CancelledErrorandGeneratorExitif you catch them. - Cancel any tasks you spawned for the request.
- Log the outcome and token count once per request.
- Confirm your proxy does not ignore client aborts.
Exercise
A teammate wraps the generator body in try: ... except BaseException: yield sse("error", {"message": "generation failed"}) so that every failure produces an error event. After a client disconnects, the server logs show warnings and the provider connection stays open. Explain what goes wrong and how to fix it.
Show answer
BaseException includes asyncio.CancelledError and GeneratorExit. When the client disconnects, the cancellation is caught, and the handler then tries to yield to a connection that is gone. That fails or is ignored, and the cancellation never propagates, so cleanup does not run as intended and the provider stream stays open. Fix it by catching Exception for error events, and by catching (asyncio.CancelledError, GeneratorExit) separately only to record the outcome and re-raise. Close the provider stream in a finally block, wrapped in anyio.CancelScope(shield=True).
Exercise
Your /chat endpoint also starts asyncio.create_task(save_transcript(...)) to store the answer. After users disconnect, partial transcripts still appear in the database. Why does cancellation not stop this task, and what are two ways to handle it?
Show answer
A task made with create_task is not a child of the response task, so cancelling the response does not cancel it. To handle it, keep a reference to the task and cancel it in the generator's finally block when the outcome is a disconnect. Alternatively, let save_transcript check the outcome and skip, or mark, partial transcripts. Which one you choose depends on whether you want to keep partial answers.