Dev.to AI 🤖 Ai 👁 0 📖 7 min read

TextDecoder Without stream: true Broke 212 of 3,000 LLM Streams

A user sent me a screenshot of a Japanese answer from my chat app. Halfway through a sentence sat three black diamonds with question marks in them. ���. The model had not written them. My frontend had. The bug was one m

A user sent me a screenshot of a Japanese answer from my chat app. Halfway through a sentence sat three black diamonds with question marks in them. ���. The model had not written them. My frontend had.

The bug was one missing option: I called TextDecoder.decode() on every chunk of the LLM stream without { stream: true }. When I replayed 3,000 recorded completions through my staging proxy, 212 of them came out corrupted. On localhost the same code corrupted zero. That gap is why I shipped it.

TL;DR

  • new TextDecoder().decode(chunk) per network chunk assumes every chunk ends on a character boundary. Network chunks are cut at arbitrary byte offsets, so a multi-byte UTF-8 character can be split in half.
  • Without { stream: true }, the decoder replaces the half character with U+FFFD (�). One split character turns into 2 to 4 replacement characters.
  • In my replay test: 0 of 1,000 English streams broke, 141 of 1,000 Japanese, 71 of 1,000 emoji-heavy. Total 212 of 3,000. After the fix: 0.
  • Fix: create one decoder outside the loop, call decode(value, { stream: true }), flush at the end. Or pipe the body through TextDecoderStream.
  • The same chunk-boundary problem also breaks naive SSE line splitting. That silently dropped deltas in 23 more streams.

Why does TextDecoder produce U+FFFD in streamed LLM responses?

TextDecoder produces U+FFFD when the bytes it receives end in the middle of a multi-byte UTF-8 character and you have not told it more bytes are coming. Without stream: true, every decode() call is treated as the complete input. An incomplete sequence at the end is invalid, so it gets replaced.

Here is the code I had. It looks like every streaming tutorial you've skimmed:

const reader = res.body.getReader();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const text = new TextDecoder().decode(value); // bug #1
  for (const line of text.split("\n")) {        // bug #2
    if (!line.startsWith("data: ")) continue;
    try {
      const evt = JSON.parse(line.slice(6));
      onDelta(evt.delta?.text ?? "");
    } catch {}                                  // bug #2's accomplice
  }
}

reader.read() hands you a Uint8Array of whatever bytes arrived. Not tokens, not events, not characters. Bytes. The server writes nice SSE events, but TCP, TLS records, proxies and the browser's own buffering are all free to cut that byte stream wherever they like.

ASCII never notices, because every ASCII character is one byte. You cannot cut a one-byte character in half. That's why my English test set came back clean and I felt great about it.

How many replacement characters does one split character create?

One split character creates 2 to 4 U+FFFD characters, depending on where the cut lands. The tail of chunk A becomes one � for the incomplete prefix. The head of chunk B is a run of continuation bytes with no lead byte, and each one becomes its own �.

Character UTF-8 bytes Cut � from chunk A � from chunk B Total
日 E6 97 A5 `E6 \ 97 A5` 1 2
日 E6 97 A5 `E6 97 \ A5` 1 1
🔥 F0 9F 94 A5 `F0 \ 9F 94 A5` 1 3
🔥 F0 9F 94 A5 `F0 9F \ 94 A5` 1 2
🔥 F0 9F 94 A5 `F0 9F 94 \ A5` 1 1

That matches the screenshot exactly: one kanji, cut after its first byte, became three diamonds. The character is gone for good. You can't reassemble it from the replacement characters because the original bytes were thrown away.

How I measured it: 3,000 replayed streams

I didn't want to measure against live model output, because two runs never produce the same text and I'd have nothing to diff against. So I recorded 3,000 completions once, as raw SSE byte streams, and built a tiny replay server that sends them back byte-for-byte.

The test sets:

  • 1,000 English answers (plain prose and code)
  • 1,000 Japanese answers
  • 1,000 English answers from a prompt that asked for emoji in every list item

Each replay went through two paths: straight to localhost, and through my staging reverse proxy over TLS, which is the same path production traffic takes. The client ran in headless Chromium with the old code and the fixed code. A stream counted as broken if its final text did not exactly equal the recorded reference.

const broken = output !== reference;
const diamonds = (output.match(/�/g) || []).length;

Results: which streams broke?

Set Streams Localhost, naive Proxy, naive Proxy, fixed
English 1,000 0 0 0
Japanese 1,000 0 141 0
Emoji-heavy 1,000 0 71 0
Total 3,000 0 212 0

