A user watches an answer stream in, decides it's going the wrong way, and clicks Regenerate before it finishes.
Your app starts a second generation. What happens to the first one?
There are three common answers, and they cost very different amounts:
1. You abort the first request, then start the second.
2. You start the second request and forget about the first.
3. You stop reading the first stream, but never cancel it.
The first is what most people intend. The second and third are what a lot of code actually does.
I measured all three against a real provider (DeepSeek, deepseek-flash, streaming Chat Completions), using the account balance as an external meter, the same method as in the previous experiment. The code is public: aiengineering-book/llm-cancellation-experiment.
The Result First
Each arm is 6 runs. Every completed answer is max_tokens=4000. In the regenerate arms, the first request is replaced 15 seconds after its first content chunk.
| Arm | What the app did with the first request | Billed per regenerate |
|---|---|---|
| A: baseline | (no regenerate) | 1 answer |
| B: abort, then regenerate |
controller.abort(), then start the second |
1 answer + the ~1,700 tokens already streamed |
| C: no abort | kept reading it to completion | 2 answers |
| D: stopped reading | stopped calling reader.read(), never cancelled |
2 answers |
At these settings, abort-then-regenerate cost about 1.4 answers. Forgetting the abort cost 2.
The 1.4 is a best case for this setup, not a price to quote. The prompt here was 31 tokens, so almost all of the cost was output. In a real chat, every request also sends the conversation history. The regenerate pays for that history again, usually at the cheaper prompt-cache rate, while the extra cost of the aborted answer stays the same ~1,700 output tokens. Measured against a full answer that includes the history, the ratio falls closer to 1. It also depends on how far the first answer got before the click. The ordering doesn't change: aborting is always cheaper than not aborting.
Arm D is the one worth looking at twice. The code looks like it moved on. The provider didn't notice.
How It Was Measured
The provider reports usage only at the end of a completed stream. An aborted stream never gets that frame, so the only way to see what an aborted request cost is from outside: the account balance.
DeepSeek exposes GET /user/balance, with two decimals of CNY and several minutes of lag. One request is far below that resolution, so each arm is a batch, and the script waits for the balance to settle between batches.
The setup:
- Model
deepseek-flash, streaming, thinking disabled. - Same long-essay prompt for every request,
max_tokens=4000. Every completed request ended withfinish_reason: "length"andusageof 4,031 tokens (31 prompt + 4,000 completion). - Regenerate fires 15 s after the first content chunk of the first request. The second request starts immediately, with no gap.
- Arm D holds the first stream unread for 120 s, then resumes reading to see what was waiting.
- A final batch repeats the baseline (A2) to catch drift. It caught some (see below).
- Only the experiment's key was active on the account during the run.
Arms C and D need no meter at all: both requests in each pair completed and reported usage. The meter matters only for arm B, where the first request was aborted.
Arm B: Abort, Then Regenerate
This is the case people worry about. The abort reaches the provider, but a new request starts the same instant. Does the provider finish the first one anyway, or bill it to max_tokens?
On this provider, no.
| CNY | |
|---|---|
| Measured balance drop for the B batch | 0.14 |
| Predicted if the first request stopped at the abort | 0.137 |
Predicted if the first request ran to max_tokens
|
0.192 |
The six aborted requests had streamed 51,733 characters, about 10,200 tokens at the 5.09 characters per token measured on the completed runs. Billing matched that, plus six full second answers.
So the cost of a regenerate done properly is the full new answer plus whatever the first had already produced. Regenerate late and you pay close to two answers even when everything is wired correctly. Regenerate early and it's close to one.
This is one provider. Other providers may finish an in-flight batch, or bill to a chunk boundary, after a disconnect. The previous article covers why that has to be measured per provider, and how to account for it when you can't: record a range, from tokens received up to max_tokens.
Arm C: Regenerate Without Abort
This is the plain bug. The Regenerate handler starts a new request and replaces the message on screen. Nobody aborts the old fetch, or the abort happens in the browser but your server never passes it upstream.
Both requests completed. Both reported 4,031 tokens. Each regenerate cost exactly two answers.
The user sees one answer. You pay for two. If they click Regenerate three times, you pay for four.
Arm D: You Stopped Reading. The Provider Didn't Stop Writing.
This one looks correct in code review. The handler returns early or ignores the old stream. Nothing reads it any more. It's easy to assume the request is effectively gone.
It isn't. Stopping reading is not a cancel. The connection stays open, and the provider keeps generating.
When the probe resumed reading after 120 seconds, the rest of each answer was already there:
| Run | Read before the pause | Waiting after the pause | Time to drain it |
|---|---|---|---|
| 1 | 5,439 chars | 14,325 chars (72%) | 111 ms |
| 2 | 7,901 | 11,786 (60%) | 95 ms |
| 3 | 8,161 | 12,931 (61%) | 119 ms |
| 4 | 8,843 | 13,149 (60%) | 103 ms |
| 5 | 8,506 | 10,953 (56%) | 126 ms |
| 6 | 11,455 | 10,307 (47%) | 99 ms |
Half to three quarters of each answer was generated while nobody was reading, buffered somewhere between the provider and the process, and handed over in about 100 ms. Every one of them completed with full usage. The batch cost matched two full answers per pair (0.39 CNY measured, 0.385 predicted).
The buffer is the socket buffers on both ends plus whatever proxies sit in between (this run went through a local proxy). For a 4,000-token answer, the whole remainder fit. A much longer answer might eventually fill the buffers, and TCP backpressure might then stall generation on the provider side. That wasn't tested here. But at ordinary answer lengths, "stopped reading" means "paid in full".
In TypeScript the difference is often one line:
// Cancels: breaking out of for-await calls cancel() on the stream.
for await (const chunk of response.body!) {
if (superseded) break;
// ...
}
// Does not cancel: the reader is simply abandoned.
const reader = response.body!.getReader();
while (true) {
if (superseded) return; // connection stays open
const { done, value } = await reader.read();
if (done) break;
// ...
}
If you use a manual reader, call reader.cancel() on the way out. Better, pass an AbortSignal to the fetch and abort it. That covers every exit path, including errors.
The Drift Check Caught a Price Change
The baseline ran twice, at the start (A) and at the end (A2). Same prompt, same model, same token counts.
| Batch | Time (UTC) | Cost |
|---|---|---|
| A | 00:33 | 0.10 CNY |
| A2 | 01:32 | 0.19 CNY |
The cost nearly doubled in an hour. The cause is in DeepSeek's pricing page: on weekdays, 01:00–04:00 and 06:00–10:00 UTC are peak hours, and peak price is twice off-peak. The run started off-peak and crossed into peak partway through arm C.
With the published prices for each window, every batch lands within 0.01 CNY (the meter's resolution) of its prediction. Without the second baseline, arm D's cost would have looked like twice what C's per-pair cost suggests, and it would have been easy to invent a reason.
Two practical points come out of this:
- If you compare costs across time, the time of day is part of the measurement. A benchmark that runs A in the morning and B in the afternoon may be measuring the price list.
- In a cost dashboard, a step change at the same time every weekday is probably pricing, not your traffic.
The App-Layer Fix: One Active Generation per Conversation
Arms C and D are both the same mistake: two generations alive for one conversation. The fix sits on the server, because the server is the one holding the upstream request:
- Keep one
AbortControllerper conversation. A new request for the same conversation aborts the previous one. - Pass the client's disconnect through to that controller, so a tab closed mid-stream also cancels upstream.
- Save an answer only if its request is still the current one when it finishes. Otherwise a slow, superseded answer can be saved next to (or over) the one the user is looking at.
The core of it:
const active = new Map<string, AbortController>();
async function handleChat(conversationId: string, res: ServerResponse) {
const controller = new AbortController();
// The newest request for a conversation wins.
active.get(conversationId)?.abort('superseded');
active.set(conversationId, controller);
// A client that leaves cancels the upstream call too.
res.on('close', () => {
if (!res.writableFinished) controller.abort('client-disconnect');
});
try {
const upstream = await fetch(PROVIDER_URL, { signal: controller.signal });
// ... stream to the client ...
// Save only if no newer request replaced this one.
if (active.get(conversationId) === controller) await saveAnswer(conversationId);
} catch {
// aborted: nothing to save
} finally {
if (active.get(conversationId) === controller) active.delete(conversationId);
}
}
The repo has a runnable version against a local mock provider that bills one unit per generated token (pnpm demo:regenerate, no API key needed). The scripted user sends a message, clicks Regenerate after a second, then double-clicks Regenerate. That's four requests, and the fourth is the one on screen. A full answer is 40 tokens:
| Server | Tokens billed | Answers saved | Max concurrent generations |
|---|---|---|---|
| Naive | 160 | 4 | 4 |
| One active generation per conversation | 68 | 1 | 2 |
Max concurrency is 2 even with the guard. The abort reaches the provider asynchronously, so the old generation and the new one overlap for a moment. That's expected. What matters is that the overlap is brief and only one answer is saved.
A Map in memory works for a single server process. With several instances behind a load balancer, two requests for the same conversation can land on different machines. Then the "current request" marker has to live somewhere shared: a row in your database or a key in Redis, checked before saving and polled or subscribed to for the abort.
What This Does and Does Not Establish
Established, for deepseek-flash on one day:
- An abort followed immediately by a new request was billed for the tokens streamed so far, not to
max_tokens. - A request that is neither read nor cancelled keeps generating and is billed in full, at least for 4,000-token answers.
- A regenerate without cancellation costs exactly two answers (from
usage, not the meter).
Not established:
- Other providers, other models, thinking mode, or non-streaming calls.
- Whether very long unread streams eventually stall through backpressure.
- An LLM gateway or reverse proxy between the app and the provider. This run went direct, apart from a local network proxy. A gateway that keeps reading the upstream stream after the client disconnects would turn arm B into arm C, so test the abort through whatever sits in your path.
- Exact per-request billing for aborted requests. The balance has two decimals of CNY, so overshoot of a few hundred tokens per abort would not show.
- Arm C's prediction depends on how many pairs ran before the 01:00 UTC price switch (about two). Its cost is not in question, since both requests reported
usage.
A Checklist for Your Regenerate Button
- The server aborts the previous upstream request for the conversation before starting a new one.
- Client disconnects reach the upstream
fetchthrough anAbortSignal. - Every early exit from a stream reader cancels it (
breakout offor await,reader.cancel(), or an aborted signal). - An answer is saved only if its request is still current.
- Each request ID is logged, along with which request superseded it. When costs look wrong, that's how you find pairs that both completed.
- Cost comparisons across time account for time-of-day pricing.
Further Reading
This is the fourth article in a series:
- Your LLM App Is Wasting Money: What Happens When Users Close the Tab?: getting the disconnect from the browser to the upstream request.
- You Aborted the LLM Request. Did You Actually Stop the AI?: whether the provider stops and bills accordingly.
- Your AI Agent Doesn't Belong Inside an HTTP Request: work that should outlive the connection, and cancelling it explicitly.
The chat interface this builds on, including the client-side AbortController and a Regenerate exercise, is in Chapter 8 of 《AI Engineering with TypeScript — A Comprehensive Guide to Building AI Agents》 at Leanpub. Cancellation with AbortController and AbortSignal.any is in Chapter 3. The book's companion code is at github.com/aiengineering-book/code.
References
- DeepSeek API — Models & Pricing (peak and off-peak hours)
- DeepSeek API — Create Chat Completion
- Streams Standard — ReadableStream async iteration
-
aiengineering-book/llm-cancellation-experiment:
src/regenerate-probe.ts(the measurement) andsrc/regenerate-guard.ts(the demo)
Top comments (5)
Arm D is the one that quietly bankrupts people, and it's invisible in every dashboard because the client-side code genuinely looks like it moved on. Using the account balance as an external meter is the right call precisely because the usage frame never arrives for an abandoned stream — you can't measure what the provider never tells you.
Two things we found that compound this: first, HTTP/2 connection reuse can keep an "abandoned" stream alive on the wire even after you think the socket's gone, so the only reliable cancel is an explicit abort propagated to the request, not just dropping the reader — which matches your Arm B/D split exactly. Second, behind a gateway or proxy the client's abort doesn't always reach the upstream provider; the gateway happily finishes reading the stream you canceled. Worth checking whether anything between your app and the provider is holding the connection open. Did you test the abort through a proxy layer, or only direct to DeepSeek?
Direct to DeepSeek, with only a local network proxy in the path, no LLM gateway. That proxy did pass the abort through: arm B was billed for the streamed tokens only. A gateway is a fair worry, though. If it keeps reading the upstream stream after the client goes away, arm B quietly becomes arm C, and nothing on the client side would show it. I've added that to the article's limits. On HTTP/2: Node's fetch speaks HTTP/1.1 by default, so these runs didn't exercise it. In HTTP/2 an abort resets just that stream, while dropping the reader without cancelling leaves it open, which is arm D again on a shared connection.
Clean setup, but the 31-token prompt is doing a lot of work in that 1.4x. With a real chat history the second request is a prefix-cache hit on everything except the new turn, so its marginal cost sits far below one full answer and the regenerate ratio drops well under 1.4. The ordering - abort cheaper than no abort - holds either way; the multiplier is a best case for the bill, not a typical one, and it's worth saying that next to the table before people quote 1.4 as the price of a regenerate.
One addition to arm D: in Node, a response body you stop reading but never cancel keeps its undici connection checked out until the socket times out, so with a few concurrent users the price stops being tokens and becomes latency for unrelated requests on the same agent. reader.cancel() before walking away is the cheap fix. Did the A2 drift land outside the balance's 0.01 resolution, or did you have to widen the batches to see it at all?
Good point, and I've added it next to the table. With a 31-token prompt nearly all the cost is output. With real history the regenerate re-sends the context, mostly at the cache-hit rate, while the extra cost stays the ~1,700 streamed tokens, so the ratio moves toward 1. It also depends on how far the first answer got.
On undici: agreed that reader.cancel() (or aborting the signal) is the fix, and the article recommends it for any manual reader. I didn't measure the pool effect. With the default dispatcher I'd expect a leaked socket rather than queueing, unless you cap connections per origin.
On A2: it wasn't subtle. Each batch was 6 requests of ~4,000 output tokens, about 0.1 CNY per batch, so A at 0.10 and A2 at 0.19 were far outside the 0.01 resolution. The cause turned out to be DeepSeek's peak pricing window.
We ran into that exact gateway Arm B to Arm C leak while debugging aborted Bedrock Invoke streams in LiteLLM under aiohttp and uvloop. Even when a client disconnected cleanly 7 seconds after the first content_block_delta, CloudWatch still billed 1,462 to 1,569 output tokens on Claude Sonnet 4.5, and 8 other aiohttp routes kept reading upstream for up to 30 seconds.
Two bugs hid behind that disconnect. First, the async streaming iterator was not closing its byte iterator and httpx response on early exit, which I missed completely on my first pass because local mocks looked fine. Second, even after wiring aclose() down every layer, aiohttp tried a graceful TLS close and drained buffered chunks instead of dropping the socket. Calling transport.abort() on early close dropped the same 7-second abort to 277 to 314 CloudWatch tokens and 0 lingering sockets.
On the TS client side, retry wrappers create a quieter version when catch blocks forget to exit on signal.aborted and retry a user cancel as a network drop. Have you tried running regenerate-probe.ts through a Python gateway yet to see if Arm B holds near 1.4x?