Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FoundationsAI guideIntermediate#foundations#streaming#ux#sse
Frame · ai-engineering / foundations / 12-streaming-and-ux-patterns.mdGuide 012 / 103

Streaming and UX patterns for LLM apps

A model that takes eight seconds to answer feels broken if the screen is blank for eight seconds, and feels fine if words start appearing after half a second. Streaming is how you get there: the provider sends tokens as they are generated and your UI renders them incrementally. It sounds like a transport detail, but it shapes your API design, error handling, tool use and how much users trust the product.

Why it matters

Perceived latency is dominated by time to first token, not total time. Streaming lets users start reading, lets them cancel a response going the wrong way (saving you output tokens), and makes long reasoning or tool-using turns legible instead of mysterious. It also introduces new failure modes: errors that arrive halfway through a response, partial JSON, and connections that drop behind proxies. Designing for those up front is much cheaper than retrofitting.

How it works

Most providers stream over server-sent events (SSE): a long-lived HTTP response where the server writes event: and data: lines as things happen. Anthropic's Messages API, with "stream": true, sends a fixed sequence: message_start, then for each content block a content_block_start, one or more content_block_delta events and a content_block_stop, then message_delta with the stop reason and usage, and finally message_stop. Deltas come in types: text_delta for text, input_json_delta for tool arguments (partial JSON you must concatenate before parsing) and thinking_delta for thinking. ping and error events can appear at any time, and the docs warn that new event types may be added, so ignore what you do not recognize.

OpenAI's Responses API streams semantic events instead, such as response.output_text.delta, response.function_call_arguments.delta and response.completed, with final usage on the completed event.

Rendering diagram…

Your server should almost always sit in the middle. It holds the API key, adds context and tools, enforces auth and rate limits, logs usage, and re-streams to the browser in a format your UI understands.

Reference architecture

The UI side is a small state machine. Modelling it explicitly avoids the classic bugs: double submits, a spinner that never stops, and a half-rendered message after an error.

Rendering diagram…

Code

With the Vercel AI SDK, a Next.js App Router route can stream a model response to the browser in a few lines. The useChat hook from @ai-sdk/react consumes this format on the client and manages message state, status and stop.

// app/api/chat/route.ts
import { streamText, convertToModelMessages, type UIMessage } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export const maxDuration = 60;

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = streamText({
    model: anthropic("claude-sonnet-4-6"),
    system: "You are a concise assistant. Use short paragraphs.",
    messages: await convertToModelMessages(messages),
    abortSignal: req.signal,
    onFinish: ({ usage, finishReason }) => {
      console.log({ finishReason, usage });
    },
    onError: ({ error }) => {
      console.error("stream error", error);
    },
  });

  return result.toUIMessageStreamResponse();
}

Passing req.signal means that when the user hits stop and the browser aborts the fetch, the upstream model request is cancelled too, so you stop paying for tokens nobody will read. If you call a provider SDK directly instead, the Anthropic Python SDK's client.messages.stream(...) context manager exposes a text_stream iterator and a final message with usage.

UX patterns that work

  • Show something within a few hundred milliseconds: a typing indicator on submit, then real tokens.
  • Render markdown incrementally but tolerate incomplete syntax (an unclosed code fence mid-stream should not break layout).
  • Keep a visible stop button while streaming, and keep partial output when stopped.
  • Surface tool activity as status lines ("Searching orders...", "Reading 3 documents") rather than silence.
  • For reasoning models, show a collapsible thinking summary or a progress label so long pauses feel intentional.
  • Stream structured output carefully: render partial objects only for display, and act on them only after the final validated object arrives.
  • Make errors recoverable: keep the user's message, show what failed, offer retry.
  • Auto-scroll only if the user is already at the bottom, so you do not yank them while they read.

Trade-offs and pitfalls

  • Proxies and buffering. Some reverse proxies and serverless platforms buffer responses, which kills streaming. Verify end to end in the deployed environment, and disable buffering for the route.
  • Timeouts. Long generations can exceed platform function limits. Set duration limits deliberately and cap max_tokens.
  • Mid-stream errors. A 200 status does not mean success; an error event (for example an overloaded error) can arrive after text has rendered. Handle it in the UI.
  • Partial tool JSON. Never parse tool arguments until the block is complete.
  • Moderation and validation. If you must check output before showing it, you lose some streaming benefit. Consider streaming with a post-hoc check and a retract path for rare failures.
  • Usage accounting. Final token usage arrives at the end of the stream. Log it in a finish callback, including for cancelled requests.
  • Accessibility. Rapidly updating text can overwhelm screen readers. Use polite live regions and announce completion rather than every token.

Checklist

  • Every user-facing generation streams, with first visible feedback in well under a second.
  • Stop cancels the upstream request through an abort signal.
  • Mid-stream errors render a clear, retryable state.
  • Tool calls and long thinking show progress text.
  • Usage is logged on finish, including stopped responses.
  • Streaming is verified through the production proxy and hosting layer.
  • Partial structured output is never acted on before final validation.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.