How do you cancel an in-flight streaming LLM request using AbortController when a user navigates away? | A1Lab@HamzaM to AI & LLMEnglish • 5 days ago

How do you cancel an in-flight streaming LLM request using AbortController when a user navigates away?

message-square
0

How Token Streaming Works Between FastAPI and React

To stream LLM tokens from a Python FastAPI backend to a React frontend, FastAPI sends chunks over an open HTTP response using StreamingResponse, and React reads those bytes progressively with fetch() and response.body.getReader() (which returns a ReadableStreamDefaultReader over the ReadableStream).

  • No polling needed: Tokens appear in the UI as soon as the model generates them instead of waiting for the full reply.
  • Works with POST requests: Unlike EventSource, fetch() + ReadableStream lets you send a JSON body (such as chat history and prompt settings) and custom headers easily.
  • Chunk boundaries vary: A single read from the stream can return part of a word, multiple tokens, or a split multi-byte character, so decoding with { stream: true } is important.

Step-by-Step Flow

  1. FastAPI yields text chunks: An async generator yields string chunks from the LLM stream and returns a StreamingResponse with media_type="text/plain; charset=utf-8".
  2. React posts the prompt: A POST request sends the user message and passes an AbortController signal so the user can cancel mid-stream.
  3. React reads the ReadableStream: Loop over reader.read(), decode bytes using TextDecoder with { stream: true }, and append new text to React state.
  4. Clean up on finish or cancel: Handle done === true, AbortError, and HTTP errors cleanly.

FastAPI Backend Example (Python)

from typing import AsyncIterator
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel

app = FastAPI()
client = AsyncOpenAI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class ChatRequest(BaseModel):
    prompt: str


async def token_generator(prompt: str) -> AsyncIterator[str]:
    stream = await client.responses.create(
        model="gpt-4o-mini",
        input=prompt,
        stream=True,
    )
    async for event in stream:
        if event.type == "response.output_text.delta":
            yield event.delta


@app.post("/api/chat/stream")
async def stream_chat(req: ChatRequest) -> StreamingResponse:
    return StreamingResponse(
        token_generator(req.prompt),
        media_type="text/plain; charset=utf-8",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )

React Frontend Example (ReadableStream)

import { useRef, useState } from "react";

export function StreamingChat() {
  const [prompt, setPrompt] = useState("");
  const [output, setOutput] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const [error, setError] = useState("");
  const abortRef = useRef(null);

  async function handleSubmit(e) {
    e.preventDefault();
    if (!prompt.trim() || isStreaming) return;

    setOutput("");
    setError("");
    setIsStreaming(true);

    const controller = new AbortController();
    abortRef.current = controller;

    try {
      const response = await fetch("http://localhost:8000/api/chat/stream", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt }),
        signal: controller.signal,
      });

      if (!response.ok || !response.body) {
        throw new Error(`HTTP \${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        const chunkText = decoder.decode(value, { stream: true });
        setOutput((prev) => prev + chunkText);
      }

      // Flush any remaining buffered multi-byte character
      const tail = decoder.decode();
      if (tail) {
        setOutput((prev) => prev + tail);
      }
    } catch (err) {
      if (err.name !== "AbortError") {
        setError(err.message || "Streaming failed");
      }
    } finally {
      setIsStreaming(false);
      abortRef.current = null;
    }
  }

  function handleStop() {
    abortRef.current?.abort();
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="Ask something..."
        />
        <button type="submit" disabled={isStreaming}>
          Send
        </button>
        {isStreaming && (
          <button type="button" onClick={handleStop}>
            Stop
          </button>
        )}
      </form>

      {error && <p>{error}</p>}
      <pre>{output}</pre>
    </div>
  );
}

Helpful Tips for Production

  • Disable proxy buffering: Adding X-Accel-Buffering: no and Cache-Control: no-cache helps prevent reverse proxies like Nginx from holding chunks before flushing.
  • Batch UI updates if needed: Very fast token streams can trigger frequent re-renders; accumulating chunks in a ref or requestAnimationFrame keeps large responses smooth.
  • Use structured SSE events for metadata: Plain text is simple for raw tokens, while SSE-formatted lines (data: {...}\n\n) work well if you also need to stream citations, tool status, or error events.