What you'll learn: By the end of this lesson you will be able to read a streamed reply from a
fetchbody as bytes, explain why chunk borders can fall inside an event or inside a character and how a streaming decoder handles that, turn events into actions for a reducer, tell five endings apart (done, error event, a stream that just stops, a failed connection and the user's Stop), cancel a stream with anAbortControllerso that Stop acts at once, apply updates once per frame, redraw only the paragraph still being written, and test all of it without a model or a network.
Imagine taking dictation over a bad phone line. The line delivers sound in little bursts that stop wherever they like, sometimes in the middle of a word. Your job is to write down what was said, never garbage from a cut word, and to know when the letter is finished: the speaker says "yours sincerely". If the line goes dead before that, you do not hand the letter over as complete. If the sender says "stop", you keep what you wrote and put the pen down. Reading a streamed model reply is this job: the sound is bytes, the sign-off is a terminal event, and the bad line is the network.
AI-Powered Frontend Architecture placed this work in the whole system. This lesson does the browser end in detail. The running example is the help assistant panel from that lesson: a text box, a growing answer, a Stop button and a status line.
This lesson uses a model of a stream, not a real one. The lab's "provider" is a fixed script that turns a string written for the lab into server-sent-event bytes. Its event names (delta, done, error, ping) and its JSON are the lab's own, not any provider's schema, and its text is not model output. No model and no network is involved, and nothing printed in this lesson is a real model response.
The core idea
- A stream is bytes, not messages and not characters. Chunks end wherever the network ended them: in the middle of an event, in the middle of a field, in the middle of a multi-byte character. Everything above the bytes must be correct for every possible cut.
- Build the client as layers, and test each layer alone. Bytes become events, events become actions, actions pass through a batcher into a reducer, and the reducer's state is drawn. Only the last step needs React.
- How the stream ends is part of the data. A terminal event means complete. The end of the bytes without one means cut short. A thrown error means failed, unless the user caused it with Stop. Every ending keeps the text received so far.
Three illustrations run through the lesson: a minimal example (decoding one reply from two chunks), a failure example (a stream cut in the middle of a character, and a stream that ends with no done) and a realistic example (the help panel, with the batcher and the block splitter).
The layers
Figure 1. From bytes to pixels
How to read this: the top row works on bytes and events and needs no React. The bottom row turns actions into state and draws it. Stop reaches the consumer directly, so it does not have to wait for the next piece of data.
The lab has a file for each box: sse.ts, consume.ts, batcher.ts, state.ts, blocks.ts and a thin react.tsx. All but the last are plain TypeScript, tested without a DOM.
Reading the body
In the browser the source is the response body of a fetch. MDN says Response.body is exposed as a readable stream, and that getReader() creates a reader locked to the stream so no other reader can read it. A call to read() returns a promise that resolves to { value, done: false } when a chunk is available and to { value: undefined, done: true } when the stream closes, and rejects if the stream errors. MDN also notes that the body is an async iterable, so for await works. A sketch, which the lab does not run because it has no network:
// Sketch only: not run in the lab, which has no network.
const controller = new AbortController();
const response = await fetch("/api/assistant", { method: "POST", body: JSON.stringify({ prompt }), signal: controller.signal });
if (!response.ok || response.body === null) throw new Error(`Response status: ${response.status}`);
for await (const chunk of response.body) {
// chunk is a Uint8Array: bytes, cut anywhere
}
The status check matters. MDN says fetch() rejects on a network error but fulfils with a Response for a status such as 404, so you check ok before reading the body. Once a stream has started, the status is already 200, which is why an error mid-stream has to arrive as data. Anthropic's documentation says exactly that: after a stream starts the API has already returned a 200, so it sends an error as an error event.
Chunk borders fall anywhere
Figure 2. One event, three chunks
How to read this: the decoder never hands up half an event or half a character. It holds what is incomplete until the rest arrives.
Two separate problems hide here. The first is the event border: a server-sent event ends with a blank line, and a chunk can end anywhere before it. A decoder must keep an incomplete line and an incomplete event between chunks. The second is the character border: UTF-8 uses more than one byte for many characters, and a chunk can end after the first byte of one. MDN documents the stream option of TextDecoder.decode() as a flag that says whether more data will follow in later calls: set it to true when processing chunks. The page does not spell out what happens to a split character, so the lab shows it by measurement.
Illustration 1: the minimal example. The lab encodes a nine-event stream (338 bytes) containing "Café", an arrow and an emoji, then cuts it into two chunks at every one of 337 positions. The decoder in sse.ts keeps one TextDecoder with { stream: true }, and every cut gives the same text. A second experiment decodes each chunk on its own with a fresh TextDecoder: 6 of the 337 cut positions damage a character, which is the count of bytes after the first in the three multi-byte characters (1 + 2 + 3). The golden output below prints both counts. The decoder also holds back a lone carriage return at the end of a chunk, because it might be the first half of a CRLF line ending.
The lab's decoder is deliberately small. It reads event and data fields, joins several data lines with a newline, ignores comments and other fields, and discards a half-sent event when the stream ends. The full rules, including id, retry and reconnection, are in Server-Sent Events in Depth, and what to do after a drop is in Reconnection and Message Ordering.
What real streams look like
The lab's events are invented. Real providers document theirs, and a client for a real provider maps them onto the same small set of actions.
| What happened | Anthropic's streaming events | OpenAI's streaming events | Action in the lab |
|---|---|---|---|
| Text arrived | content_block_delta carrying a text_delta |
response.output_text.delta |
delta |
| The reply ended normally | message_stop |
response.completed |
done |
| The provider reported an error | an error event, for example overloaded_error |
an error event |
error |
| Keep-alive or bookkeeping | ping, message_start, message_delta, block start and stop |
other typed events such as response.created |
ignored |
| An event the client does not know | new types may be added | the guide lists further event types beyond those four | ignored, not fatal |
Anthropic's documentation describes the flow as message_start, then content blocks each with a start, any number of content_block_delta events and a stop, then one or more message_delta events, then message_stop, with any number of ping events possible. Its versioning policy allows new variants of streaming event types, and the streaming page says code should handle unknown event types gracefully. OpenAI's guide says events are typed, each with a type property, and a text stream commonly uses response.created, response.output_text.delta, response.completed and error. Because both formats can grow, the lab's consumer skips an event name it does not know and records it, instead of failing.
Two details matter. A tool call's arguments arrive as partial JSON strings in Anthropic's stream, to be accumulated and parsed once the block ends, so a text client never parses half an object. And the outcome of a reply is not in the status code: the terminal event carries it.
The reply state
The reducer in state.ts has six statuses: idle, streaming, complete, stopped, failed and interrupted. Only streaming accepts changes. A late text piece after Stop, or a second done, returns the same state object, so nothing is redrawn and nothing is overwritten. This is the state machine of the previous lesson, now as running code.
export function reduce(state: StreamState, action: Action): StreamState {
if (action.type === "start") return { ...initialState, status: "streaming" };
if (state.status !== "streaming") return state; // same object: nothing to redraw
Figure 3. How did the stream end?
no terminal event"| I["interrupted"] A -->|"ordinary chunk"| R
How to read this: the loop continues only on an ordinary chunk. Each of the other five arrows is an ending, and all five keep the text received so far.
Illustration 2: a failure. The lab's fourth demo section runs the endings with the same three pieces of text. Done gives complete. An error event gives failed with the provider's message. A stream that simply ends gives interrupted, with outcome cut. A source that throws gives failed with "connection lost". Stop after two of three pieces gives stopped with two. The text is kept every time. The case to remember is the third one: a client that treats the end of the bytes as success would call a cut reply complete. Anthropic's documentation says that on a mid-stream connection drop no error event arrives, which is exactly this case.
Stop that acts now
To cancel, the page calls abort() on an AbortController whose signal was given to fetch. MDN says the fetch() promise then rejects with an AbortError, and that if the abort comes after fetch() fulfilled but before the body has been read, reading the body rejects with an AbortError. MDN's guide to readable streams adds a caution for loops: code in the loop runs only when the stream has new data, so there may be a delay between the signal being aborted and the loop stopping.
With a real fetch body the read itself rejects, so the delay should not appear. The lab reads from any async source, including a hand-driven one that simply waits for the next chunk, so its consumer races the next read against the abort signal:
const step = await Promise.race([next, aborted]);
if (step === "aborted") return leave("aborted");
The test for this would hang if the consumer waited for another chunk, and it passes. Two small rules go with it. An error that the source throws after an abort is not reported as a failure, because the user caused it. And the page sets the stopped status itself, immediately, and keeps the text it has. In the lab's hook, stop flushes held text, dispatches stop and closes the batcher, so nothing from the old stream can arrive later.
A new Send does the same to the previous reply, so a late piece from it cannot be appended to the next answer.
Once per frame
A model can send many small pieces in the time of one frame. Applying each one as its own state update means a render for each. The lab's batcher holds the text of deltas that arrive between two frames and releases it as one delta action that carries a count of the parts. A scheduler is injected: in a page it would call requestAnimationFrame, which MDN describes as running your callback before the next repaint, at a frequency that generally matches the display refresh rate, and paused in most browsers in background tabs. In the lab a manual scheduler stands for "the next frame".
Any other action releases held text first, so a done never overtakes the last words. Illustration 3: the realistic example is the third demo section: 40 deltas in one task give 40 state updates without the batcher and 1 with it, with the same final text, and three bursts with a frame after each give 3 updates for 6 deltas. A hidden tab holds the text until it is visible again, which is a choice to make on purpose: the state is not lost, but nothing is drawn.
Redrawing only the tail
Drawing each update still means drawing the whole answer, unless the finished part is skipped. A block of text is finished when it is followed by a blank line outside a code fence, and from then on it never changes. The lab's splitBlocks returns the finished blocks and a tail, and reports whether the tail is inside an unclosed code fence. A React component for each finished block, wrapped in memo, is not redrawn while the tail grows. Over the 26 updates of the demo text, redrawing everything draws 1677 characters and redrawing only the tail draws 505. Both numbers come from one small text and prove only the direction of the effect.
The splitter models Markdown with only blank lines and triple-backtick fences. A real renderer must also cope with lists, tables and emphasis not yet closed. The principle carries over: decide which part is final and draw it once.
Screen readers need a different treatment. MDN says aria-live="polite" is for updates that are important but not so rapid as to be annoying, and that the screen reader speaks changes when the user is idle. The lab's component marks only the status line as a status and leaves the growing text as ordinary content, with aria-busy on the region while it is streaming. Announcing every piece would be unusable. Accessible Forms and Dynamic Content covers live regions in general.
The thin React layer
useLlmStream is a reducer, an AbortController in a ref and the batcher. start aborts and closes any earlier run, creates a new controller and batcher, dispatches start and hands the source to consume. stop aborts, flushes, dispatches stop and closes. An effect aborts on unmount. A Reply component maps the six statuses to a status line, draws the finished blocks and the tail, and shows an error as an alert. The tests render it with Testing Library into jsdom, fed by a hand-driven source.
MDN's streams concepts page describes backpressure, where a slow stream later in a chain signals earlier ones to slow down, and says a readable stream's queue holds chunks that have been enqueued but not yet read. The lab's consumer only decodes and dispatches, so it keeps up. A consumer that did slow work per chunk would let unread chunks pile up, and the better answer is less work per chunk, which is what the batcher and the tail split give.
Choosing
| Decision | Choice | Gain | Cost |
|---|---|---|---|
| Source | fetch body (POST, headers) |
Any method, body and auth header | You parse the event format yourself |
| Source | EventSource |
Built-in parsing and reconnection | MDN documents only a URL and withCredentials |
| Decoding | One streaming TextDecoder |
Characters survive any cut | State to keep between chunks |
| End of reply | Terminal event | A cut stream is visible | The server must send one |
| Updates | Once per frame | Few renders | A scheduler; held text in hidden tabs |
| Drawing | Finished blocks and a tail | Little work per update | A splitter to maintain |
| Stop | Abort plus stopped status |
Immediate, keeps the text | Server must stop its own work |
Build it: decode, reduce, batch, end
Goal. Run a model of a streamed reply through six situations: chunk borders, one reply action by action, frames, five endings, events the client does not know, and finished blocks.
Setup. The lab is examples/frontend/labs/llm-stream-client in the course's example workspace (Node 26.13.1, React 19.3.1, Vitest 5.1.0, jsdom). The core is pure TypeScript; React and Testing Library are used only for the thin layer's tests. There is no network and no model.
cd examples/frontend
pnpm install
cd labs/llm-stream-client
pnpm test # 47 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In section 1, find "6 positions damage a character". Those are the cuts that fall inside a multi-byte character when each chunk is decoded alone.
- In section 3, compare 40 updates with 1.
- In section 4, read the five endings side by side; only
interruptedcame from a stream that said nothing. - In section 6, watch the open code fence stay in the tail until it closes.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01):
A streamed reply in the browser: bytes, events, state, frames and endings (a model, not a real provider)
=== 1. Chunk borders fall anywhere, including inside a character
text: "Café prices fell → 3 items 🙂 today." (36 UTF-16 units)
stream: 9 events, 338 bytes
cut into two chunks at each of 337 positions: streaming decoder right 337 times, wrong 0
same cuts, a fresh decode of every chunk on its own: 6 positions damage a character (U+FFFD)
chunks of [7] bytes: same text
chunks of [1] bytes: same text
chunks of [3,1,5] bytes: same text
=== 2. One reply, action by action
start -> streaming ""
delta -> streaming "The"
delta -> streaming "The order"
delta -> streaming "The order shipped"
delta -> streaming "The order shipped today."
done -> complete "The order shipped today."
=== 3. Frames: 40 deltas in one task, with and without batching
without batching: 40 state updates, 40 deltas, status complete
with batching: 1 state updates, 40 deltas, status complete
same final text: true
three bursts, a frame after each: 3 state updates, 6 deltas, text "a b c d e f", complete
=== 4. Five endings. The text received so far is kept in all of them
done event: complete, 3 deltas, text "One two three" (outcome done)
error event: failed, 3 deltas, text "One two three", error "The service is busy" (outcome error)
stream just ended: interrupted, 3 deltas, text "One two three" (outcome cut)
connection error: failed, 3 deltas, text "One two three", error "connection lost" (outcome failed)
Stop after 2 of 3: stopped, 2 deltas, text "One two" (outcome aborted, returned without waiting for another chunk)
=== 5. Events this client does not know are skipped, not fatal
complete, 2 deltas, text "Hello there"
skipped events: ["ping","usage","ping"]
a delta with no text: failed, 0 deltas, text "", error "malformed delta event"
=== 6. Finished blocks never change, so only the tail needs drawing
after 4 tokens: 0 finished blocks, tail "Here is the plan."
after 10 tokens: 2 finished blocks, tail "```ts\nconst" (inside an open code fence)
after 20 tokens: 3 finished blocks, tail "Then restart"
after 26 tokens: 3 finished blocks, tail "nd check the logs."
26 updates; finished blocks never changed once finished: true
characters drawn if every update redraws everything: 1677; if only the tail is redrawn: 505
What the lab does not show. No browser, no fetch, no real ReadableStream and no real provider: the byte source is a hand-driven async iterable, and "the next frame" is a manual scheduler. The tests render into jsdom, which does no layout, painting or timing, so nothing about how the reply looks or feels was seen. The fake tokens are pieces of a fixed string cut at whitespace, not tokenizer output, and the event names are invented. React Strict Mode and concurrent features were not tested.
Break it. In src/sse.ts, change this.#decoder.decode(bytes, { stream: true }) to this.#decoder.decode(bytes). Three tests fail (the cut-at-every-position test, the one-byte-per-chunk test and the chunk-size test of consume), because a character split by a chunk border now turns into replacement characters. Restore the option afterwards.
In practice: an assistant that froze on long answers
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A store's help panel streams its answers. In the first version, every piece updates a string in state, and the whole string is parsed as Markdown and drawn again on each update. Short answers feel fine. Long answers, such as a step-by-step guide with code, make the page sluggish on mid-range phones, and typing in the text box lags while a reply is coming in.
Starting architecture
Figure 4. Starting point: one state update per piece, everything redrawn
How to read this: the work per update grows with the length of the answer, and updates come as fast as the network delivers pieces.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Throttle the updates to a fixed interval | Fewer redraws | A timer that ignores frames; text may appear in jumps | Still redraws everything each time |
| Batch per frame | One update per frame at most | A scheduler | Held text in a hidden tab |
| Batch per frame and split finished blocks from the tail | Work per update stays small however long the answer grows | A splitter; a memoized block component | The splitter is not a full Markdown parser, so edge cases need tests |
The decision
| Field | Decision record |
|---|---|
| Context | Per-piece redraws of a long answer block the main thread on slower phones. |
| Decision | Batch deltas per frame, split the text into finished blocks and a tail, render each finished block once as a memoized component and redraw only the tail. Keep the six-status reducer and announce only the status line. |
| Consequences, good | Work per update depends on the tail, not on the whole answer; the endings and Stop keep working; the pieces are testable without a browser. |
| Consequences, bad | A splitter and its tests to maintain, and a rule for what the tail shows while a code fence is open. |
| Revisit when | The renderer needs lists, tables or footnotes that change earlier blocks, or measurements show the tail itself is too heavy. |
Rollout and verification
- Reproduce first: feed the page a scripted long stream and record a profile in a real browser, in CI or on a test device. The lab cannot show timing.
- Ship the batcher alone, compare responsiveness for a small group, then add the block split.
- Test the splitter with prefixes of real answers, and every ending with scripted streams.
The 2 a.m. failure
After the change, support reports that in one browser, answers sometimes stay blank for a long time and then appear all at once (illustrative). The tab was in the background when the answer started. The scheduler used requestAnimationFrame, which is paused in most browsers in background tabs, so deltas were held until the tab came forward.
First three checks: (1) reproduce by starting an answer and switching tabs; (2) check whether the scheduler is tied to frames; (3) check what stop and done do to held text. Mitigation: release held text on a timer when the page is hidden, or on visibilitychange, and flush when a terminal event arrives. Follow-up: add a hidden-tab case to the test suite and record how long text is held.
Architect's notes
- Make the decoder total. Same events for every possible cut, tested at every position.
- A terminal event is the only proof of completion. The end of the bytes is
interrupted. - Keep the text in every ending, and make Stop immediate and final. Abort, set the status yourself, ignore what arrives later.
- Batch to frames, redraw only what changed, and decide what a hidden tab does.
Common mistakes
- Decoding each chunk with a fresh
TextDecoder, which damages characters cut by a chunk border. - Splitting the text on newlines per chunk instead of holding an incomplete line.
- Marking a reply complete when the stream ends.
- Failing on an unknown event name, so a provider update breaks the page.
- Reporting a user's Stop as an error.
- Letting a late piece from an old reply reach a new one.
- Updating state for every piece, or announcing every piece to a screen reader.
Key takeaways
- A stream is bytes: chunk borders can fall inside an event and inside a character. Use one streaming decoder and hold incomplete lines.
- Layer the client: decode, consume, batch, reduce, draw. Everything but the last step is testable without React.
- A reply has six statuses; only
streamingaccepts text, and every ending keeps the text. - Complete means a terminal event arrived. Without one the reply is
interrupted; a thrown error isfailed, unless the user pressed Stop. - Cancel with an AbortController and race the abort against the next read if your source can wait.
- Once per frame, redraw only the tail, announce only the status.
- Real providers add event types over time: skip what you do not know.
Practice exercises
Exercise 1 — Starter (45 min): The lab's consume already returns the names of the events it skipped. Write a test with three ping events among the deltas that checks the text is unchanged and the list holds three ping entries.
Exercise 2 — Intermediate (2 hours): Add a scheduler that falls back to a timer when the page is hidden. Write a test that holds text, "hides" the page, and checks that the text is released once.
Exercise 3 — Advanced (half day): Extend splitBlocks so that a list item stays in the tail until the next blank line. Keep the prefix test that finished blocks never change, find one input where your rule fails, and say what the renderer should do.
Related reading
In this course:
- AI-Powered Frontend Architecture, where this work sits in the whole system.
- Server-Sent Events in Depth, the full parser rules and reconnection.
- Reconnection and Message Ordering, resuming a stream and keeping order.
- Real-Time Data in React State and Query Caches, subscribing a component to a stream without redrawing everything.
- Accessible Forms and Dynamic Content, live regions.