# Streaming

> The Streaming is a technique of sending the response of a model in parts while it is being generated.

## How do I stream LLM responses to the browser?

The technique where the API sends generated tokens in chunks as soon as they are ready, usually via Server-Sent Events. Users see the answer appear immediately instead of waiting for the full response.

- Topic: APIs & Integrations
- Type: technique

## Example

Wrong:

```js
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
  const event = JSON.parse(chunk.replace('data: ', ''));
  render(event.text);
}
```

Right:

```js
let buffer = '';
for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
  buffer += chunk;
  const events = buffer.split('\n\n');
  buffer = events.pop();
  for (const e of events) render(JSON.parse(e.replace(/^data: /, '')).text);
}
```

Buffering until a blank line handles events split across chunks, which a direct `JSON.parse` of each chunk breaks on.

## Common mistakes

- A proxy buffers the response, so the whole answer appears at once.
- Parsing each chunk as complete JSON when an event is split across chunks.

## Key points

- The client reads the stream incrementally and handles chunks split mid-event.
- The user can cancel, and cancel aborts the request with `AbortController`.
- Errors that arrive mid-stream are shown to the user, not silently dropped.
- Tool call arguments are parsed only after their last fragment arrives.

## Interview questions

### SSE vs WebSocket for streaming LLM responses?

SSE is enough for one-way token streaming from server to browser over plain HTTP. WebSocket is needed when both sides send messages continuously.

### Why does my streamed response appear all at once?

Something between the server and browser buffers it, often a proxy or compression. Disable buffering for the route and flush each chunk.

### Can I use EventSource for LLM streaming?

Only for GET requests without custom headers. For POST with a body, read the stream with `fetch` and parse the events yourself.

## Related cards

- [Server-Sent Events](https://wonderium.dev/web/server-sent-events.md)
- [fetch()](https://wonderium.dev/js/fetch.md)
- [AbortController](https://wonderium.dev/js/abort-controller.md)
- [LLM API](https://wonderium.dev/ai/llm-api.md)
- [Latency](https://wonderium.dev/ai/latency.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/streaming
- Last updated: 2026-11-25
