BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
← All field notes

AI

Streaming AI Responses Without Breaking the User Experience

Design AI streaming around useful first output, stable rendering, reliable recovery, and a final state users can trust.

A response forms one line at a time beside a square stop button.

Streaming AI Responses Without Breaking the User Experience

Estimated reading time: 8 minutes

Read the Arabic edition: بث ردود الذكاء الاصطناعي دون الإخلال بتجربة المستخدم

Streaming can make a conversation feel prompt, but the first bytes are not the first useful answer. A heartbeat, a loading hint and half a Markdown heading can all arrive early without helping the reader. Worse, if a connection closes and the interface calls an unfinished answer complete, fast delivery has made the product less trustworthy. The goal is to show useful progress early while keeping the message readable, recoverable and honest about its state.

Treat this as a contract between production, delivery and presentation. The server decides what a run has produced and whether it is final. The transport delivers framed events, sometimes more than once after reconnect. The browser builds a display from those events. None of those responsibilities is quite the same as the others, and bugs emerge when one layer guesses what another layer knows.

Measure the first useful thing, not merely the first byte

A request can be accepted before a worker begins. A worker can start before it retrieves supporting material. A gateway can emit headers and heartbeats while buffering the first visible paragraph. Instrument distinct milestones: request start, first server progress, first response bytes, first useful content painted, and terminal outcome. One metric cannot tell you where a perceived delay occurs. If message rendering is expensive or a proxy buffers early chunks, a fast model timestamp and a slow first paint can both be true.

Choose usefulness for the product. In a documentation assistant, the first useful content might be a short answer grounded in the right version of a manual. In an analysis interface, it might be the first validated finding or an explicit clarification request. Do not start with filler that happens to be easy to generate. A concise progress message can help during a genuine wait, but it should not be counted as answer content or reveal private steps, source passages or speculative tool activity. Test the real deployment path with incremental writes, because a local connection does not reproduce every intermediary.

Frame the stream at the application layer

HTTP transport chunks are not application messages. One read may contain half of a multi-byte Arabic character, part of a JSON event, or several events at once. Incremental UTF-8 decoding must preserve unfinished characters between reads. Then a framing parser separates messages. For example, an SSE parser observes event boundaries in the text, not the boundary of each read; a line-delimited JSON parser retains the incomplete last line until the rest arrives. Validate a complete frame before applying it to the UI. A malformed frame should not become arbitrary markup or a false completion signal.

Native browser EventSource handles decoding, framing and its own reconnect behavior for a GET event stream. A reconnecting EventSource may send the last event ID when the server provided event IDs. That is a cursor hint, not a guarantee of application replay. If you initiate generation with a POST and consume its response through Fetch, you have more control over the request but must supply the relevant parsing and recovery logic yourself. Another option is a POST to create a run followed by an authenticated GET stream for that known run. Choose based on how you start, authorize and recover a run, not on which demo has fewer lines.

Application event Minimum meaning
accepted A run ID exists; no answer is promised yet
progress A short, non-content milestone suitable for the user
delta Content for this run with a stable sequence number
completed The identified canonical answer is finalized
failed or cancelled No more final-answer deltas are expected for this run

Include the run ID on every event and sequence state changes consistently. Keep an ordered last-applied cursor per run. Ignore an event already applied, but treat a gap as a reason to reconcile rather than silently appending out of order. Terminal events should have a defined schema and remain recoverable after reconnect. End of file by itself means the connection ended; it cannot tell the browser whether the worker succeeded, crashed or was cut off by a network change.

flowchart TD
    A["Start or look up a run"] --> B["Worker emits ordered application events"]
    B --> C["Transport frames, buffers and delivers"]
    C --> D["Browser decodes, validates and applies by run and sequence"]
    D --> E["Render stable content and selected status changes"]
    D --> F["Gap or lost connection: recover the same run"]
    F --> A
    B --> G["Persist final answer or terminal failure"]
    G --> F

The main branch shows the live result. The recovery branch goes back to the same run and uses its durable state, not a second implicit generation. The final state is not a property of the socket. It is an application decision that can be observed through the socket or recovered separately.

Worked example 1: a fragmented Arabic answer and a missing final frame

A fictional equipment assistant is answering an Arabic question about a manual. The worker emits events for run R-21. The connection splits one Arabic character across two chunks and delivers the following event in the same read as the end of the first. A browser that runs JSON.parse on each read fails on valid input. A browser that decodes each chunk in isolation can display replacement characters even when the network delivered all bytes. With incremental decoding and framing, it reconstructs the original text and applies each event once.

