Srikanth Bandaru

GPU to pixel

Why a chat reply that streams smoothly on a laptop can arrive in production all at once, or with ��� where an emoji should be.

Contents4 sections
  1. Some hops hold the whole reply
  2. A token is not a character
  3. A chunk is not a message
  4. The browser counts in blocks and frames

The stream works on your laptop. In production the page shows nothing, then the whole answer. Or the text comes in bursts, or a � sits where an emoji should be. If one of these is yours, find it in the first column.

What you see Where it starts Fix
nothing, then everything gzip or body-hashing middleware flush after each event
text in bursts proxy buffer turn proxy buffering off
� that stays server decodes each token alone hold bytes until valid UTF-8
� only in production client decodes each chunk alone one TextDecoder, stream: true
an empty bubble parser misses CRLF accept CR, LF and CRLF
raw asterisks Markdown block still open parse per block
slower as it grows re-parse on every token append
stutter one page write per token one write per frame

Why so many different symptoms? Because a reply doesn’t go straight from the GPU to your screen. It goes through a chain of hops, and each hop has its own buffer and counts in its own unit (tokens, bytes, events or frames). So most streaming bugs happen at a handoff where one buffer waits to fill, or where the units on each side don’t line up.

Some hops hold the whole reply

Say you get nothing, and then the whole answer at once. The usual first fix is proxy_buffering off in nginx. Go ahead and try it in the figure.

Which hop is holding the reply?

Model of one reply, not a recorded trace

The chat bubble

A grey line is a token moving down. An orange line is a token being held. Change a setting, then press Play.

nginx proxy_buffering
gzip

Time runs left to right. Each token falls through 5 lanes, one per hop. The model sends 1 token every 0.15 s, and a full proxy buffer releases 6 at a time (both numbers are examples). gzip runs in the server lane and the nginx proxy in the wire lane.

Did the bubble change? No! The proxy now passes every token along right away, but gzip is still holding all of them. It collects a window of bytes before it writes, and this short reply never fills one.

And looking at the bubble, you can’t tell which hop is holding the stream. The figure can show you because it is a model. In production you have to count the bytes going into each hop and coming out of it.

Any hop can do what gzip did here. If it needs a full window or the whole body before it sends anything, your stream becomes a download. So turn compression off on streaming endpoints, or flush after each event.

Middleware can do this too. An ETag is a hash of the whole body, so middleware that adds one can’t send anything until the reply ends.

I have seen the extreme version of this at work. My team integrated an AI assistant that another team in the company built. When I reviewed the client library, I found it wasn’t streaming at all! The whole answer came back in one response, and then the page revealed it word by word.

I timed one generated page summary, and it took about a minute. So I asked that team for a feasibility assessment. They ran 24 requests outside production. The average was about 21 seconds for product pages and 24 seconds for articles, and the slowest request took close to a minute. But I never saw the final result of that assessment, so I don’t know how it ended.

Streaming would not have made that answer finish any sooner. But you would have been reading the first words while the rest was still on the way.

A token is not a character

Take 🦙. You see 1 character, but in UTF-8 it is 4 bytes. 👩‍💻 also looks like 1 character (that is called a grapheme), but it is 3 code points and 11 bytes. The model doesn’t work in characters at all. It produces token IDs, and the detokenizer turns those back into bytes. Many tokenizers split along bytes, so one emoji can be spread over several tokens.

So what happens when you decode a token that holds only half of the llama? The decoder prints �, the replacement character, for any bytes that don’t form a character. Move the cut in the figure and count the � you get.

What does a decoder print when a character is cut in two?

Runs in your browser

Drag the cut, use the arrows, or tap any byte.

0

A new decoder for each chunk

One decoder, after chunk 1

One decoder, after chunk 2

Each column is one grapheme. The cut stands for any boundary that splits bytes, such as a token boundary on the server or a network chunk on the client. The bytes before the cut are chunk 1 and the rest are chunk 2. One decoder means one TextDecoder called with stream: true.

The count even tells you where the cut fell. Cut 🦙 after its first byte and you get 4 (1 for the first byte alone and 3 for the bytes left behind). After the second byte you get 3, and after the third you get 2.

A server that decodes each token alone sends that � to every user, and nothing on the client can repair it, because the original bytes are gone. The fix is to hold tokens back until their bytes form valid UTF-8, as Hugging Face’s DecodeStream does.

A chunk is not a message

Even a server that sends only whole characters, as hosted APIs do, can’t stop the network from cutting the bytes again. In the browser a response body arrives as chunks, and a chunk is whatever bytes one read happens to return. Locally, one write usually arrives as one chunk, so a broken parser passes every local test, and the � shows up only in production.

Most of the trouble comes from 2 client bugs. The first is creating a new TextDecoder for each chunk, which turns a split character into �. LangChain.js’s Vertex adapter shipped this bug in 2024. The second is line endings. Server-sent events let a line end in CR, LF or CRLF, and a parser that splits on "\n\n" never matches a CRLF stream, so nothing renders.

Here is a parser that handles both. It keeps one decoder per stream and accepts all 3 line endings. It passes a test with 🦙, 👩‍💻 and 。 in CRLF lines, cut into chunks of every size.

async function* sseData(body) {
  // one decoder per stream
  const decoder = new TextDecoder();
  let buf = "", data = [];
  for await (const chunk of body) {
    // stream: true keeps a split
    // character for the next chunk
    buf += decoder.decode(chunk, { stream: true });
    let m;
    // CR, LF, CRLF all end a line
    while ((m = /\r\n|\r|\n/.exec(buf))) {
      // a final CR may be
      // half of a CRLF
      const atEnd = m.index === buf.length - 1;
      if (m[0] === "\r" && atEnd) break;
      const line = buf.slice(0, m.index);
      buf = buf.slice(m.index + m[0].length);
      if (line === "") {
        if (data.length) yield data.join("\n");
        data = [];
      } else if (line.startsWith("data:")) {
        data.push(line.slice(5).replace(/^ /, ""));
      }
    }
  }
  // the stream ended on a held CR
  if (buf === "\r" && data.length) yield data.join("\n");
}

The browser counts in blocks and frames

Now every character reaches the page whole. But there is still one more place where it can go wrong. Markdown works in blocks (a paragraph, a table, a list). While a reply streams, the last block is still open and can change type (a line that looks like a paragraph becomes a table when its second row arrives). Inside it, **Menu shows up as raw asterisks until the closing pair arrives.

Chrome’s guide to streamed replies says to append new text, not re-parse the whole message on every token. Re-parsing makes the work grow with the square of the reply’s length.

The other thing to watch is how often you write to the page. The screen redraws about 60 times a second (every 16.7 ms), so there is no point writing more often than that. Collect the tokens that arrive between two redraws and add them in one write.

There is one buffer you add on purpose. Vercel’s AI SDK ships smoothStream, which holds text briefly so it comes out at an even pace. It is a jitter buffer, like the one a video player uses when packets arrive unevenly. It adds a little delay, but it is worth it, because text that lands in bursts is harder to read.

The word-by-word reveal in the assistant I reviewed paced the text the same way, but only after the whole answer had arrived. So the text came out smooth, but you still waited the whole time for the first word.

If I could add only one test to a streaming endpoint, it would go through the production proxy. Send emoji and CRLF line endings, cut at random byte offsets, and time how long the first word takes to reach the client.