Across the 212 broken streams there were 307 destroyed characters and 781 U+FFFD characters. Most broken streams had exactly one bad spot, which is the worst possible failure mode for getting noticed. One glitch in a long answer looks like a font problem, so nobody files a ticket. One user did, and I owe them a coffee.

Japanese broke twice as often as emoji. That makes sense once you look at the bytes: nearly every byte of Japanese text sits inside a 3-byte character, so almost any arbitrary cut lands mid-character. In the emoji set, most bytes are still ASCII, and a cut only hurts if it lands inside one of the emoji.

Why did it work on localhost?

It worked on localhost because nothing re-cut the bytes. I logged chunk boundaries on both paths. On localhost, each reader.read() returned exactly one SSE event, because the server flushed per event and nothing in between merged or split the writes. Every chunk ended on \n\n, which is always a character boundary.

Through the proxy, reads came back at arbitrary byte offsets. Sometimes two events glued together, sometimes an event sliced in the middle of a JSON string, sometimes in the middle of 日.

This is the part I'd tattoo on a junior dev: chunk boundaries are a property of the transport, not of your server. Your dev setup is the one environment where they happen to look tidy.

How do you fix TextDecoder for streaming?

Create one TextDecoder for the whole stream and pass { stream: true } on every call. In streaming mode the decoder holds an incomplete trailing sequence in an internal buffer and prepends it to the next chunk. A final call without stream: true flushes whatever is left.

const decoder = new TextDecoder("utf-8");
const reader = res.body.getReader();
let buf = "";

while (true) {
  const { done, value } = await reader.read();
  buf += decoder.decode(value, { stream: !done }); // value is undefined when done: that call flushes

  const lines = buf.split("\n");
  buf = done ? "" : lines.pop(); // keep the partial last line for the next round

  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const payload = line.slice(6);
    if (payload === "[DONE]") continue;
    const evt = JSON.parse(payload); // no silent catch: let it throw
    onDelta(evt.delta?.text ?? "");
  }
  if (done) break;
}

Three things changed. The decoder moved out of the loop. stream: true went in. The partial last line now waits for the next chunk instead of being parsed half-finished.

If you don't need manual control, let the platform do it:

const textStream = res.body.pipeThrough(new TextDecoderStream());

TextDecoderStream keeps the decoder state across chunks for you. You still need the line buffer, though, because a decoded string can still end in the middle of an SSE line.

What was the second bug hiding behind the first?

The second bug was naive line splitting plus an empty catch {}. When a chunk ended in the middle of a data: {...} line, JSON.parse threw on the first half, the catch swallowed it, and the second half didn't start with data:, so it was skipped too. The whole delta vanished.

This one hits English just as hard, because it doesn't care about encoding. In the proxy run, 23 of 3,000 streams silently lost at least one delta: words missing from the middle of an answer, no error, no diamond, nothing. That's worse than the U+FFFD bug. Diamonds at least look broken.

The empty catch was there because "sometimes the stream has a weird line". It did. Every one of those weird lines was half of a real event.

Does Python have the same problem?

Yes, if you decode bytes chunk by chunk yourself. chunk.decode("utf-8") on a split character raises UnicodeDecodeError, or quietly inserts � if you passed errors="replace" to make the exception go away. The fix is the same idea, an incremental decoder:

import codecs

decoder = codecs.getincrementaldecoder("utf-8")()
for chunk in response.iter_bytes():
    text = decoder.decode(chunk)       # holds partial sequences
    ...
text_tail = decoder.decode(b"", final=True)

Higher-level helpers that hand you text (like iter_text() in httpx) already use an incremental decoder internally. The bug shows up when you drop to raw bytes "for performance" and decode them yourself.

What I check in every streaming client now

  1. One decoder per stream, created before the loop.
  2. { stream: true } on every chunk, and a final flush.
  3. A line buffer that carries the partial last line forward.
  4. No empty catch around JSON.parse. Log it, count it, or throw.
  5. A test that replays a non-ASCII stream through something that cuts bytes at random offsets. A 10-line fake server that writes in random 1 to 17 byte slices would have caught both bugs on day one.

Total cost of this bug: one day of me blaming the font stack, one day building the replay harness, and a fix that added three lines.

The short answer

TextDecoder without stream: true breaks LLM streams because network chunks split multi-byte UTF-8 characters, and a non-streaming decode replaces each half-character with U+FFFD. In my replay of 3,000 recorded completions through a real proxy, that corrupted 212 streams (141 Japanese, 71 emoji-heavy, 0 English), while localhost showed 0 failures. Use a single TextDecoder per stream with decode(value, { stream: true }) and a final flush, or TextDecoderStream, and buffer partial SSE lines so JSON.parse never sees half an event.

Written by the developer behind Preterview, an interview prep platform.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.