AI Engineering · Concept Library · Free article
LLM Streaming
LLM streaming sends each token to the reader the moment the model produces it, so the wait ends at the first word instead of the last. It is the model's decode phase made visible rather than a UI trick, and getting it right decides whether your product feels instant or broken.
An LLM generates one token at a time, so you can either wait for the whole answer and show it at the end, or push each token to the user as it appears. Streaming almost always wins, because the number people feel is when the FIRST word lands, not the last. But streaming is more than a cosmetic word-by-word reveal: the stream you render is literally the model's slow, expensive decode phase, which is why a closed browser tab can keep burning money, and why a proxy you forgot about can silently turn your stream back into a wait.
Wrenlet's reply-drafter is accurate now, it abstains instead of inventing refund policies. But a new complaint lands on your desk: it's slow. An agent clicks “Draft reply,” and for eight seconds nothing happens. A spinner. Then, all at once, a paragraph appears. Some agents assume it's frozen and click again, firing a second call, doubling the cost, sometimes posting two drafts. The model is doing fine work. The waiting is the problem.
Here's the thing you already know from how the model works: it doesn't compute the whole reply and hand it over. It produces the first word quickly, then the next, then the next, one token at a time, each one fast. You are making the agent wait eight seconds for something the model started producing after a few hundred milliseconds. Streaming is the decision to stop hiding that.
Why stream an LLM response at all?
Streaming doesn't make the model faster, the last token lands at the same moment either way. What it changes is when the wait ends for the human. As soon as the first words appear, the reader starts reading, and reading occupies the very seconds that would otherwise be dead spinner time. By the time the final token arrives, they've often already consumed most of the answer. The wall-clock is identical; the felt experience is not.
Run the same Wrenlet reply both ways below. Both finish at exactly the same time. Watch how differently they land.
One thing to hold in mind for every panel on this page: the timings are Wrenlet's, and they are illustrative. They are sized to make one relationship visible at a time rather than measured off a production cluster, so your own first-token time will depend on your model, your prompt length and how far you sit from the region serving it. The shapes are what transfer. Measure the values yourself.
The interactive version of this example is available when JavaScript loads.
Rough perception guides (the classic response-time thresholds Miller measured in 1968 and Nielsen popularised): about a tenth of a second feels instant, and up to a second keeps a train of thought unbroken. Nielsen's third limit is ten seconds, the point past which people stop attending to the wait at all. A chat product loses them long before that, which is the whole argument for streaming: you are not trying to clear Nielsen's ten-second bar. You are trying to clear the much lower one your users set for a text box that answers back. Streaming lets a slow-to-finish answer still clear the “is this broken?” bar, because the first token arrives long before the last. This is why every major chat product streams, and why not streaming is the fastest way to make a capable model feel sluggish.
What streaming actually is: the decode phase, made visible
It's tempting to file streaming under “front-end animation.” It isn't. It's a window onto how the model runs. Generation happens in two phases. First prefill: the model reads your entire prompt in one parallel pass and builds up its internal state. This is the work that produces the first token, so prefill time basically sets your time to first token. Then decode: the model generates the reply one token at a time, each step depending on the last, strictly serial. That serial trickle is the stream. Token appears in the browser ⇄ one decode step on the GPU.
Two words are doing quiet work in that paragraph, and they matter later, so here they are. As the model decodes, it keeps a running summary of everything it has read and written so far, called the KV cache, and re-reads that whole thing to produce each next token. That is why decode is waiting on memory rather than on arithmetic, and it is why a long conversation decodes more slowly than a short one. And because one stream alone would leave the hardware idle, a serving engine runs many streams together, each holding its own KV cache in a slot, adding and retiring streams as they come and go. Slot is the thing you are competing for, and it is what a cancelled request gives back.
This split explains a puzzle: the two latencies move for different reasons. Prompt length feeds prefill, so it sets your first-token time; reply length and the model's decode speed set the rest. Push each slider and watch which number reacts. The reply-length slider does not move the first-token time by a single millisecond, which is the whole lesson. Then switch between the two models and push the prompt slider until the first token leaves the responsive band. Both of them get there. The gap between where they get there is the thing to notice.
The interactive version of this example is available when JavaScript loads.
What the panel settles is which lever owns which number. The reply-length slider moves the total and leaves the first-token time untouched at every setting, so writing a shorter answer is a throughput fix and never a responsiveness one. The prompt slider moves both, and the model's prefill speed decides how much room you have before the first token stops feeling immediate: on these illustrative figures the frontier model leaves the responsive band at around 3,600 prompt tokens and the small one holds on to about 8,000. Neither is immune, and the practical rule falls out of that. When your first token is slow, look at the prompt and at the model. Do not look at how much you asked it to write.
Server-Sent Events or WebSockets: how does a token reach the browser?
Over Server-Sent Events, in almost every case, and the reason is that the traffic only ever goes one way. To stream, the server can't send one response and close the connection. It holds a single response open and pushes each token down it as decode produces it. The near-universal way LLM APIs do this is Server-Sent Events: a one-directional stream of small text events over an ordinary long-lived HTTP response. You've used it: a stream: true flag on the OpenAI- and Anthropic-shaped APIs turns the reply into a sequence of little events, one per chunk, ending with a done marker. Google uses a separate streaming method rather than a flag, which is the first hint that the details here are per-provider.
Why this and not something fancier? Because the shape fits. The server needs to talk; the client only needs to listen. That one-way fit means plain HTTP with no special protocol upgrade, and it rides through normal infrastructure. You will read that the protocol reconnects on its own, and that is worth being precise about: reconnection is behaviour of the browser's built-in EventSource object, not of the wire format, and the next section explains why you will not be using EventSource. What the format gives you is the raw material, an id: field and a retry: field, so a resumable session is expressible. You write the resuming yourself, and for a token stream you usually do not want it, because the provider will not pick up a half-finished generation. It will start a new one and bill you for it. The two-way alternative: a full duplex socket, buys you nothing here and costs you sticky connections and harder scaling. You reach for that only when the client must stream back mid-generation (live voice), which most products don't.
Don't take “SSE won” on faith, score the options yourself. Fix the requirement (a one-way stream of text, straight to a browser over the open web) and check each transport against it: the one-way HTTP-native option fits every box, a WebSocket adds two-way power you aren't using, gRPC is a backend champion that browsers can't call directly, and a plain request isn't streaming at all.
The interactive version of this example is available when JavaScript loads.
Score all four and the same row wins for the same reason each time. Server-Sent Events is the only one that fits a one-way stream of text, reaches a browser directly, and travels through ordinary HTTP infrastructure with no protocol upgrade to negotiate. A WebSocket meets the first two and charges you for a return channel a token stream never uses. gRPC streaming is excellent between your own services and cannot reach a browser at all without a translating proxy in front of it. A plain request fails the one requirement that defines the problem, because it is not streaming. Notice what none of them differ on: tokens per second belongs to the model and the hardware, so this choice is about direction and reach, never about speed.
The trap that ships to production and not to your laptop
You build streaming, it's beautiful on localhost, you deploy, and in production it's back to an eight-second spinner and a wall of text. Nothing in your code changed. The culprit is almost always something between your server and the user: a reverse proxy, load balancer, or gateway that buffers the response. Instead of forwarding each token as it arrives, it quietly collects the whole thing and delivers it in one lump, turning your carefully streamed reply back into exactly the batch experience you were trying to escape.
A closed tab is not free
Recall that the stream is the decode phase, and decode is the expensive majority of the request. Now a customer opens Wrenlet, gets 40% of the way through the answer, sees enough, and closes the tab. What happens on the GPU? If nothing tells it to stop, it keeps going, dutifully generating the rest of a reply that no human will ever read, one costly token at a time, and billing you for every one. The browser is gone; the meter is still running.
The fix is to make cancellation propagate: when the client disconnects, the signal has to travel all the way to the model call and abort it, freeing that slot for the next customer. Be precise about what that buys you, because it depends on who owns the GPU. If you run the serving fleet, aborting genuinely stops the work and frees the slot, and you can watch it happen. If you call a provider's API, which is what Wrenlet does, aborting the HTTP request is what you have; no major provider documents whether generation stops or billing stops when you do, so measure it against your own invoice before you count the saving. What is certain either way is that nothing useful is produced after the tab closes. Raise the abandonment rate and flip the switch:
The interactive version of this example is available when JavaScript loads.
Where streaming fights the rest of your system
Streaming is not free of trade-offs. The sharpest one: it fights structured data. If Wrenlet's reply needs to come back as machine-readable JSON, an intent, a refund amount, a priority, then a half-finished stream is useless, because every partial chunk is invalid until the closing brace lands. You can't act on {"refund_amount": 4 mid-stream. So the very thing that makes text feel fast makes structured output awkward: you're often back to waiting for the whole object. Managing that tension is its own skill, the structured outputs page is the next read.
Two more rough edges worth naming. Partial rendering: a token can cut a markdown link or a code block in half, so a naive renderer flashes broken formatting, you buffer until a fragment is whole before displaying it. Mid-stream errors: because the response returned a success status before generation finished, an error can arrive after you've already shown the user half an answer. You need a “stitch the final message together and check how it actually ended” step rather than assuming a 200 meant success.
Which streaming metrics actually matter?
Three, and total response time is not among them: time to first token, the gap between tokens and how much that gap varies, and sustained tokens per second. An average response time hides all three, because it reports one number for a thing the reader experiences as a beginning and a rhythm.
| Metric | What it is | Why it matters |
|---|---|---|
| Time to first token | How long until the first word appears (≈ prefill time). | This is the perceived-latency number: the “is it working?” bar. Optimize this first. |
| Inter-token latency (and its jitter) | The gap between successive tokens during decode, and how much that gap varies. | A good average gap can still stutter badly if the tail spikes; jerky text reads as broken even when the mean looks fine. Watch the worst case, not just the mean. |
| Tokens per second | Sustained decode throughput. | Sets whether the reply keeps pace with reading. Comfortable reading runs around 200 to 300 words a minute, which is only about 5 to 7 tokens a second, so almost any model clears it. That is why the first-token time and the jitter matter more than this number for a text product, and why it becomes the binding constraint only when something downstream consumes the tokens faster than a person does. |
Set targets per surface, because they differ wildly: an inline agent-assist can tolerate a slower first token than a live voice assistant, where the budget for the first token is brutally tight because speech synthesis downstream eats the rest. And when you autoscale the serving fleet, scale on concurrency, meaning how many streams are in flight, rather than on raw GPU utilization. The reason is worth knowing, because it catches people out in the opposite direction from what they expect. NVIDIA defines that metric as the percent of time over the sample period during which at least one kernel was executing. Decode always has a kernel executing, so the number pins near 100% long before the fleet is actually full, and it stays there whether you are serving four streams or four hundred. It saturates, so it cannot tell you about headroom. Streams in flight or queue depth can.
What do teams actually build this with?
A provider SDK for the call, a framework helper for the server, and, on the front end, a toolkit that turns the stream into rendered text. A useful thing to internalise before picking between them: the transport is almost never your bottleneck. Tokens-per-second is set by the model and the hardware, so Server-Sent Events, a WebSocket, or gRPC all deliver the stream at the same speed, you choose between them for direction, reconnection, and how they scale, not for raw throughput. That's why the one-way, HTTP-native option wins for browser apps, as the transport comparison earlier showed. What actually varies day to day is the tooling you reach for.
| Tool | What it is | Its streaming surface |
|---|---|---|
| Provider SDKs | The official OpenAI / Anthropic / Google clients. | A stream: true flag returns an iterator of delta events; a built-in helper accumulates the final message. |
| Vercel AI SDK | A full-stack TypeScript toolkit for AI UIs. | Server helpers stream text and tool calls to React hooks over an SSE-based protocol: the common front-end path. |
| LangChain / LangGraph | An orchestration framework. | A stream call yields tokens or per-step updates; a typed event stream exposes start / delta / end for each stage. |
| Web frameworks | FastAPI, Express, and friends. | A streaming-response object over text/event-stream; you write each token and flush. |
| Serving engines | vLLM, TGI, Triton behind the API. | Native token streaming over HTTP and gRPC: the source every higher layer relays. |
How do you read a token stream in code?
Because the browser's built-in event client can't send an auth header or a POST body, real apps read the stream by hand. The client shape is always the same:
The client read-loop, step by step
- Open a cancellable request.
fetch(url, { method: 'POST', body, signal })withstream: truein the body, and hold theAbortControllerso you can stop it later. - Read the body as chunks.
const reader = res.body.getReader()plus aTextDecoder; loop onreader.read()until it reports done. - Buffer across reads. A single event can be split across two network chunks, so append each decoded chunk to a running buffer and only act on whole events.
- Split on the blank line. SSE events are separated by an empty line; cut the buffer there and keep any trailing partial for the next round.
- Parse each data line. Stop if the payload is the provider's end marker; otherwise
JSON.parseit, pull the delta (delta.contentordelta.text), and append it to the message you're rendering. - Finish honestly. When the stream ends, take the accumulated message and its stop reason as the source of truth: a mid-stream error can arrive after the initial
200 OK.
The six habits, and the mistake each one prevents
Two of these have not come up yet. The rest are the sections above, compressed into the form you would put on a checklist.
| Wire this in | Because otherwise |
|---|---|
| Stream by default, and budget a first-token target per surface. | A capable model feels slow, and you spend the week optimising the total latency, which is the number nobody feels. |
Turn buffering off at every hop, and set X-Accel-Buffering: no on the response. | It streams beautifully on your laptop and arrives in one lump in production, with application logs that look perfect. |
| Send a keep-alive comment on a short timer, about every 15 seconds. | An idle-timeout killer on a proxy cuts a long, quiet stream off mid-reply. The SSE spec names that interval and that reason: a comment line every 15 seconds or so, to survive proxies that drop a quiet connection. |
| Pass an abort signal, and wire client disconnect through to the model call. | Abandoned replies keep decoding, holding a slot the next customer is queuing for. |
| Let a slow client slow your reader instead of buffering the reply in memory. | One slow reader on a long answer becomes a memory problem you will debug at the wrong layer. Reader-driven streams handle this for you unless you fight them. |
| Hold a half-written markdown link or code fence until it is whole, and reconcile the assembled message and its stop reason at the end. | The UI flickers broken formatting, and a truncation or a late error arrives after the 200 OK you already treated as success. |
The seventh habit is not a wire at all, it is a decision: settle per call whether this one streams text or returns structure, because a half-finished JSON object is worth nothing to the code waiting on it.
Interview cheat-sheet, intern to principal
- Why do LLM replies stream instead of arriving all at once?
- Because the model generates autoregressively, one token at a time, so the first token is ready long before the last. Streaming pushes each token as it's produced, which collapses perceived latency: the user starts reading immediately instead of staring at a spinner. Total latency is unchanged; the felt wait is far shorter.
- Time to first token vs total latency, which do you optimize and why?
- Time to first token, almost always. It maps to prefill (reading the prompt) and it's the number the user feels, the moment the wait visibly ends. Total latency is dominated by decode and matters for throughput and cost, but a great first-token time with a slightly slower finish feels far better than the reverse.
- Why is Server-Sent Events the standard transport for LLM streaming rather than WebSockets?
- The data flow is one-directional: the server streams tokens, the client only listens. SSE fits that exactly over plain HTTP, with no protocol upgrade, and it scales statelessly through ordinary infrastructure. Its
id:andretry:fields make a resumable session expressible, though the automatic reconnection people credit it with belongs to the browser'sEventSourceobject rather than to the format, and real clients read the stream withfetchinstead. WebSockets add bidirectional capability you don't need and sticky connections you'd rather avoid; you'd only reach for them when the client must stream back mid-generation, like live voice. - Your streaming works locally but batches in production. What happened?
- Almost certainly a reverse proxy, load balancer, or gateway buffering the response, collecting all the tokens and delivering them in one lump. Your server streamed fine; the infrastructure re-batched it. Disable response buffering on every hop, and check for compression and idle-timeout settings that break long-lived streams.
- How is streaming connected to inference cost?
- The stream you render is the decode phase, and decode is the serial, expensive majority of a request. That means stopping decode early is a cost lever: if a user abandons a reply and the cancellation doesn't propagate to the model call, the GPU keeps generating tokens nobody reads, at full price. Wiring client-disconnect through to abort the generation reclaims the slot and the spend.
- What breaks when you need structured output from a streaming response?
- Every partial prefix of a JSON object is invalid until it's complete, so you can't act on the structured data mid-stream, you're effectively back to waiting for the whole object. You either give up token-by-token streaming for that call, or use a tolerant incremental parser that fills typed fields as they complete, accepting that you only have a guaranteed-valid object at the end.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.