A TCP Chunk Can Split One UTF-8 Character: Buffer the Bytes Before You Decode
LLM streaming endpoints emit UTF-8 text chunks over HTTP/2 or Server-Sent Events (SSE). Because TCP packet boundaries operate independently of UTF-8 character encoding, multi-byte sequences (such as emojis or complex punctuation) can tear cleanly across chunk boundaries.
Decoding each chunk on its own with chunk.toString() does not throw. It silently turns the torn bytes into U+FFFD replacement characters, so the corruption reaches your logs and your users. Use Node.js string_decoder.StringDecoder('utf8') or a stateful byte buffer to hold incomplete multi-byte sequences until the trailing bytes arrive.
Decoding is not framing. A clean decoded chunk can still end halfway through a JSON object, so JSON.parse() on a chunk throws SyntaxError. Split the decoded text on newlines or SSE event boundaries first, and parse only complete lines.
import { StringDecoder } from "node:string_decoder";
export async function* decodeSafeStream(rawByteStream) {
const decoder = new StringDecoder("utf8");
for await (const chunk of rawByteStream) {
// StringDecoder preserves trailing partial UTF-8 bytes across iterations
const safeText = decoder.write(chunk);
if (safeText) yield safeText;
}
const finalChunk = decoder.end();
if (finalChunk) yield finalChunk;
}
Get the next essay by email
One email per new essay: a production failure, taken apart, and the code that fixed it. Reply to any of them to unsubscribe.