Streaming LLM Tokens to the Browser
Deliver model output token by token with server sent events, handle disconnects cleanly, and avoid buffering that turns a fast first token into a long wait.
On this page
Introduction
Users judge a model by how quickly text appears, not by total generation time. Waiting for the full answer before rendering means staring at a spinner for many seconds, even though the first tokens were ready almost immediately. Streaming flushes each token to the client as it is produced, so the interface feels responsive and users can start reading while generation continues. The engineering challenge is getting every layer between the model and the browser to stop buffering and to handle disconnects without leaking resources.
Why Buffering Defeats Streaming
Streaming fails when any proxy, framework or compression layer accumulates bytes before forwarding them. A reverse proxy that buffers responses, a framework that only flushes at the end, or gzip middleware that holds data can each turn a token stream into a single late burst. Every hop must be configured to flush immediately, and the response must be marked so intermediaries do not coalesce it. Test with a deliberate delay between tokens and confirm they arrive incrementally rather than all at once.
import type { Request, Response } from 'express';
export async function streamAnswer(req: Request, res: Response) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no'); // disable nginx buffering
res.flushHeaders();
const generationId = crypto.randomUUID();
const controller = new AbortController();
// Abort upstream work the moment the client goes away.
req.on('close', () => controller.abort());
let index = 0;
try {
for await (const token of callModel(req.body.prompt, controller.signal)) {
res.write(`event: token\ndata: ${JSON.stringify({ index: index++, text: token })}\n\n`);
}
res.write(`event: done\ndata: ${JSON.stringify({ generationId })}\n\n`);
} catch (err) {
res.write(`event: error\ndata: ${JSON.stringify({ message: 'generation failed' })}\n\n`);
} finally {
res.end();
}
}
Choosing a Transport
Server sent events give a simple one way text protocol over HTTP with automatic reconnection and named event types, which fits token streaming well. Chunked HTTP responses with newline delimited JSON work when you want to control framing yourself. WebSockets are the right choice only when you also need client to server messages on the same channel. For most chat interfaces SSE over HTTP is simpler to operate, degrades gracefully, and passes through existing proxies when configured to flush.
export function consumeStream(url: string, onToken: (t: string) => void) {
const source = new EventSource(url);
let buffer = '';
source.addEventListener('token', (e) => {
const { text } = JSON.parse((e as MessageEvent).data);
buffer += text;
onToken(buffer); // caller renders as a safe text node, never innerHTML
});
source.addEventListener('done', () => source.close());
source.addEventListener('error', () => {
// EventSource auto-reconnects; treat as a fresh generation server side.
console.warn('stream interrupted');
});
return () => source.close();
}
Framing the Token Events
Send each piece of the answer as an event with a type, so the client can distinguish content from a final usage summary or an error. Include an identifier for the generation and a monotonically increasing index so the client can detect gaps and order events even if the transport reorders them. Send a terminating event explicitly rather than relying on connection close, because a proxy timeout looks identical to a completed answer at the client otherwise.
Handling Disconnects and Cancellation
When the browser closes the connection the server must stop generating, otherwise you pay for tokens nobody will read and hold a worker for a dead client. Listen for the close event and abort the upstream model request through an abort signal so the provider stops billing. On the client, treat reconnection as a new generation unless you have server side resumability, and make the request idempotent so a retry does not start a duplicate job. Clean up timers, listeners and buffers on both ends.
Backpressure and Slow Consumers
A client on a slow connection cannot consume tokens as fast as the model produces them, so unread bytes accumulate in memory. Apply backpressure by pausing the upstream stream when the write buffer crosses a threshold and resuming when it drains, or drop to a coarser granularity such as sentences. Without backpressure a handful of slow clients can exhaust server memory, which is a denial of service you caused yourself. Bound the per-connection buffer and disconnect clients that stay slow beyond a deadline.
Security and Correctness on the Wire
Validate the request before starting generation, because a stream that begins and then fails still costs money and can leak partial output. Send the appropriate content type, disable caching and buffering headers, and ensure the endpoint requires authentication. Never echo raw model output into HTML without escaping, since streamed text arrives piecewise and a naive renderer can assemble a script tag across chunks. Accumulate into a safe text node and render incrementally.
Testing the Stream End to End
An automated test should assert that the endpoint returns multiple chunks rather than one, that the first chunk arrives within a latency budget, that a mid stream abort stops upstream generation, and that the terminating event is present. Record time to first token and tokens per second in production, because a regression in proxy buffering shows up as a jump in first byte latency while total duration barely changes. These metrics turn a subjective feeling of speed into something you can regression test.
When Blocking Beats Streaming
Streaming is not always the better experience. For very short answers the overhead of connection setup and event framing can exceed the generation time, and a single response is simpler to cache and to inspect. For structured output that must be validated before use, streaming raw text to the client risks showing invalid data that later fails validation, so it is often better to validate and then deliver in one piece. Stream when the answer is long, when users read as it appears, and when time to first token is the metric that matters; block when correctness of the whole payload is the priority.
Sources
Sources: MDN server sent events, MDN Streams API, Node.js HTTP response.
FAQ
- Why do my tokens arrive all at once?
- Something in the path is buffering. Disable buffering on the reverse proxy, avoid compression on the stream, flush headers explicitly, and mark the response no-transform.
- Should I use WebSockets instead of SSE for chat?
- Only if you need client to server messages on the same channel. For one way token streaming, SSE over HTTP is simpler, reconnects automatically, and is easier to operate behind existing proxies.
Report a problem with this articleOpens a pre-filled issue on GitHub.