skip to content

When a user closes the browser tab mid-answer, what happens to a FastAPI 0.143 path operation still yielding a language model's tokens?

level: seniorimportance: should knowfreq 40%

answer

  1. the server reports a disconnect
  2. cancellation lands on an await
  3. threads cannot be interrupted
  4. cleanup belongs in finally
  5. request.is_disconnected() for explicit checks

basics

~20 s

Under Uvicorn, Starlette's streaming response notices the disconnect and cancels the stream: an async def generator gets CancelledError at its current await and its finally runs. A def generator's in-flight step finishes in its thread first.

solid answer

~50 s

FastAPI streams yield path operations, JSON Lines and SSE alike, through Starlette's `StreamingResponse`. Under Uvicorn it runs a listener for the ASGI `http.disconnect` message beside the body loop, and when the tab closes it cancels that loop. An `async def` generator then gets `CancelledError` at whatever it is awaiting, such as the next token from the model, so `finally` and `async with` cleanup run and the upstream call is abandoned. FastAPI adds a checkpoint after every item an async generator yields, so even a fast producer can be cancelled. A plain `def` generator runs each step in a worker thread, which cannot be interrupted: the current step finishes, the generator is never resumed, and its `finally` runs only when the abandoned generator is closed later. `await request.is_disconnected()` is a non-blocking check for code that wants to stop on its own.

code

python · 27 lines
python
import logging
from collections.abc import AsyncIterable

import anyio
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse, ServerSentEvent

app = FastAPI()
logger = logging.getLogger("chat")


async def generate_tokens(prompt: str) -> AsyncIterable[str]:
    for token in prompt.split():
        await anyio.sleep(0.5)  # stands in for awaiting the model
        yield token


@app.get("/chat/stream", response_class=EventSourceResponse)
async def chat_stream(prompt: str) -> AsyncIterable[ServerSentEvent]:
    sent = 0
    try:
        async for token in generate_tokens(prompt):
            yield ServerSentEvent(data=token, event="token")
            sent += 1
    finally:
        # Runs on normal completion and when a disconnect cancels the stream
        logger.info("chat stream closed after %d tokens", sent)

go deeper

for a junior

Remember that closing the tab cancels a FastAPI async streaming generator, and cleanup belongs in a finally block.

for a middle

Explain how Starlette's streaming response listens for the disconnect and cancels the body, and why cancellation lands at an await.

for a senior

Contrast async def and def generators on disconnect, spot code that swallows cancellation, and say when request.is_disconnected() earns its place.

for a principal

Make cost control explicit: async model clients for streamed endpoints, usage recorded in finally, and a rule against def generators that hold threads after users leave.

## How the disconnect is noticed A **client disconnect** is the client closing the connection before the response has finished: a closed tab, a navigation, a cancelled `fetch`. For a chat endpoint this matters because the server may still be paying for a model to generate tokens nobody will read. In **FastAPI 0.143**, every yielding path operation is served through Starlette's `StreamingResponse`: directly for JSON Lines and raw streams, and as the base class of `EventSourceResponse` for Server-Sent Events. What it does on a disconnect depends on the ASGI server: - **Uvicorn** reports ASGI HTTP spec version 2.3. For that, Starlette runs two tasks side by side: one sends the body, the other waits for the ASGI `http.disconnect` message. When the message arrives, it **cancels** the body task. - A server that reports spec 2.4 or later gets a different path: Starlette learns of the disconnect only when a write fails, and raises `ClientDisconnect`. A stream that goes quiet is then noticed late. The rest of this answer assumes Uvicorn, the server the `fastapi` CLI runs. ## async def generators: cancelled at the next await Cancellation in asyncio and anyio is delivered at an **await point**. When the body task is cancelled, the generator receives `CancelledError` where it is suspended, typically awaiting the model's next token. Then: 1. the `except` and `finally` blocks run, and any `async with` around the model client exits, closing the upstream stream; 2. the exception propagates, the response task ends, and the request's teardown proceeds. FastAPI adds an extra `anyio.sleep(0)` checkpoint after each item an async generator produces, so a generator that produces items faster than the network takes them can still be cancelled. Two things defeat this: - **Swallowing the cancellation.** `except Exception` does not catch `CancelledError`, but a bare `except:` or `except BaseException:` that does not re-raise keeps the generator running. - **Long stretches without an await.** CPU-bound work between yields cannot be interrupted until it next awaits. For SSE, FastAPI runs the generator in its own producer task, with a one-slot buffer and a keep-alive timer, inside a task group on the request's exit stack. The disconnect cancels the response, the exit stack closes the task group, and the producer, and with it the generator, is cancelled the same way. ## def generators: the thread finishes its step A plain `def` generator is advanced with each `next()` call running in a **worker thread** from anyio's pool. Python cannot cancel a running thread, so on a disconnect: 1. the step already in progress runs to completion, holding its thread, even if it is a blocking model call that takes seconds; 2. the generator is never resumed after that; 3. its `finally` block runs only when the abandoned generator object is closed or garbage-collected, not at the moment of the disconnect. For an endpoint whose purpose is to stop paying for a model the moment the user leaves, this is a strong reason to write the generator as `async def` with an async model client. | Generator style | On disconnect | When `finally` runs | |---|---|---| | `async def` | `CancelledError` at the current await | right away, during cancellation | | `def` | current step completes in its thread | later, when the generator is closed | ## request.is_disconnected() Declaring a `request: Request` parameter gives access to `await request.is_disconnected()`. It checks, without blocking, whether a disconnect message is waiting, and returns `True` once one has been seen. Under Uvicorn the cancellation above usually arrives first, so it is not required for an `async def` generator that awaits. It is useful: - before starting an expensive step that would not hit an await quickly; - on servers where Starlette only learns of a disconnect when a write fails; - in a loop that wants to stop deliberately and record why. It is a coroutine, so a `def` generator cannot call it. ## Checklist for a token stream - Write the generator as `async def` and await an async model client. - Put usage accounting and upstream cleanup in `finally` or an `async with`. - Never swallow `CancelledError`. - Treat a missing done event on the client as an interrupted answer. How framework-neutral servers detect aborted requests and enforce timeouts is covered with web framework concurrency concepts.

  • Why might a def generator endpoint keep calling the model for several seconds after the client has gone?
    Each `next()` of a `def` generator runs in a worker thread, and threads cannot be cancelled. The step in progress, such as a blocking model call, finishes before FastAPI stops asking for items, and the generator's `finally` waits until the abandoned generator is closed. An async generator with an async client stops at its current await instead.
  • When is calling await request.is_disconnected() inside a FastAPI streaming generator worth it?
    When something would otherwise run without reaching an await: before starting an expensive step, in a tight loop, or under a server where Starlette notices disconnects only on a failed write. Under Uvicorn, an async generator that awaits is already cancelled at that await, so the check is optional there.
  • What does a bare except: around the token loop do to disconnect handling?
    It catches `CancelledError` too, so the generator can keep running, or try to yield again, after the stream was cancelled, which wastes the very model call the cancellation was meant to stop. Catch `Exception` for model errors, or re-raise in an `except BaseException` block, and keep cleanup in `finally`.

  • A streaming generator keeps running to the end after the client disconnects.
  • FastAPI raises WebSocketDisconnect inside an HTTP streaming generator.
  • A def generator stops immediately, mid-call, when the tab closes.
  • except Exception will swallow the cancellation and break disconnect handling.
  • request.is_disconnected() blocks until the client goes away.

Assumes FastAPI 0.143 on Starlette 1.7 under Uvicorn; yield path operations exist since 0.134 and EventSourceResponse since 0.135.