FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Streaming Markdown Parsing: Stable Prefixes

Stream Markdown without reflow by preserving parser state, delaying ambiguous tails, and committing only fragments whose syntax boundaries are stable.

Freshness: current•14 min read•AI User Experience and Human-AI Interaction
Full Technical Reference Document

Mental model

Streaming Markdown is a consistency problem between append-only text deltas and syntax whose meaning can depend on later input. Preserve raw source and parser state, keep an undecided tail, and expose provisional output as provisional. At completion, parse the full document and reconcile it; early rendering is a preview, never the canonical document.

Theory

Markdown is not a sequence of independent characters that can always be turned into final HTML as they arrive. A backtick can start a code span or fence that closes much later. A list item can continue across indented lines. A link label may remain unresolved until a reference definition appears elsewhere in the document. Micromark exposes a stream interface for consuming bytes, but its documentation also explains that reference definitions make a fully streaming interpretation impossible in the general case. A streaming UI therefore needs an explicit policy for uncertain syntax instead of assuming that network chunk boundaries are Markdown boundaries.

Maintain three distinct values: the accumulated source, parser state for open constructs, and the rendered projection. On each delta, append the bytes exactly as received. A parser that exposes incremental tokens can publish nodes it declares stable and retain the unresolved tail. If the chosen parser does not expose that state, parse a coalesced prefix for a clearly provisional preview, then run a complete parse at finish. The final full parse is the source of truth, especially for reference links, tables, and any renderer that replaces the current DOM.

There is a measurable cost to reparsing every growing prefix. Let nkn_k be the accumulated source length in bytes after update kk, and mm the number of updates. Re-reading every prefix costs Wreparse=∑k=1mnkW_{\text{reparse}}=\sum_{k=1}^{m}n_k; a one-pass parser reads roughly Wpass=nmW_{\text{pass}}=n_m bytes, plus its grammar-specific state updates. With a 48 KiB answer delivered in 48 chunks of 1 KiB, full-prefix parsing reads S48=1+2+⋯+48=1,176S_{48}=1+2+\cdots+48=1{,}176 KiB, or 24.5 times the final source size. This is parser input work only; DOM construction, sanitization, and layout add separate costs.

Receive ordered text deltas
Append raw source to the carry buffer
Track open blocks and unresolved references
Publish only a provisional or stable projection
Reparse and reconcile the complete document at finish
Conceptual teaching model synthesized from:micromark-commonmark-parser,vercel-ai-sdk-ui-stream-protocol

A coalesced preview

When an incremental AST is unavailable, coalesce deltas to one render per animation frame instead of running a full parser for every network event. This example produces a sanitized preview from the current prefix and marks the host busy until the complete response is reparsed. Partial emphasis or a link may change appearance as new text arrives; consumers should not treat that preview as final content.

typescript
import { micromark } from "micromark";
import DOMPurify from "dompurify";
​
export class MarkdownPreview {
private source = "";
private frame = 0;
​
constructor(private readonly host: HTMLElement) {
host.setAttribute("aria-busy", "true");
}
​
append(delta: string): void {
this.source += delta;
if (this.frame !== 0) return;
this.frame = requestAnimationFrame(() => this.renderPreview());
}
​
finish(): void {
if (this.frame !== 0) cancelAnimationFrame(this.frame);
this.frame = 0;
this.host.innerHTML = DOMPurify.sanitize(micromark(this.source));
this.host.setAttribute("aria-busy", "false");
}
​
private renderPreview(): void {
this.frame = 0;
this.host.innerHTML = DOMPurify.sanitize(micromark(this.source));
}
}

This full-prefix example is intentionally simple, not an incremental parser. For large responses, keep a stable rendered prefix and reparse only the tail if the parser exposes enough state to prove that the prefix cannot be changed by later definitions. Otherwise, leave ambiguous constructs as plain text or defer rich rendering until the closing delimiter or end marker arrives. When an abort occurs, cancel the scheduled frame and make the partial response state explicit; do not silently relabel an incomplete code fence as complete.

Failure modes and misconceptions

FailureWhy it happensSafer behavior
A fenced block closes only after several deltasThe opening delimiter changes the grammar of every later line until a matching fencePreserve the open-fence state and do not commit its contents as ordinary paragraphs
A reference-style link changes after earlier text was renderedA definition later in the document can resolve an earlier labelReconcile the full document at completion or keep such links provisional
A parser runs once per tiny tokenGrowing prefixes repeat work and may exceed the generation rateCoalesce to a frame or use a genuinely incremental parser interface
Raw HTML from model output reaches innerHTMLMarkdown parsing does not itself authorize untrusted HTMLSanitize the produced HTML and apply the application’s link policy
Replacing the entire preview jumps the pageFull DOM replacement changes element heights and scroll anchoringPreserve keyed block nodes and apply an explicit scroll-follow policy

A line break can be useful as a display hint, but it is not proof that Markdown meaning is settled. GFM tables, indented lists, block quotes, and reference definitions can all depend on material outside the latest line. Use the parser’s grammar, not a collection of ad hoc string checks, to decide what can be committed. For accessible output, keep document order stable and avoid announcing every provisional reparse through a live region; pair the stream with a concise status message instead.

Trade-offs

Parsing the full prefix keeps implementation small and works well for short answers, but the cost grows with both response length and update count. A stable-prefix renderer reduces repeated parsing and layout changes, but it must track open constructs correctly and still handle references that can resolve later. Plain-text streaming is the most robust fallback when a parser cannot expose enough state. Rich formatting can be applied at finish, or to a bounded tail after a server sends explicit block boundaries.

The text stream protocol supplies deltas; it does not specify how Markdown should be rendered. Keep transport framing, Markdown parsing, HTML sanitization, and UI reconciliation as separate steps. That separation lets a team switch from a full-prefix preview to an incremental parser without changing how it validates stream ordering or how it treats the final response.

Decision scenario

A response contains a reference link near its first paragraph, while its reference definition is emitted at the very end. The current preview initially shows the label as plain text and the team wants a stable interface on long answers. Keep the early content provisional or plain text, then parse and reconcile the whole response at the finish marker. Do not permanently commit an unresolved reference as a dead link just because its closing definition has not arrived yet.

Learning outcomes

  • Explain why a Markdown parser that accepts input chunks may still need document-wide context to resolve references.
  • Estimate repeated parser input when a renderer reparses every prefix.
  • Choose between provisional previews, stable parser events, and final-only rich rendering based on latency and grammar requirements.
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-501AI Evaluation and Reliability

Turn product intent and risk into representative evaluations release gates traces service targets and continuously improving regression evidence.

17 concepts~22h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next