Mental model
When an AI user hits "Stop Generating", switches chat threads, or rapidly resubmits an edited prompt mid-answer, simply ignoring arriving tokens inside React leaves your FastAPI workers, upstream OpenAI/vLLM GPUs, and downstream RAG tools burning full compute until completion cleanly invisibly! End-to-end mid-stream cancellation links browser AbortController / AbortSignal cleanup directly across TCP/HTTP2 socket teardown into backend ASGI disconnect propagation (request.is_disconnected() / racing http.disconnect) and deterministic finally: resource release, preventing leaked upstream connections, orphaned GPU tokens, and stale turn race conditions in UI state.
Learning outcomes
- Scope fresh
AbortControllerinstances strictly per user submission cleanly (requestIdguard against staleAbortErrorraces on rapid re-prompts). - Handle browser teardown reliably across component unmounts and
useEffectcleanups without crashing React state updates. - Propagate socket drops inside FastAPI generators cleanly (
request.is_disconnected()plus racingreceive()against slow blockedawait httpx.aiter()calls!) rather than letting awaiting tasks hang cleanly until next token! - Release upstream LLM streams, database cursors, and concurrency semaphores inside
finally:blocks immune to Pythonasyncio.CancelledError(BaseException).
Theory
Two real-world implementation flaws make naive cancel handlers look broken in production:
- Reusing One Global
AbortControllerAcross Messages (or Letting Aborted Turn A Mutate Turn B): AnAbortSignalremains permanently aborted once.abort()fires! Always mint a freshAbortControllerper prompt turn alongside a monotonically uniquerequestId, checkingif (activeTurnIdRef.current !== turnId) return;inside error/finally blocks so delayedAbortErrorcleanups from canceled Turn 1 never wipe Turn 2's loading spinner! - Checking
request.is_disconnected()Strictly Between Slow Upstream Awaits: Writingif await request.is_disconnected(): breakinside afor chunk in provider.stream()loop does nothing while the coroutine sits frozen insideawait upstream_chunkwaiting10 secondson a slow reasoning model! Truly responsive server cancellation spawns a tiny background watcher monitoring ASGI socket disconnects (http.disconnect) that immediately triggers.cancel()on the provider task—and closes upstreamhttpx.AsyncClientstreams insidefinally:(BaseException-safe, because modern Python'sasyncio.CancelledErrorbypasses plainexcept Exception:!).
| Cancellation Control Layer | Failure Without Safeguard | Production Safe Pattern |
|---|---|---|
Browser Client (React + fetch) | Orphaned sockets on route switch; shared aborted signal bricks next turn | Dedicated per-turn AbortController, unmount useEffect .abort(), check error.name === "AbortError" + turn ID |
Reverse Proxy (Nginx / Traefik) | Proxy holds upstream connection open despite client disconnect (proxy_ignore_client_abort on) | Ensure client-abort propagation stays enabled (proxy_ignore_client_abort off default!) on streaming paths |
| FastAPI / ASGI Server | Hung generator keeps draining vLLM tokens during slow 15s pause between chunks | Task-race receive() http.disconnect alongside upstream aiter_lines(), abort task immediately on close |
Resource & Token Metering (finally:) | Semaphores / pooled connections leak cleanly on CancelledError (BaseException); zero usage logged | Wrap stream teardown & partial token metering deterministically inside finally: before exit |
typescriptimport { useEffect, useRef, useState } from "react";export function useCancellableChatStream() {const [streaming, setStreaming] = useState(false);const controllerRef = useRef<AbortController | null>(null);const activeTurnRef = useRef<number>(0);const stop = () => {controllerRef.current?.abort("user_cancelled");controllerRef.current = null;};useEffect(() => () => stop(), []); // Prevent background socket leaks on navigation unmountconst start = async (prompt: string, onChunk: (text: string) => void) => {stop(); // Deterministically abort any previous active turn before starting next turnconst turnId = ++activeTurnRef.current;const controller = new AbortController();controllerRef.current = controller;setStreaming(true);try {const res = await fetch("/api/v1/chat/stream", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ prompt }),signal: controller.signal,});if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);const reader = res.body.getReader();const decoder = new TextDecoder("utf-8");while (true) {const { value, done } = await reader.read();if (done || activeTurnRef.current !== turnId) break;onChunk(decoder.decode(value, { stream: true }));}} catch (err: unknown) {if ((err as { name?: string })?.name === "AbortError") return; // Expected cancellation paththrow err;} finally {if (activeTurnRef.current === turnId) setStreaming(false);}};return { streaming, start, stop };}
pythonimport asynciofrom collections.abc import AsyncIteratorfrom fastapi import FastAPI, Requestfrom fastapi.responses import StreamingResponseapp = FastAPI()async def upstream_disconnect_guarded_stream(request: Request) -> AsyncIterator[str]:upstream_closed = Falsetry:for step in range(100):if await request.is_disconnected():returnawait asyncio.sleep(0.05)yield f"data: {{\"tok\": {step}}}\n\n"except asyncio.CancelledError:upstream_closed = Trueraisefinally:# Runs cleanly on normal completion, GeneratorExit, AND asyncio.CancelledError:# Close upstream httpx response, release tenant concurrency semaphore, persist partial metered tokens!_ = upstream_closed
Notice one vital server nuance when using StreamingResponse alongside FastAPI yield database dependencies: verify database writes (partial metered usage) either use a standalone fresh short session inside finally: or complete cleanly without touching an already-torn-down request session!
Alternatives and trade-offs
- Native HTTP
fetch()AbortSignal+ ASGIhttp.disconnectTask Cancellation: Zero custom control endpoints required, cleanly passes standard HTTP/2RST_STREAMcancellations straight down reverse proxies into Python tasks; slightly trickier when you explicitly want an async workflow (like deep research) to continue running cleanly in the background after closing a laptop (detachable job queuebeats pure HTTP disconnect!). - Explicit Cooperative Cancel Endpoint (
POST /runs/{run_id}/cancel) + Idempotent Worker: Essential whenever mobile disconnects shouldn't accidentally kill expensive multi-minute agent runs (keep generating silently until explicit Stop button or Redis cancel flag fires!), trading instant socket-level teardown for decoupled job lifecycle control. - Unchecked Server Timeout Only: Lets aborted chat prompts burn remaining output budgets uselessly until timeout—acceptable solely for sub-second non-billable responses.
Failure modes and misconceptions
- Ignoring
asyncio.CancelledErrorBypassingexcept Exception:in Python 3.8+: Catching onlyexcept Exception:around async provider HTTP loops skipsCancelledError(BaseException), leaking locked DB pools, tenant semaphores, or streaming connections whenever sockets abort mid-turn! Always release leases cleanly insidefinally:. - Stale
AbortErrorHandler Clearing Newly Started Prompt B's Loading UI: Rapid Stop -> Re-Send triggers latefinallycallbacks from Turn A that accidentally flip Turn B's spinner tofalseunless guarded cleanly by monotonicactiveTurnRef. - Killing Long-Running Research Workflows Unintentionally on Flaky Cellular Handoffs: If every Wi-Fi-to-5G disconnect aborts backend orchestration completely cleanly, mobile users lose 90 seconds of deep research! Distinguish ephemeral single-turn completions (abort cleanly on socket close) from durable agent runs (cancel explicitly via
POST /cancel, resume cleanly viaafter_seq). - Assuming
proxy_ignore_client_abort onExists Innocently on Edge Proxies: Turning on Nginxproxy_ignore_client_abortsilently swallows browserAbortController.abort()signals at the edge proxy—never closing FastAPI's socket until total completion!
Decision scenario
Your interactive coding copilot streams multi-thousand-token diffs from upstream vLLM GPUs through Nginx + FastAPI to React users who frequently abort half-started answers and rapidly submit refined follow-ups. Allocate a fresh per-turn AbortController + activeTurnRef ID in React (stop() previous turn cleanly on resubmit and unmount), verify Nginx leaves proxy_ignore_client_abort off, wire FastAPI to watch ASGI disconnects cleanly alongside upstream httpx streams, release concurrency semaphores and persist accurate partial token counts strictly inside finally: blocks, and keep explicit POST /runs/{id}/cancel routes strictly for detachable multi-minute background jobs.
Trade-offs
End-to-end HTTP AbortController + ASGI cancellation eliminates orphaned GPU compute and leaked semaphore capacity deterministically across ephemeral streaming chat sessions, while requiring careful stale-turn React UI guarding, BaseException-safe finally: teardown, and intentional separation from detachable mobile-resilient background runs.