Sub topic 13
Letting users stop generation
This chapter assumes you can read Python and JavaScript, know how a streamed response reaches the browser (SSE over a fetch body), and understand promises and asyncio. It covers how a "Stop" button works from the browser through your server to the model provider, and where cancellation commonly fails.
Why stopping matters
A streamed answer can run for tens of seconds. Users often see within the first sentence that the answer is wrong, too long, or aimed at the wrong question. A Stop button lets them cut it off. It also saves money, because most providers bill for output tokens as they are generated. If generation keeps running after the user gives up, you pay for text nobody reads.
Cancellation means stopping the work at every layer. Hiding the text in the UI is not enough. A request passes through three layers, and each one has to stop:
- The browser, which is reading the response body.
- Your backend, if it relays the stream.
- The provider, which is generating tokens.
Cancelling in the browser
The standard tool is AbortController. You create one controller per request and pass its signal to fetch. Calling controller.abort() closes the connection and makes pending reads reject with an AbortError.
let controller = null;
async function send(prompt, onText) {
controller = new AbortController();
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
signal: controller.signal,
});
if (!response.ok || !response.body) {
throw new Error(`Request failed with status ${response.status}`);
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value;
const events = buffer.split("\n\n");
buffer = events.pop();
for (const event of events) {
for (const line of event.split("\n")) {
if (line.startsWith("data: ")) onText(line.slice(6));
}
}
}
return "finished";
} catch (err) {
if (err.name === "AbortError") return "stopped";
throw err;
} finally {
controller = null;
}
}
function stop() {
if (controller) controller.abort();
}Three details matter here.
- An abort is not an error. The
catchblock separatesAbortErrorfrom real failures. Without that check, every Stop click shows an error banner. - Keep what has arrived. Text already rendered stays on screen. Mark the message as "stopped" in your state so the user can tell it is incomplete, and so you can send it back as conversation history if you choose.
- One controller per request. An aborted controller stays aborted. Reusing it makes the next
fetchfail immediately.
You can also abort for other reasons: the user navigates away, starts a new message, or a timeout fires. AbortSignal.timeout(ms) creates a signal that aborts on its own, and AbortSignal.any([a, b]) combines several signals in current browsers.
Cancelling on the server
When the browser aborts, the TCP connection closes. Your server only stops generating if it notices. Frameworks differ in how they surface this.
In FastAPI (Starlette), a streaming response that is cancelled raises asyncio.CancelledError inside your generator at its next await. You can also poll request.is_disconnected(). The generator below closes the upstream stream in a finally block, so cleanup runs whether the stream ends normally, fails, or is cancelled.
import asyncio
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
app = FastAPI()
client = AsyncOpenAI()
@app.post("/api/chat")
async def chat(request: Request):
body = await request.json()
async def events():
stream = await client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": body["prompt"]}],
stream=True,
)
try:
async for chunk in stream:
if await request.is_disconnected():
break
if chunk.choices and chunk.choices[0].delta.content:
text = chunk.choices[0].delta.content
yield f"data: {text}\n\n"
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
raise # let the framework finish cancelling
finally:
await stream.close() # closes the upstream HTTP connection
return StreamingResponse(
events(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)The line that matters is await stream.close(). Closing the upstream response closes the connection to the provider. Providers generally stop generating when the client disconnects, though the exact moment varies. If you drop the reference to the stream without closing it, the connection may stay open until garbage collection or a timeout, and generation can continue.
This example sends raw text in data: lines for brevity. As the earlier FastAPI example noted, tokens containing newlines need JSON encoding in a real relay.
What the provider bills when you cancel
Billing after a cancel depends on the provider and on timing. These are the general patterns, so check your provider's documentation for the exact rules.
| Situation | Typical result |
|---|---|
| Disconnect mid-stream | Output tokens generated up to the disconnect are billed. Generation stops soon after. |
| Disconnect, but server never closes upstream | Generation may continue and be billed for the full answer. |
| Stop before the first token | Input tokens are usually billed. Little or no output is billed. |
| Final usage chunk never arrives | You have no exact usage numbers for that request. |
The last row has a practical consequence. Usage totals normally arrive in the last chunk of a stream. A cancelled stream never delivers it. If you track cost per user, estimate tokens from the text you received, and treat the provider's invoice as the source of truth.
Cancelling when you cannot reach the provider connection
Some designs separate the request that starts generation from the connection that reads it, for example a background job that writes tokens to a queue. Closing the browser connection then does not stop the job. In that case, give each generation an ID and add an explicit cancel endpoint:
cancelled: set[str] = set()
@app.post("/api/chat/{generation_id}/cancel")
async def cancel(generation_id: str):
cancelled.add(generation_id)
return {"status": "cancelling"}The worker checks generation_id in cancelled between chunks and closes its upstream stream when it finds a match. The in-memory set works only for one process. With several workers, use shared storage such as Redis. Expire old IDs so the set does not grow forever.
Common failures
- Stop does nothing visible. The UI stops updating, but the server keeps generating. Check that the server closes the upstream stream, and look at provider usage after a test cancel.
- Proxy hides the disconnect. A buffering proxy may keep the upstream connection to your app open after the browser leaves, so your app never learns of the cancel. Disable buffering for the route, as covered in the proxy chapter.
- Race at the end. The user clicks Stop just as the stream finishes. Treat a stop after completion as a no-op, and make
stop()safe to call at any time. - Swallowed cancellation. A bare
except Exceptionorexcept BaseExceptionaround anawaitcan catchCancelledErrorand keep the task alive. Re-raise it. - Partial events. An abort can arrive in the middle of an event. Discard the incomplete
bufferinstead of parsing it. - Stale callbacks. After starting a new request, late chunks from the old one must not write into the new message. Compare a request ID before updating state.
Summary
Cancellation is a chain: browser AbortController, server disconnect detection, explicit upstream close. Break any link and the user sees a stop while you keep paying for tokens. Treat an abort as a normal outcome, keep the partial text, and clean up in finally.
Exercise
A user clicks Stop. The text stops appearing in the browser, but your provider dashboard shows the full answer was billed. Name two likely causes and one fix for each.
Show answer
First, the server did not close the upstream stream when the browser disconnected. Fix it by calling the stream's close method in a finally block and by handling the client disconnect. Second, a buffering proxy between the browser and your app hid the disconnect, so the app never saw it. Fix it by disabling buffering on the streaming route (for example with X-Accel-Buffering: no or the proxy's equivalent setting). A third acceptable cause is a background worker that is not tied to the browser connection. Fix it with an explicit cancel endpoint that the worker checks between chunks.
Exercise
Why must the catch block in the browser code check err.name === "AbortError", and what should the UI do with the text received before the abort?
Show answer
Calling controller.abort() makes pending reads reject with an AbortError. Without the check, a normal Stop click is treated as a failure and shows an error. The UI should keep the partial text and mark the message as stopped.