Skip to content
mentoor

Streaming UI for an LLM feature

For engineers

Scenario lesson and practice set combining LLM features in the frontend, streaming responses, designing for AI latency, user control and AI error states. Completing it counts as evidence for every listed skill.

The one-sentence idea: a streamed AI answer feels fast only when the whole path works together: the server sends clean events, the proxy lets them through, the page renders them without jumping, the user can stop or edit, and every failure says what happened and what to do next.

The case

Harbor Help is a support assistant inside a billing web app. A customer types "How do I get my money back for a duplicate charge?" and the answer streams into a panel. The team built it in a week: a Node server calls a model API (Claude, ChatGPT and Gemini all offer streaming), forwards the tokens to a React page, and the page appends them to the screen.

In the demo it worked. In production four things broke. The answer arrived all at once behind the company proxy. Code blocks showed raw backticks and then jumped. A Stop button hid the text but the provider kept generating. And when the connection dropped, the user saw "Something went wrong".

Why it matters

A model call can take ten seconds or more. Streaming does not make the model faster. It moves the first useful word to about a second, and Nielsen Norman Group's response-time limits explain why that matters: about one second keeps the user's flow of thought, ten seconds is the limit of attention. But streaming also makes partial, wrong and failed output visible, so the interface now has to deal with states a request-and-response page never had.

How to do it

  1. Send and read the stream correctly. Server-sent events are plain text: a data: line and a blank line per event. Append each delta in order and keep its spaces. Tool-call arguments arrive as JSON fragments, so join them and parse once at the end. Errors can come after the HTTP status 200, so watch for error events and for a stream that ends without its stop event.
  2. Let the bytes through. Reverse proxies such as nginx buffer responses by default and compression waits for full blocks. Turn buffering and compression off for the stream route, and test behind the real proxy, not only on your laptop.
  3. Render without jumping. Re-render the accumulated text with a markdown parser that accepts unfinished blocks. Reserve space for the answer, and decide per output whether to stream, validate first or wait: a draft reply can stream, a refund amount or form-filling JSON should not.
  4. Give the user the steering wheel. Stop must abort the browser request and the provider call. Keep the partial text, mark it as stopped and offer Continue and Regenerate. Keep earlier versions and the user's own edits when regenerating, and put a confirmation with the exact effect in front of actions that are hard to undo.
  5. Make waiting honest. Use real step labels instead of a timer-driven bar. Quote the median and the slow tail from measurements, never the best run. Jobs of minutes run in the background and tell the user when they finish.
  6. Make failures specific. Map each failure to a message, a recovery path and a reference id, keep the user's input, and offer a non-AI fallback. The failures nobody can detect, such as a fluent wrong fact, need a source next to the answer and a report button.

Before and after

Before: the handler writes each delta with res.write(delta), the page does setText(text + delta), Stop calls controller.abort() in the browser only, and every error shows "Something went wrong".

After: the server writes data: ... events and ends them with a blank line, the page uses setText(prev => prev + delta), the server aborts the provider call when the response closes, and an error reads "The answer stopped because the connection dropped. Your question is saved. Retry, or copy it. Ref H-4821".

What goes wrong

  • Fixing it only in the demo. Buffering, timeouts and compression appear only behind real infrastructure, so the stream looks fine until release.
  • Trusting the status code. A stream that began with 200 can still fail. A client that checks only the status shows a half answer as if it were complete.
  • Treating AI output as safe to show early. Streamed text can be wrong, and a number shown in part can be read as final. Validate what can cause harm before it is displayed.
  • Retries that duplicate. A retry that appends to the earlier partial text produces the same sentence twice. Reset the buffer first.
  • Assistant-written code that looks right. Coding assistants happily produce handlers with stale state or no event framing, and a Stop that only closes the browser side. Read their output as you would a pull request from a stranger.

Steps

  1. Send a correct event stream

    Skill: api-streaming

    Write each delta as an event: a data: line and a blank line. Set Content-Type: text/event-stream, flush the headers, and end the stream with a stop event so the client can tell success from a cut connection.

    SSE event framing
    res.setHeader('Content-Type', 'text/event-stream');res.setHeader('Cache-Control', 'no-cache');res.flushHeaders();for await (const delta of answerStream(q)) {  res.write(`data: ${JSON.stringify(delta)}\n\n`);}res.write('event: done\ndata: {}\n\n');res.end();
  2. Test behind the real proxy

    Skill: api-streaming

    Run the stream through the same nginx or load balancer as production. If the answer arrives in one piece, disable proxy buffering and compression for the stream route, and send an X-Accel-Buffering: no header from the app.

  3. Render the answer without flicker

    Skill: api-frontend-ux

    Append deltas with a functional state update, re-render the accumulated markdown with a parser that accepts unfinished blocks, and reserve space so controls below the answer do not jump.

  4. Choose what to stream and what to hold

    Skill: aiux-latency

    Prose can stream. Numbers that drive a decision and JSON that fills a form are validated first. Replace a fake progress bar with real step labels, and quote the median and slow-tail times in any time hint.

    Stream or wait
    OutputDecision
    How-to answerStream
    Draft replyStream into an editable box
    Refund amountWait, validate, then show
    Form-fill JSONWait, validate against schema
  5. Give the user control

    Skill: aiux-control

    Stop aborts the browser request and the provider call. Keep the partial text and label it as stopped. Regenerate keeps the earlier version and the user's edits. Actions that move money or send messages show their exact effect and ask first.

  6. Design the failures

    Skill: aiux-errors

    For each failure write what failed, what to do next and a reference id, keep the user's input, and offer a non-AI path. Add a source next to answers and a report button for wrong facts that no system check can detect.

    Failure map
    FailureMessage and recovery
    Rate limitBusy; question saved; retry after the wait
    Provider outageFallback to help-center search
    TimeoutQuestion saved; Retry and search
    Stream cutShow the partial text as incomplete; Retry

Skills this scenario uses

Where to study