At sequence 11 the phone changes networks. The server continues and has already persisted the finalized answer by the time the browser reconnects. The client asks for R-21 after its last applied sequence, rather than sending the original prompt again. If replay is available, the server replays the gap and the final event, and any repeated sequence is ignored. If the replay retention window has expired, a status endpoint returns a canonical final snapshot for R-21, which replaces the provisional display. That fallback is especially important when generated content can have downstream cost or when rerunning might produce a different answer. If extended recovery is not available, show the preserved partial response and label it incomplete; let the user intentionally start a new run.

The acceptance test should split bytes at several positions, include two frames in one read, lose a connection immediately before completion, and verify that the UI reconciles to one final answer with one run ID. It should also exercise the expired-cursor path. A user who refreshes after losing connectivity should never see the interface silently declare success based on text that only happened to be visible before the loss.

Worked example 2: a stop request races with completion

A fictional report assistant is generating R-37. The user presses Stop just as the worker persists its final answer. Consider what each control can promise. Aborting Fetch or closing EventSource stops that browser’s reading; it does not, by itself, prove remote work stopped. If Stop is intended to stop the server too, send an explicit cancel request for R-37 and give the server a single authoritative transition. Cancellation can be requested while the state is running; a committed completed state should not be silently relabeled cancelled. The browser may first show “Stopping…”, then reconcile to “Stopped” or “Completed before stopping” according to the server’s result.

If cancellation wins, preserve any already displayed text as partial when that fits the workflow, but do not style it as the final answer or attach citations that were never validated. If completion wins and the user has since started R-38, a late event for R-37 must not append text to the newer run. Keep view identity and current run identity explicit. Repeated cancel requests should be safe to handle and return the known state. If the server cannot confirm cancellation, do not claim that it did. Test both outcomes with controlled delays plus a refresh during the “Stopping…” state. Verify cancellation time in the worker separately from the point at which the UI stops appending.

Render for reading, not for the transport

A model token is a generation detail, not a rendering instruction. Coalesce UI updates on a bounded cadence and render stable blocks where possible. An unfinished code fence, table or link should not cause the entire conversation to reflow on every fragment. Keep a plain-text provisional rendering for unstable blocks when needed, then render the finalized Markdown with the same safe pipeline used for nonstreaming answers. Validate citations before displaying them as trusted links. Do not continuously reparse a growing answer if it causes noticeable input lag, and cap buffers for slow consumers so a blocked connection cannot keep collecting unbounded text.

Preserve the reader’s place. Auto-scroll while the reader is already near the bottom, not while they are reviewing an earlier paragraph; offer a jump-to-latest control. Keep focus on the active control rather than moving it every time a new line arrives. Do not put every changing fragment in an assertive live region. A persistent, separate status region can convey a few meaningful transitions such as “Generating,” “Connection lost, reconnecting,” and “Answer ready.” WAI-ARIA defines status with polite live-region semantics. Put the answer itself in a normally navigable reading area and test with keyboard and assistive technology in both languages; the role alone is not proof of a comfortable experience.

Maintain evidence through successful, partial and failed runs

Use an explicit state model in the UI: waiting, streaming, reconnecting, completed, cancelled and failed. Keep the last useful text on recoverable errors, tell the user what happened, and offer the appropriate choice: resume this run, start a new answer, or stop. Separate transport-level errors from content failures and from policy or validation failures. Persist the final answer before announcing completion if your product promises a recoverable answer. If persistence fails, present that as a failure even if draft text was displayed.

Track time to first useful paint, finalization latency, reconnect and recovery rates, duplicate-event suppression, partial-response rate, and the time from cancellation request to confirmed worker stop. Segment by client, network and path where possible. An interval from browser send to browser paint should use the browser’s own clock; cross-service timing needs correlated spans, not arithmetic on unaligned clocks. Avoid logging prompt or answer bodies by default; event types, counts, timing and anonymous correlation data are usually sufficient for this purpose. Test a slow consumer, a buffered proxy, an incomplete frame, a missing final event and a cancellation race before calling the design dependable.

Streaming helps when it makes long work easier to follow without asking the user to interpret the network. A responsive first answer, stable text, recoverable progress and a credible ending are what the experience should optimize for.

Primary references

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.