FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Mid-Stream Client-Side Cancellation

Aborting active generation streams in React using AbortController and sending termination signals to FastAPI backends.

Freshness: current•14 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

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.

Allocate Fresh Per-Turn AbortController
Bind signal to fetch() + Cleanup on Unmount
User Stops / Edits -> controller.abort()
FastAPI Catches Disconnect / CancelledError
Close Upstream Provider httpx Stream in finally
Conceptual teaching model synthesized from:mdn-abort-signal,fastapi-streaming

Learning outcomes

  • Scope fresh AbortController instances strictly per user submission cleanly (requestId guard against stale AbortError races on rapid re-prompts).
  • Handle browser teardown reliably across component unmounts and useEffect cleanups without crashing React state updates.
  • Propagate socket drops inside FastAPI generators cleanly (request.is_disconnected() plus racing receive() against slow blocked await 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 Python asyncio.CancelledError (BaseException).

Theory

Two real-world implementation flaws make naive cancel handlers look broken in production:

  1. Reusing One Global AbortController Across Messages (or Letting Aborted Turn A Mutate Turn B): An AbortSignal remains permanently aborted once .abort() fires! Always mint a fresh AbortController per prompt turn alongside a monotonically unique requestId, checking if (activeTurnIdRef.current !== turnId) return; inside error/finally blocks so delayed AbortError cleanups from canceled Turn 1 never wipe Turn 2's loading spinner!
  2. Checking request.is_disconnected() Strictly Between Slow Upstream Awaits: Writing if await request.is_disconnected(): break inside a for chunk in provider.stream() loop does nothing while the coroutine sits frozen inside await upstream_chunk waiting 10 seconds on 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 upstream httpx.AsyncClient streams inside finally: (BaseException-safe, because modern Python's asyncio.CancelledError bypasses plain except Exception:!).
Cancellation Control LayerFailure Without SafeguardProduction Safe Pattern
Browser Client (React + fetch)Orphaned sockets on route switch; shared aborted signal bricks next turnDedicated 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 ServerHung generator keeps draining vLLM tokens during slow 15s pause between chunksTask-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 loggedWrap stream teardown & partial token metering deterministically inside finally: before exit
typescript
import { 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 unmount
​
const start = async (prompt: string, onChunk: (text: string) => void) => {
stop(); // Deterministically abort any previous active turn before starting next turn
const 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 path
throw err;
} finally {
if (activeTurnRef.current === turnId) setStreaming(false);
}
};
​
return { streaming, start, stop };
}
python
import asyncio
from collections.abc import AsyncIterator
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
​
app = FastAPI()
​
async def upstream_disconnect_guarded_stream(request: Request) -> AsyncIterator[str]:
upstream_closed = False
try:
for step in range(100):
if await request.is_disconnected():
return
await asyncio.sleep(0.05)
yield f"data: {{\"tok\": {step}}}\n\n"
except asyncio.CancelledError:
upstream_closed = True
raise
finally:
# 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 + ASGI http.disconnect Task Cancellation: Zero custom control endpoints required, cleanly passes standard HTTP/2 RST_STREAM cancellations 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 queue beats 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

  1. Ignoring asyncio.CancelledError Bypassing except Exception: in Python 3.8+: Catching only except Exception: around async provider HTTP loops skips CancelledError (BaseException), leaking locked DB pools, tenant semaphores, or streaming connections whenever sockets abort mid-turn! Always release leases cleanly inside finally:.
  2. Stale AbortError Handler Clearing Newly Started Prompt B's Loading UI: Rapid Stop -> Re-Send triggers late finally callbacks from Turn A that accidentally flip Turn B's spinner to false unless guarded cleanly by monotonic activeTurnRef.
  3. 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 via after_seq).
  4. Assuming proxy_ignore_client_abort on Exists Innocently on Edge Proxies: Turning on Nginx proxy_ignore_client_abort silently swallows browser AbortController.abort() signals at the edge proxy—never closing FastAPI's socket until total completion!
Reflect before revealing the guide

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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next