A user reports that answers appear all at once after thirty seconds, "like the old version". Another reports that a long answer stopped halfway and the retry produced a second, slightly different answer that was also billed. Neither user is wrong, and neither report is about model quality. The first is a proxy holding the response in a buffer. The second is a stream that died at token nine hundred, after the provider had already generated and charged for it, in a system that had no idea the two events were related.
Streaming looks like a latency feature and is mostly a transport decision. It moves the units you cannot control — connection lifetime, buffer size, decode boundaries, client attention — into the critical path of a request that was previously one atomic round trip. A non-streaming call either succeeds or fails; a streamed call can succeed for eleven seconds and then fail, and everything written during those eleven seconds exists in three places at once: the database, the client's screen, and the provider's bill.
Most of the bugs below share one shape. The response was designed as a sequence of characters pushed through a pipe, and the system around it was designed as if the pipe were a value. Buffers, proxies, readers, retries and caches all made assumptions that hold for a value and not for a sequence. Fixing them is not about adding streaming support. It is about deciding what the record is, and making the stream a view onto it.
What streaming actually buys, and what it costs
The benefit is time to first token. A user who sees the first sentence in eight hundred milliseconds starts reading, and a twenty-second answer feels like a four-second one because reading overlaps with generation. On a chat interface that is worth a great deal, and on an interface nobody is watching — a nightly extraction job, a batch classification — it is worth nothing at all.
The cost is a much larger failure surface, and it scales with how long the answer takes. A nine-hundred-token answer at forty tokens per second is a twenty-two second connection held open through a load balancer, an ingress proxy, a CDN ideally not in the path, and a network that a phone can lose by changing cell towers. Each of those hops has an idle timeout, a buffer size and a habit of reassembling bodies before forwarding them. Against a single non-streaming request of the same duration the failure probability is similar; the difference is that the streamed request fails visibly and partially, and each partial failure costs tokens nobody reads.
So the first design question is not "how do we stream this" but "does this endpoint need to stream at all". A summariser inside a pipeline does not. A user-facing answer does, and then the engineering problem becomes: what do we guarantee when the pipe breaks, and what does the user see?
Measure the last token, not the first
Almost every team measures time to first token, because it is the number that justifies the feature. It is also the number least likely to reveal a broken stream, because the kernel flushes headers immediately whether or not a single event follows. A response that buffers the entire answer and then writes it in one flush has an excellent time to first byte and a terrible time to first token, and dashboards that measure at the wrong layer will report the first as the second.
Three measurements cover the same ground honestly:
- Time to first token — from request start to the first content delta reaching the client, measured in the browser or at the edge, not at the application.
- Inter-token p99 — the longest gap between two consecutive deltas, per stream. This is what users experience as a stall, and it is where a buffering proxy shows up: one gap of twenty seconds followed by the whole answer.
- Completion ratio — streams that reached their terminal event, divided by streams that started. A ratio below one means disconnects are routine, and the missing streams are the ones that cost money.
The complement of the completion ratio is the number that pays for this work: tokens billed divided by tokens delivered. When it is one, every token you paid for reached a reader. When it is 1.3, thirty percent of the spend went into streams that were abandoned, killed or silently dropped, and no model change will fix it.
Your proxy is holding the stream
Server-sent events are an ordinary chunked HTTP response with a content type. Nothing in the protocol obliges an intermediary to forward chunks as they arrive, and the most common intermediary does not. Nginx buffers proxied responses by default — proxy_buffering on, with buffers sized by proxy_buffer_size and proxy_buffers — reading the whole upstream body as fast as it can and forwarding in units it finds convenient. For a static page this is a feature. For a token stream it means the user sees nothing until the buffer fills or the response ends, and the only visible symptom is a burst at the end.
The fix is one response header, because it travels with the response instead of living in a config file someone else owns:
Cache-Control: no-cache, no-transform
X-Accel-Buffering: no
Content-Type: text/event-stream
# nginx, if the header is ever stripped by a sub-filter
proxy_buffering off;
proxy_cache off;
gzip off;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_read_timeout 300s;
Each line earns its place. no-transform stops a CDN from re-compressing or rewriting the body, which is a distinct mechanism from caching and survives no-cache. gzip off matters when the compression list includes event streams, because a compressor with a five-kilobyte window will withhold exactly the small frames you need delivered now. And proxy_read_timeout is a limit on the gap between two reads from upstream, not on total duration — which is why a stream that thinks for forty seconds before its first token needs a keepalive rather than a larger total timeout.
The spec suggests a comment line every fifteen seconds for exactly this reason. A line beginning with a colon is ignored by every conforming parser and resets every idle timer in the path, so a long tool call does not look like a dead connection:
// emitted by the server when no token has been written for a while
: keepalive\n\n
Buffering is also the one failure that is invisible to the application: the server wrote every chunk, the logs show a clean stream, and only the client knows it arrived late. The diagnostic worth having is the distribution of flushes per stream — a healthy one writes many times per second of generation, a buffered one writes once, just before close.
A chunk boundary is not an event boundary
Now the client side, where the bug is not environmental but mathematical. TCP gives you bytes, delivered in whatever grouping the network and the runtime chose. An SSE frame is a logical unit that ends with a blank line. The two are unrelated, and a reader that assumes one read equals one frame works perfectly on a local network and fails in production roughly one time in a few hundred, at the exact moment a frame straddles two reads.
The naive version is common enough to recognise on sight:
// wrong: each network chunk is not a frame
for await (const chunk of response.body) {
const text = decoder.decode(chunk);
for (const block of text.split('\n\n')) {
handle(JSON.parse(block.replace(/^data: /, '')));
}
}
It breaks in three ways at once. A frame split across chunks yields two fragments that are not JSON. A multi-line data field — which the spec allows, and which servers emit for payloads containing newlines — is a single event that this code treats as several. And decoding each chunk independently corrupts any character whose UTF-8 encoding straddles the boundary, which for a stream of emoji or non-Latin text is not rare.
The correct reader is a line buffer with a carry, and it follows the spec's rules rather than guessing: fields before the first colon, a single leading space stripped from the value, multiple data lines joined with newlines, comment lines dropped, blank line dispatching the event.
async function* events(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
const reader = body.getReader();
const decoder = new TextDecoder();
let carry = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
// stream: true keeps a split multi-byte character in the decoder
carry += decoder.decode(value, { stream: true });
let index: number;
while ((index = carry.indexOf('\n\n')) !== -1) {
const frame = carry.slice(0, index);
carry = carry.slice(index + 2);
const data = frame
.split('\n')
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).replace(/^ /, ''))
.join('\n');
if (data.length > 0) yield data;
}
}
}
Two details in that function are the whole test suite. The carry is never reset per chunk, so a frame that starts in one read and ends in the next is assembled once and dispatched once. And the decoder is fed with stream: true, so a four-byte codepoint split after its second byte stays in the decoder instead of becoming three replacement characters — a corruption that no amount of retrying recovers, because the bytes were valid and the client destroyed them.
CRLF endings deserve a sentence, since some proxies normalise and some do not. A server writing \r\n\r\n will not match a search for \n\n, so the delimiter check belongs on a normalised buffer or must accept both. This is the kind of bug that ships twice: once in staging behind a proxy that rewrites, and once in production behind one that does not.
Tool calls do not arrive as objects
Text deltas concatenate, so they survive almost any handling. Tool calls do not. In the OpenAI-style protocol each delta carries a tool_calls array whose entries have an index, an id that appears only on the first fragment, a name that may be split, and an arguments string that is a fragment of JSON — individually invalid, meaningful only when joined. Parallel calls interleave in the same stream, so the array position is not the call's identity.
type Partial = { id?: string; name: string; args: string };
function accumulate(calls: Map<number, Partial>, deltas: readonly ToolDelta[]): void {
for (const delta of deltas) {
const slot = calls.get(delta.index) ?? { name: '', args: '' };
if (delta.id) slot.id = delta.id;
if (delta.function?.name) slot.name += delta.function.name;
if (delta.function?.arguments) slot.args += delta.function.arguments;
calls.set(delta.index, slot);
}
}
// parse only once the stream reports finish_reason: 'tool_calls'
const args = JSON.parse(entry.args) as unknown;
const parsed = schema.safeParse(args);
if (!parsed.success) throw new TruncatedToolCall(entry.name);
Three failures follow from getting this wrong. Parsing a fragment throws, and a retry inside the loop turns a recoverable stream into a duplicated call. Keying by array position merges or splits parallel calls, so a two-tool step executes one tool twice with the other's arguments. And parsing at the end is necessary but not sufficient: a stream truncated after the last brace still parses, and still misses required fields, which is why validation has to run before dispatch rather than after the tool has already written something.
Anthropic's protocol makes the same point with a different shape: content blocks are opened and closed explicitly by index, tool arguments arrive as input_json_delta fragments of partial_json, and thinking blocks carry a signature delta just before they close. Any accumulator written for one provider and pointed at the other will treat block boundaries as content.
Breaking out of the loop does not stop the model
This is the most expensive misunderstanding in the list. A reader that stops reading, or a function that returns early, does not tell the provider to stop generating. Tokens are billed as they are produced, so an early exit means the remainder is generated, charged and discarded — while the connection may stay open until the server finishes writing into a socket nobody reads.
Cancellation has to be explicit and it has to reach two places: the HTTP request, through an AbortController signal passed to the client, and the reader, which should be cancelled in a finally block so the body is released even on the success path.
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 120_000);
try {
const stream = await client.chat.completions.create(
{ model, messages, stream: true, stream_options: { include_usage: true } },
{ signal: controller.signal },
);
for await (const chunk of stream) {
if (chunk.usage) recordUsage(chunk.usage);
const text = chunk.choices[0]?.delta?.content;
if (text) await emit(text);
}
} finally {
clearTimeout(timer);
controller.abort();
}
Usage accounting interacts with cancellation in a way that quietly breaks cost dashboards. With usage reporting enabled, the final chunk carries token counts and has an empty choices array — it arrives before the terminator, and code that indexes choices[0] unguarded throws on it. More importantly, if the stream is interrupted or cancelled you may never receive that chunk at all. A client that only records usage from the final frame therefore under-reports exactly the runs that were abandoned, which are the ones worth knowing about. Either estimate from a tokenizer at abort time and mark the row estimated, or accept that the abort path has no usage and instrument the count of such rows.
A stream is a view, not the record
Everything above is easier once one decision is made: the generation is a job, and the stream is one way to watch it. The job has an id, an owner, a state, and a stored result. The stream carries deltas of that result plus a sequence number. When the pipe breaks, the job does not.
That inversion fixes the reconnect problem without special cases. A resume request names the job and the last sequence number the client rendered; the server replays from that point out of a short-lived buffer — Redis, a table, whatever already exists — and continues live if the job is still running. A client that reconnects gets exactly the missing suffix, not the whole answer again, and a second tab can follow the same stream without starting a new generation.
Two constraints make it work in practice. The buffer needs a TTL, because a finished job does not need its deltas forever — only its final result. And replay is not continuation: a client that reloaded the page has lost its streaming state, so it must accept a full replay of the text part rather than a continuation of a half-rendered one. Libraries that handle this expose it as an explicit choice, and choosing wrong produces duplicated sentences that look like a model stutter.
There is a tempting shortcut here — put the assembled answer in the database only at the end — and it fails at the moment that matters. If the process dies at token nine hundred, there is no record at all, the client has text the server never stored, and the retry produces a different answer. Persisting the partial result, marked as partial, with the sequence number, costs one write per flush interval and converts an unrecoverable state into a resumable one.
A disconnect is not a stop
Users close tabs, refresh, switch applications, and put phones in pockets. Every one of those closes the connection. Treating that as a cancellation is wrong in one direction: the user paid for a generation that was one second from finishing, and now has nothing. Treating it as "keep going no matter what" is wrong in the other: an abandoned job keeps generating until it hits its token ceiling, and a user who refreshes twenty times has twenty jobs.
The resolution is a bounded grace period plus an explicit stop. On disconnect, mark the job detached and let it run for a short window — long enough to survive a refresh, short enough that an abandoned run cannot bill for minutes. If the client returns inside the window, attach and replay. If the user presses stop, cancel immediately, persist the partial result, and never auto-resume that job. And a hard cost ceiling per generation, enforced by the runner rather than by prompt politeness, so an orphan cannot exceed it even when nobody is watching.
The distinction has to survive the client too. A refresh is not a stop, so no cancellation should be sent from a cleanup function that runs on unmount; a page teardown and an explicit button press look identical at the socket level and must not be treated identically at the application level.
Retries must attach, not duplicate
Once streams fail partially, retries become a correctness problem rather than a reliability nicety. The safe boundary is precise and it is worth stating as a rule: a request may be retried only while zero content has been delivered. Before the first token, a retry is indistinguishable from the original attempt and costs nothing but time. After the first token, a retry is a second generation, a second bill, and a second answer that will not match the first — the model is not deterministic, so "try again" means "respond differently".
That rule implies the retry decision belongs on the server, next to the job, and not in the client's fetch wrapper. A request carries an idempotency key; the server either finds a job in progress and attaches, finds a completed job and returns its stored result, or starts one. Client-side retry logic that re-posts on a mid-stream failure breaks this in the most expensive way: the first job is still running, so both finish, both bill, and two answers exist for one question.
-- one row per request, not per attempt
INSERT INTO generation (id, request_key, state, seq, partial, usage)
VALUES ($1, $2, 'running', 0, '', NULL)
ON CONFLICT (request_key) DO NOTHING
RETURNING id;
-- 0 rows returned means the request already exists: attach, do not start
The retry rule also sets the failure message. A stream that broke after the first token cannot be silently restarted, so it must be resumed or surfaced: "the answer was cut off, continue from here" is honest and cheap, while a quiet second attempt produces two half-answers and a support ticket about hallucinations.
The buffer you cannot drop
One stream per user is fine. Ten thousand streams, each with a server-side queue decoupling generation from a slow socket, is a memory budget nobody wrote down. Generation happens at a steady rate; a mobile client on a weak link reads in bursts. Everything in between accumulates.
Text streams have an unusual property that constrains the fix: you cannot lossily drop tokens. Dropping one delta from a sentence produces a response that reads as broken, and it is not recoverable by the client because the client has no way to know something is missing. So the backpressure policy cannot be "drop oldest" the way a metric pipeline can. It has two honest options: block generation on the write, which transfers the cost to the provider's timeout and the wallet, or disconnect the slow reader and let it resume from the last sequence number when it can read again. The second is almost always right. The bound on the buffer is then a bound on the grace window, and the number to watch is peak buffered bytes per connection.
File descriptors belong in the same budget. A long-lived stream occupies a connection in the app, in the proxy, and in the load balancer, and the effective ceiling is the smallest of the three. Running out of them does not degrade streaming; it takes down every other endpoint on the host.
What to instrument
Six numbers make this class of failure visible, and five of them are cheap:
- Time to first token, per provider and per route — measured at the client, so a buffering proxy cannot hide in the 200 status.
- Maximum inter-token gap per stream — the p99 of the maximum. A single long gap followed by a complete body is a buffer, not a slow model.
- Completion ratio — terminal event reached divided by streams started, split by client and by route. Mobile clients will be lower; a desktop route at ninety percent is a bug.
- Tokens billed over tokens delivered — the ratio that translates abandoned streams into money.
- Resume rate and resume success — how often a stream is continued, and whether the continuation delivered the missing suffix without duplication.
- Flushes per stream — the diagnostic for buffering, and the one almost nobody emits until they have been paged for it.
The symptom-to-cause mapping is short enough to memorise. Everything arrives at once after a delay: buffering in a proxy or a compressor. Long stall mid-answer, then continuation: an upstream idle timeout, or a provider-side pause that needed a keepalive. Text stops but the request completes: an exception after the loop, swallowed by a handler that logged it. Duplicated sentences on reload: replay treated as continuation. Two answers for one question, both billed: client-side retry after the first token.
Tests that catch it
A fake upstream is the only way to test this without waiting for a network to fail at the right byte. The fake writes frames you control, one write per frame, so the reader's chunk boundaries are yours to choose. Three cases carry most of the value:
- Split the frame. Write a single event in two writes with the boundary inside the JSON string and inside a multi-byte character. Assert the assembled output is byte-identical to the unsplit version. This test fails on the naive reader every time.
- Kill at frame N. Close the stream after a known number of frames, then resume from the last sequence number and assert the concatenation of both halves equals the full answer, with no duplicate prefix and no missing sentence.
- Abort, then assert. Cancel mid-stream and assert three things: the job records partial content, a usage row exists or is explicitly marked estimated, and no second job was created for the same request key. The third assertion is the one that catches client-side retry logic.
Add a test for the multi-line field, because it is the case that passes review and fails in production: a delta containing a newline is legal, is emitted as two data lines, and is reassembled with a single newline between them. A parser that treats each line as an event will split a sentence in half and, because each half is valid JSON on its own, will not throw.
None of this is model work, which is why it gets skipped. It is the same class of problem as retry storms and durable workflow compensation: the failure is not in the reasoning, it is in the boundary between the system and everything it assumes. A stream that cannot be resumed, cannot be cancelled, and cannot say how many tokens it wasted is not a fast interface — it is an interface that hides its own costs. If you are shipping a streaming interface and cannot answer what happens at token nine hundred, tell us how the pipe breaks today; it is ordinary work in our AI engineering practice, and it reads better alongside step budgets and run traces than it does as a feature list.