Topic 3 of 4 · 5 min read
Cancelling a stream cleanly mid-response
Goal: Propagate a cancel from the client to the upstream provider request so the stream closes and no further tokens are generated.
To stop a stream you must cancel at every hop: the browser aborts its request, your server notices the closed connection, and your server aborts the upstream call to the provider. If any hop is missed, the model keeps generating and you keep paying for tokens nobody reads.
Check yourself · 1 of 3
A user clicks Stop. Which chain stops the model generating?
Why it matters
Users click Stop, close the tab or send a new message while the old answer is still streaming. A long answer can run for tens of seconds. Closing only the browser side does not reach the provider. Your server happily reads the rest of the stream into a socket that no one is listening to.
How to do it
- Browser: create an
AbortController, pass itssignaltofetch, and callabort()on Stop. The request body stream ends and the connection closes. - Your server: listen for the client's disconnect. In Node this is the
closeevent on the request or response. In many frameworks it is anAbortSignalon the request object. - Upstream: create your own
AbortControllerper request, pass its signal to the provider call or SDK, and callabort()from the disconnect handler. The SDKs accept a signal, or offer a stream object with an abort method. - Clean up: stop the loop that reads events, release the response, and clear any timers. Do not leave the iterator half read.
- Keep what arrived. Save the partial text if the user may want it, and mark the message as stopped, not finished. Tokens already generated are normally billed. Check your provider's rules for cancelled requests.
Before and after
Weak:
app.post("/chat", async (req, res) => {
const stream = await client.messages.create({ ...params, stream: true });
for await (const ev of stream) res.write(format(ev));
res.end();
});
If the user leaves, the loop runs to the end of the model's answer.
Better:
app.post("/chat", async (req, res) => {
const ac = new AbortController();
res.on("close", () => ac.abort());
const stream = await client.messages.create(
{ ...params, stream: true },
{ signal: ac.signal },
);
try {
for await (const ev of stream) res.write(format(ev));
} catch (err) {
if (!ac.signal.aborted) throw err;
} finally {
res.end();
}
});
What goes wrong
- Aborting only in the browser. The upstream request continues.
- Treating the abort as an error. An aborted read throws. Catching it as a failure floods your error log and may retry a request the user cancelled.
- Listening to the wrong event. Use the event for a closed connection before the response finished, not for a finished one.
- No cancel on retry or resend. Starting a new answer while the old one streams leaves two generations running.
Examples
Stop button in the browser
const ac = new AbortController();
stopButton.onclick = () => ac.abort();
const res = await fetch("/chat", { method: "POST", body, signal: ac.signal });
The fetch rejects with an AbortError. The UI should keep the text received so far and show it as stopped.
Two requests at once
A user sends a new message while the old answer streams. The client aborts the first request before sending the second. Without the abort, two generations run for one user and the first one's tokens still count on the bill.
Key points
- A cancel must travel through every hop: browser, your server, then the provider request.
- In the browser, pass an AbortController signal to fetch and call abort on Stop.
- On your server, tie the disconnect event of the response to an AbortController for the upstream call.
- An aborted read throws, so catch it and do not log or retry it as a failure.
- Save the partial text and mark it stopped, not finished, since generated tokens are normally billed.
Common mistakes
- Aborting only in the browser and assuming the provider call stops by itself.
- Logging the abort as an error and triggering an automatic retry of a cancelled request.
- Listening for the end of the request instead of the early close of the response.
- Discarding the partial answer that the user already saw.
Check yourself · 2 of 3
Which browser feature cancels a fetch request that is streaming a response?
Check yourself · 3 of 3
The handler below streams a reply. A user closes the tab at second 3 of a 40 second answer. What happens, and what is the fix?
Practice items, not counted towards your mastery.
Start here
- Streaming messages (Claude) (opens in a new tab)DocsFree
The full event sequence, delta types, partial tool JSON and mid-stream error behaviour of a Claude stream.
- Streaming API responses (OpenAI) (opens in a new tab)DocsFree
How another vendor names and orders its stream events, useful for comparing event shapes.
- Using server-sent events (MDN) (opens in a new tab)DocsFree
The wire format: data lines, blank-line separators, event names and the text/event-stream type.
More for this topic
- AbortController (MDN) (opens in a new tab)DocsFree
How to create an abort signal and pass it to fetch so a request and its body stream can be cancelled.