Skip to content
mentoor

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?

Choose one answer

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

  1. Browser: create an AbortController, pass its signal to fetch, and call abort() on Stop. The request body stream ends and the connection closes.
  2. Your server: listen for the client's disconnect. In Node this is the close event on the request or response. In many frameworks it is an AbortSignal on the request object.
  3. Upstream: create your own AbortController per request, pass its signal to the provider call or SDK, and call abort() from the disconnect handler. The SDKs accept a signal, or offer a stream object with an abort method.
  4. Clean up: stop the loop that reads events, release the response, and clear any timers. Do not leave the iterator half read.
  5. 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?

Choose one answer

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?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic