The annoying bug where your chat widget renders half a markdown code block during SSE streaming
Anyone who has built a streaming AI chat UI has run into this at some point. Everything looks great in local testing, and then in production:
- The model outputs an opening
```pythonfence, and for the next 4 seconds the syntax highlighter flashes between plain text and broken DOM nodes on every incoming token. - On a shaky mobile connection,
EventSourcereconnects mid-response and either loses the last 20 tokens or replays from the start because there wasn't a stream cursor.
Keep markdown stable while tokens arrive
Re-parsing the entire message string from character 0 on every token gets noticeably laggy once a response passes 300 lines. Two simple habits fixed both the flicker and CPU spikes for us:
- Split completed blocks from the active tail: Once a paragraph or fenced code block has a closing
\n\nor closing```, memoize it so React never re-parses finished blocks. - Auto-close dangling fences in a tiny pre-pass before handing the active tail to your markdown renderer so half-streamed code stays inside a
<pre>box instead of spilling into prose.
tsexport function closeOpenCodeFence(partial: string): string { const fenceMatches = partial.match(/```/g); if (fenceMatches && fenceMatches.length % 2 === 1) { return partial + "\n```"; } return partial; }
For reconnects, push each SSE chunk into a short-lived Redis stream (XADD) with a monotonic event id: so Last-Event-ID lets the client pick up right where the socket dropped.