Filed underL07 · Design
Published
Reading time25 min
Words5,826
Field notes · L07 Design

Designing for AI latencyStreaming, optimistic UI and showing uncertainty

AI UX patterns for latency: time-to-first-token as a UX metric, streaming over SSE, agent step disclosure, cancellation, sources, uncertainty and error states.

The short answer

You can't make a large model answer in 100 ms, so design for the wait instead of hiding it. Acknowledge every input within 100 ms. Get the first useful token on screen inside a second. Stream text at a steady pace a person can read. Show agent steps as a live timeline, not a spinner. Give the user a Stop button that actually stops the upstream generation, show sources rather than made-up confidence scores, and treat a failure halfway through the stream as a normal state of the UI, not an exception. On the wire, server-sent events over a POST fetch request are the right default for almost every team. Use your own event schema, a heartbeat, and the proxy settings that stop something in the middle from buffering your stream.

The rest of this post covers the metrics, the patterns, the failure modes and a reference implementation. There is also a latency budget matrix and a release checklist you can take straight into a design review.

01Why AI latency is a design problem, not just an infrastructure one

Normal web performance work is about getting a response down to a few hundred milliseconds. With LLM features that usually can't be done. A model with tools might take 2 seconds to start talking and 40 seconds to finish. An agent might take five minutes. No CDN or index will close that gap.

So the job changes. You stop trying to remove the wait and start shaping how it feels. OpenAI's own latency optimisation guide makes the point well: "There's a huge difference between waiting and watching progress happen." It calls streaming "the single most effective approach, as it cuts the waiting time to a second or less."

The thresholds that matter haven't changed in decades. Nielsen's three response-time limits still hold:

  • 0.1 s feels instant.
  • 1 s is "the limit for the user's flow of thought to stay uninterrupted".
  • 10 s is the limit for keeping attention. Beyond that, people need feedback about when the work will finish, and "a clearly marked way to interrupt".

An AI interaction crosses all three thresholds in a single turn. That's why it needs a design for each phase, not one loading state.

02The four latencies of an AI turn

Split every turn into four intervals and instrument each one separately, for example as spans when tracing LLM apps with the OpenTelemetry GenAI conventions. "p95 latency" for a whole streaming response tells you almost nothing.

Diagram
user presses Enter
│
├── t_ack ─────────── UI acknowledges input (message echoed, composer cleared)
│                     target: < 100 ms, entirely client-side
│
├── TTFB ──────────── first byte of the HTTP response (your server is alive)
│
├── TTFT ──────────── first token of model output reaches the client
│
├── TTFUT ─────────── first *useful* token: first visible answer text,
│                     after tool calls, retrieval, hidden reasoning
│
├── stalls ────────── gaps between tokens > N ms during generation
│
└── TTC ───────────── turn complete (stop reason received)
Metric What it measures Where to measure What moves it
t_ack Did the UI react? Client Optimistic rendering. Pure front-end work
TTFB Is the server path healthy? Client and edge Auth, cold starts, proxy buffering
TTFT Model queue + prefill time Server (upstream) and client Prompt length, prompt caching, model choice, region
TTFUT When the user gets something to read Client Tool-call count, retrieval latency, reasoning budget, how much preamble you stream
Stall p95 Smoothness Client Tool calls mid-answer, upstream load, buffering proxies
TTC Total cost of the turn Server Output length, model speed
Cancel rate Did we answer the wrong thing, or too slowly? Client Product quality as much as latency

Two things here are not obvious.

Measure TTFT on the client as well as the server. The server sees the model's TTFT. The user sees TTFT plus every proxy, load balancer and compression layer that might hold bytes back. A gap between the two numbers almost always means buffering. More on that below.

TTFUT is the metric to put on the dashboard. An agent that streams "Let me look into that…" in 300 ms and then goes quiet for 12 seconds while it calls tools has a good TTFT and a bad experience. Count from Enter to the first token of answer text the user can actually use.

How fast does streaming need to be?

Faster than people read, and not much more than that. Here is the calculation, with its assumptions:

  • Silent reading speed for English non-fiction is roughly 238 words per minute (Brysbaert, 2019 meta-analysis).
  • Anthropic's pricing FAQ gives a rule of thumb of 1 token ≈ 0.75 English words. The same page notes that newer Claude tokenizers produce about 30% more tokens for the same text, so for those models assume about 0.58 words per token.
  • 238 wpm ÷ 60 ≈ 4 words/s. That is about 5.3 tokens/s with the older ratio, or about 6.8 tokens/s with the newer one.

Almost any hosted model streams prose far faster than that. So once text is flowing, raw throughput barely matters for prose the user reads line by line. It matters a lot for output the user can't use until it's finished: code they will copy, a table they will scan, JSON your UI parses. For those, cut TTC by generating fewer tokens. Don't just make them arrive faster.

03The AI latency budget and pattern matrix

This is the asset to take into a design review. Find the band your feature falls into for p75 TTFUT and p75 TTC, then build every pattern in its row. If a feature drifts into a slower band in production, the UI has to change with it, not only the infrastructure.

Band (p75) Typical feature Must show Interaction Do not
< 1 s TTC Autocomplete, classification, short rewrite Nothing beyond an inline result; maybe a subtle pending state after 300 ms Debounce input; cancel stale requests on each keystroke Stream. Flickering partial output is worse than a 600 ms wait
TTFUT < 1 s, TTC 1–10 s Chat answer, summary, explanation Echoed input; streamed text at a smoothed cadence; cursor or caret at the insertion point Stop button visible from the first byte Show a spinner and then dump the full text
TTFUT 1–5 s RAG answer, single tool call A named activity ("Searching 3 policy documents") within 500 ms; then stream Stop; show the sources as they are retrieved, before the answer Fake typing or filler text to look busy
TTFUT 5–30 s Multi-step agent, code generation with tests A step timeline with live status per step; elapsed time; partial artefacts as they land Stop; expand/collapse steps; steer ("skip the tests") if your harness supports it Percentage bars without a real denominator
TTC > 30 s, up to minutes Research agent, batch edit, migration Everything above, plus: a run that outlives the tab; resumable stream; notification on completion User can leave and come back; explicit cancel separate from closing the tab Tie the work's lifetime to one HTTP connection
TTC > 10 min Long-running background job A job record with status, not a chat bubble Email/Slack/in-app notification; result as a durable artefact Pretend it's a conversation

The rule behind the table: the slower the band, the more the UI should show the work, and the less it should show the waiting.

04Streaming patterns that work

Smooth the token stream

Tokens don't arrive evenly. They come in bursts with irregular gaps, especially across tool calls or under load. If you paint each chunk the moment it arrives, the text stutters. It's hard to read, and it looks broken.

Put a small buffer between the network and the DOM, and drain it at a rate that adapts to how much is waiting:

ts
// Drains a text buffer once per animation frame.
// Speeds up when the backlog grows, so we never fall far behind the network.
export function createSmoother(onFlush: (text: string) => void) {
  let backlog = "";
  let rafId: number | null = null;
  let finished = false;

  const tick = () => {
    if (backlog.length === 0) {
      rafId = null;
      return;
    }
    // ~2 chars/frame at rest (~120 chars/s at 60 fps), scaling with backlog.
    const n = Math.max(2, Math.ceil(backlog.length / 20));
    const take = finished ? backlog.length : n; // flush instantly at the end
    onFlush(backlog.slice(0, take));
    backlog = backlog.slice(take);
    rafId = requestAnimationFrame(tick);
  };

  return {
    push(chunk: string) {
      backlog += chunk;
      if (rafId === null) rafId = requestAnimationFrame(tick);
    },
    end() {
      finished = true;
      if (rafId === null && backlog) rafId = requestAnimationFrame(tick);
    },
  };
}

At rest, 120 characters a second is roughly 24 words a second, comfortably ahead of reading speed. When the network sends a large chunk, the divisor makes the drain catch up within about 20 frames. Respect prefers-reduced-motion: for those users, flush per sentence instead of per frame.

Render Markdown in blocks, not tokens

Re-parsing the full Markdown document on every token is the most common cause of a janky streaming UI. The cost is O(n²) over the response, and half-finished syntax makes the layout jump: an unclosed ** turns the rest of the paragraph bold for a moment, and an open code fence turns everything after it into code.

What we'd do:

  1. Split the stream into closed blocks (paragraphs, list items, finished code fences) and one open tail.
  2. Render closed blocks once and memoise them. They never change.
  3. Render the open tail as plain text, or with a forgiving parser that auto-closes open emphasis and fences.
  4. Batch DOM updates to one per animation frame. The smoother above already does this.

Code blocks need special handling. Don't run syntax highlighting until the fence closes. Show a monospace block with the language label straight away, then highlight once.

Stream structure, not just prose

When the output is structured (a form fill, a set of extracted fields, a plan with steps), stream it into a skeleton. Render the field labels straight away and fill each value as its key arrives. Anthropic's streaming API sends tool input as input_json_delta partial JSON strings. The docs note that current models emit "one complete key and value property from input at a time", so expect pauses between fields, not a smooth flow of characters. Design the skeleton for that rhythm.

When not to stream

You probably shouldn't stream when:

  • The output must be checked before anyone sees it. Generated SQL you're about to run, moderated content in a regulated setting, anything that a policy check might reject. Streaming and then retracting text is worse than waiting.
  • The output is short. Below about a second of TTC, a single render looks cleaner.
  • The output is a decision, not a document. A classification label, a yes/no answer, a routing choice.
  • Partial output is actively misleading. "The contract permits early termination…" followed two seconds later by "…only with 90 days' notice and a penalty." If the second half changes the meaning, wait for it, or stream at sentence granularity.

05Optimistic UI for AI: what you can and can't predict

Optimistic UI means rendering the expected result before the server confirms it. With AI you can't predict the content, but you can predict almost everything around it:

  • Echo the user's message immediately, in its final position and style, with a pending marker that only appears after about 300 ms. That gives you a t_ack under 100 ms whatever the backend does.
  • Insert the assistant turn container immediately, with the model name, a caret, and the Stop button. The layout shouldn't shift when the first token arrives.
  • Pre-warm. When the composer gets focus or the user starts typing, open the connection, refresh auth, and (if your provider supports it) warm the prompt cache with the system prompt and conversation prefix. Caching a long prefix cuts both cost and prefill time; our guide to prompt caching and LLM cost engineering covers the layout that makes it hit.
  • Speculate cheaply where the next action is predictable. Suggested follow-ups, the likely next document, the retrieval for an obvious follow-up question. Throw the work away if it isn't used.

There is one firm rule. Never be optimistic about side effects. Don't show "Email sent", "Ticket created" or "Refund issued" until the tool call has returned and your system has confirmed it. An agent's claim that it did something is not evidence that it did. Our post on agent failure modes in production covers why you check the world rather than the model's report.

06Progressive disclosure of agent steps

Once a task involves tools, the wait stops being a wait and becomes work. Show the work.

Diagram
┌──────────────────────────────────────────────────────────────┐
│ √ Read 4 files in src/billing/                     0.8 s     │
│ √ Searched issues for "proration"                  1.2 s     │
│ ● Running test suite (142 of ~300 tests)           18 s ...  │
│ ◌ Draft fix                                                  │
│                                                   [ Stop ]   │
└──────────────────────────────────────────────────────────────┘

Rules we hold to:

  • Write each step label in the user's terms, from the tool call's arguments. "Searched issues for 'proration'", not github.search_issues({"q":"proration"}). Generate the label in your harness from a template for each tool. Don't ask the model to narrate. That's slower, costs tokens and can drift from what actually happened.
  • Show elapsed time per step, live. A counter that keeps moving tells the user the system is still alive, without making promises about when it will finish.
  • Only show a percentage when you have a real denominator. "142 of ~300 tests" is honest. A progress bar driven by a guess is not, and users learn to ignore it.
  • Collapse finished steps when the answer starts. Keep them one click away. Auditors, power users and your support team will want them.
  • Show artefacts as they arrive. Retrieved sources, a draft diff, a chart. A partial artefact is more useful than a status line.
  • Show hidden reasoning only as summaries, if at all. Some providers now offer summarised or progress-only reasoning output. Anthropic's thinking display has an "omitted" mode and an "updates" beta, documented in its streaming docs. Short progress updates between tool calls make good step labels. Raw reasoning is usually noise for an end user.

The design of the step timeline depends on the harness behind it. If your harness doesn't emit structured step events, the UI has nothing honest to show. Our post on what an agent harness is covers that side.

07Cancellation: a Stop button that actually stops

A Stop button that hides the output while the model keeps generating (and billing) on the server is one of the easiest AI UX bugs to ship. Cancellation has to go all the way through:

Diagram
[Stop] → AbortController.abort() → fetch rejects, reader cancels
       → server sees the disconnect (request.signal aborts)
       → server aborts the upstream SDK call (same signal)
       → provider closes the generation; you stop paying for output tokens

Client:

ts
const controller = new AbortController();
stopButton.onclick = () => controller.abort();

try {
  const res = await fetch("/api/turns", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ conversationId, message }),
    signal: controller.signal,
  });
  for await (const ev of readEvents(res)) handle(ev);
} catch (err) {
  if ((err as DOMException).name === "AbortError") markTurn("stopped");
  else markTurn("failed", err);
}

abort() cancels the fetch, the body read and the stream, and rejects with an AbortError (MDN). If you also want a client-side timeout, combine signals with AbortSignal.any(). MDN lists it as Baseline, available across browsers since March 2024 (MDN).

UX details that matter:

  • Keep the partial output and label it "Stopped". The user stopped it because they'd seen enough or seen something wrong. Either way, they want to see it.
  • Restore the composer with the original prompt, so editing and resending takes one keystroke.
  • Make Stop available from the first byte, not from the first token. Most of the frustrating waits happen before any token arrives.
  • In long-running designs, keep cancel and disconnect separate. If agent runs survive a closed tab (and past the 30-second band they should), a dropped connection must not cancel the run. Stop sends an explicit POST /runs/:id/cancel. Closing the tab only detaches.

08Showing uncertainty: sources beat scores

Users want to know when to trust the answer. The tempting fix is a confidence badge, a percentage the model reports about itself. Don't. A model's stated confidence is a generated token, not a measurement, and research has found it tends towards overconfidence (Xiong et al., 2023). A "92% confident" badge that has never been calibrated against your own eval set misleads people in a precise-looking way.

What we'd show instead, roughly in order of value:

  1. Inline citations tied to specific claims, with the quoted passage available on hover or tap. Many providers now return citations as structured data. Render them as links to the exact passage, not a list of documents at the bottom.
  2. Coverage signals you actually computed. "Answered from 3 of your documents" or "No matching policy found; answering from general knowledge". You know this from your retrieval step. Say it.
  3. Verification state. "Code compiled and 12 tests passed" is a confidence signal grounded in reality. So is "Figures cross-checked against the ledger".
  4. Abstention as a designed state. "I couldn't find this in the contract" should get a proper component with a next action (search wider, ask a person), not a paragraph of hedged prose.
  5. Calibrated thresholds, if you have the data. If your eval set shows that answers with a retrieval score below x are wrong y% of the time, you've earned the right to flag them. Our post on how to build LLM evals for your own use case covers building that evidence.

Use language with care. Hedging every sentence teaches users to ignore hedges. Hedge once, where the uncertainty actually is, and make the source of the uncertainty visible.

09Error states: the stream will fail halfway through

With streaming, an HTTP 200 doesn't mean success. The status code went out with the first byte, long before the outcome was known. Anthropic's docs say plainly that errors can arrive inside the event stream, for example an overloaded_error that "would normally correspond to an HTTP 529 in a non-streaming context" (streaming docs). Your client needs a state for "partial answer, then failure".

Failure What the user sees What the system does
Fails before first token (429, 5xx, overload) "Busy, retrying…" with a countdown; then a manual retry Automatic retry with jittered backoff, at most 2 attempts; switch to a fallback model if you have one
Fails mid-stream (in-stream error event) Partial text kept, marked incomplete; "Continue" and "Retry" actions Do not silently restart. Duplicated or diverging text is worse than an honest stop
Connection drops (network, proxy timeout) "Reconnecting…" inline, not a modal Reconnect with Last-Event-ID, replay from the run log (see resumable streams below)
Heartbeat missing for > 2 intervals Same as connection drop Client treats silence as failure; don't wait forever
max_tokens stop reason Answer marked truncated; "Continue" Continue from the last turn rather than regenerating
Tool failure inside an agent That step shows as failed with the reason; run continues or pauses Harness decides retry, skip or escalate; the UI shows what it decided
Policy refusal A designed refusal component with a reason category Log for review; never show a raw provider error string

Two rules apply across the table. Never show raw provider errors to users. And tell retryable and non-retryable errors apart in your own event schema, so the client doesn't have to guess.

10Implementation: streaming LLM responses with server-sent events

Why SSE (over fetch) and not WebSockets

For model output, SSE wins on almost every count that matters. It's plain HTTP, so your auth, logging, WAF and CDN already understand it. It's one-directional, which fits a token stream. And it has a standard wire format with built-in event IDs and a reconnection convention.

Don't use the browser's EventSource API for chat, though. Its constructor takes a URL and a withCredentials flag, and nothing else (MDN). That means GET only, no request body, and no Authorization header. Use fetch with POST and parse the stream yourself. It's about 30 lines of code.

Use WebSockets when the client genuinely needs to stream upwards at the same time, as with live voice, collaborative cursors or interrupting mid-utterance. Otherwise you're taking on connection-state machinery you don't need.

SSE over fetch EventSource WebSocket
Method / body Any / yes GET / no Upgrade / n/a
Custom auth header Yes No (cookies only) Only on handshake, awkwardly
Through standard proxies/CDNs Yes, with buffering off Yes Usually; needs upgrade support
Auto-reconnect You write it Built in You write it
Client → server mid-stream No (separate request) No Yes
Our default for LLM text Yes No Only for duplex (voice, co-editing)

Define your own event schema

Don't forward the provider's raw events to the browser. You'll be tied to their schema, you'll leak internals, and you'll break when they add fields. Anthropic's docs warn that "new event types may be added, and your code should handle unknown event types gracefully". Translate at your server into a small, stable vocabulary:

ts
type TurnEvent =
  | { type: "turn.started"; runId: string }
  | { type: "step"; stepId: string; status: "running" | "done" | "failed"; label: string; elapsedMs?: number }
  | { type: "source"; ref: number; title: string; url: string }
  | { type: "text.delta"; text: string }
  | { type: "turn.completed"; stopReason: "end_turn" | "max_tokens" | "cancelled" }
  | { type: "error"; code: "overloaded" | "rate_limited" | "upstream" | "policy"; retryable: boolean };

Server: relay with cancellation and heartbeats

This handler uses only web-standard Request/Response, so it runs as-is in a Next.js route handler, Hono, or a Cloudflare Worker with Node compatibility enabled. Cancellation depends on the runtime aborting request.signal when the client disconnects. Next.js on its Node runtime and Hono's @hono/node-server adapter both do this; Workers only do it with the enable_request_signal compatibility flag. Test it on your platform:

ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

export async function POST(req: Request): Promise<Response> {
  const { messages, runId } = await req.json();
  const enc = new TextEncoder();
  let seq = 0;

  const body = new ReadableStream<Uint8Array>({
    async start(controller) {
      const write = (s: string) => {
        try { controller.enqueue(enc.encode(s)); } catch { /* stream closed */ }
      };
      const send = (ev: TurnEvent) =>
        write(`id: ${runId}:${++seq}\nevent: ${ev.type}\ndata: ${JSON.stringify(ev)}\n\n`);

      // Comment lines keep idle connections alive through proxies.
      const heartbeat = setInterval(() => write(": hb\n\n"), 15_000);
      send({ type: "turn.started", runId });

      let stopReason: "end_turn" | "max_tokens" | "cancelled" = "end_turn";
      try {
        const upstream = await client.messages.create(
          { model: process.env.MODEL!, max_tokens: 2048, messages, stream: true },
          { signal: req.signal }, // client disconnect aborts the upstream call
        );
        for await (const ev of upstream) {
          if (ev.type === "content_block_delta" && ev.delta.type === "text_delta") {
            send({ type: "text.delta", text: ev.delta.text });
          } else if (ev.type === "message_delta" && ev.delta.stop_reason === "max_tokens") {
            stopReason = "max_tokens";
          }
          // Everything else, including event types added later, is ignored.
        }
        send({ type: "turn.completed", stopReason });
      } catch (err) {
        if (!req.signal.aborted) send(classify(err));
      } finally {
        clearInterval(heartbeat);
        try { controller.close(); } catch { /* already closed */ }
      }
    },
  });

  return new Response(body, {
    headers: {
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
      "X-Accel-Buffering": "no",
    },
  });
}

function classify(err: unknown): TurnEvent {
  // Errors before the stream starts carry an HTTP status. An `error` event inside
  // the stream is thrown as an APIError with no status, so read its `type` too.
  const status = err instanceof Anthropic.APIError ? err.status : undefined;
  const kind = err instanceof Anthropic.APIError ? err.type : null;
  if (status === 429 || kind === "rate_limit_error") return { type: "error", code: "rate_limited", retryable: true };
  if (status === 529 || kind === "overloaded_error") return { type: "error", code: "overloaded", retryable: true };
  return { type: "error", code: "upstream", retryable: status === undefined || status >= 500 };
}

Notes on the choices:

  • The 15-second heartbeat comes straight from the spec, which suggests "a comment line (one starting with a ':' character) every 15 seconds or so" to stop proxies dropping idle connections (WHATWG). It matters most during tool calls, when no tokens are flowing.
  • id: on every event lets you resume. On reconnect, the client sends the last ID it saw, using the Last-Event-ID header by convention.
  • no-transform and X-Accel-Buffering: no stop intermediaries from compressing or buffering the stream. In nginx, a yes/no value in X-Accel-Buffering turns proxy buffering on or off for that response (nginx docs).

Client: parse SSE from a fetch body

ts
export async function* readEvents(res: Response): AsyncGenerator<TurnEvent> {
  if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buf = "";
  while (true) {
    const { value, done } = await reader.read();
    if (done) return;
    buf += value;
    let sep: number;
    // Our server emits LF line endings only, so "\n\n" ends an event.
    while ((sep = buf.indexOf("\n\n")) !== -1) {
      const raw = buf.slice(0, sep);
      buf = buf.slice(sep + 2);
      const data: string[] = [];
      for (const line of raw.split("\n")) {
        if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
        // ignore comments (":"), "event:" (type is in the payload), "id:" (track it if resuming)
      }
      if (data.length) yield JSON.parse(data.join("\n")) as TurnEvent;
    }
  }
}

The infrastructure traps that break streaming

Each of these turns a streaming UI back into a 20-second blank screen, and none of them shows up in local development:

  • Proxy buffering. nginx buffers proxied responses by default. Send X-Accel-Buffering: no or set proxy_buffering off for the streaming route.
  • Read timeouts between bytes. nginx's proxy_read_timeout defaults to 60 s and applies "between two successive read operations", so a long silent tool call can kill the connection. Heartbeats fix this. Cloudflare's proxy read timeout is 125 s by default and can only be raised on Enterprise (Cloudflare limits, 524 docs).
  • Compression middleware that waits for a full block before flushing. Exclude text/event-stream, or make sure the middleware flushes on each write.
  • HTTP/1.1 connection limits. Without HTTP/2, browsers allow 6 connections per browser per domain, shared across all tabs. Chrome and Firefox have marked this "Won't fix" (MDN). Five open tabs each holding a stream will stall the sixth tab's ordinary API calls. Serve over HTTP/2 or HTTP/3 end to end.
  • Serverless execution limits. If your function platform caps wall-clock time below your p99 TTC, the stream gets cut off. That's another reason to move long runs off the request path.

Resumable streams for long-running agents

Past the 30-second band, don't tie the run to the connection. Separate them:

Diagram
POST /runs ──► create run, enqueue job ──► 202 { runId }
                        │
                worker executes agent, appends TurnEvents
                        │
                        ▼
              append-only run log (Redis Stream, Postgres table, Durable Object)
                        ▲
GET /runs/:id/events ───┘  SSE: replay from Last-Event-ID, then tail live
POST /runs/:id/cancel ─────►  sets cancel flag; worker checks between steps

The worker writes events with monotonic IDs. The SSE endpoint replays everything after the client's Last-Event-ID, then tails new events as they arrive. A refresh, a network blip or a laptop lid closing becomes a reconnect, not a lost answer. If you retry run creation, make it idempotent, or a flaky network will start two agents. Our post on idempotency keys for APIs that survive retries covers the pattern.

11Where this crosses into other layers

AI latency is never purely a design problem, which is why we look at it across the stack. TTFT depends on prompt length and caching (AI & Automation). Whether tokens actually reach the browser depends on your proxies, CDN and HTTP version (Cloud & DevOps). Cancellation that doesn't reach the provider shows up as cost (Strategy, eventually). Step labels need structured events from the harness (Software). Citations need retrieval that returns passage-level provenance, and a RAG evaluation set that checks it (Data). A design team handed a spinner and a deadline can't fix any of these alone. It goes better when design, platform and AI engineers share one set of latency metrics. Our post Anatomy of a request: distributed tracing through CDN, WAF, load balancer, app and database shows how to see where the milliseconds go.

12Release checklist for a streaming AI surface

Run this before an AI feature ships. Every item should be a yes, or a deliberate and documented no.

Metrics

  • t_ack, TTFB, TTFT (server and client), TTFUT, stall p95, TTC and cancel rate are instrumented and on one dashboard.
  • The feature's latency band from the matrix is written down, with an alert if p75 drifts into the next band.

Streaming

  • Text is smoothed; DOM updates happen at most once per animation frame.
  • Markdown renders closed blocks once; code highlighting waits for the closing fence.
  • prefers-reduced-motion gets sentence-level updates.
  • A deliberate decision has been made about not streaming outputs that need validation first.

Agent steps

  • Step labels come from tool arguments via templates, not model narration.
  • Elapsed time is live; percentages only appear with a real denominator.
  • Side effects are shown only after confirmation from your system.

Cancellation

  • Stop is visible from the first byte.
  • Stop aborts the upstream provider call (verified in provider usage logs, not assumed).
  • Partial output is kept and labelled; the prompt is restored to the composer.
  • For long runs, closing the tab detaches and does not cancel.

Uncertainty

  • No uncalibrated model-reported confidence scores.
  • Citations link to passages; retrieval coverage is shown honestly; abstention has a designed state.

Errors

  • Mid-stream errors render as partial + incomplete, with Continue/Retry.
  • Missing heartbeats are treated as a failure on the client.
  • The event schema marks errors as retryable or not; raw provider errors never reach users.

Infrastructure

  • Buffering is disabled on every hop (app server, nginx/ingress, CDN, compression).
  • The heartbeat interval is shorter than every proxy read timeout on the path.
  • HTTP/2 or HTTP/3 end to end.
  • Tested through the production proxy chain, not just localhost.

13FAQ

What is a good time-to-first-token target for an AI chat interface?

Aim for under one second to the first useful token at p75. That's Nielsen's limit for keeping the user's flow of thought. Acknowledge the input in under 100 ms whatever the backend does. If tools or retrieval make sub-second TTFUT impossible, show a named activity within about 500 ms so the user knows what they're waiting for.

Should I use WebSockets or server-sent events to stream LLM responses?

Server-sent events, sent over a fetch POST, for almost all text generation. It's plain HTTP, works with your existing auth and proxies, and fits one-way token streams. Use WebSockets only when the client must stream data upwards at the same time, as with live voice or collaborative editing.

Why does my LLM stream arrive all at once in production but work locally?

Something between the server and the browser is buffering it. Usually that's nginx proxy buffering, a CDN, or compression middleware. Send Cache-Control: no-cache, no-transform and X-Accel-Buffering: no, turn off buffering on the route, and compare server-side and client-side TTFT to find the hop that's holding bytes.

Does clicking "Stop generating" stop the model and the billing?

Only if you wire it through. The browser's AbortController cancels the fetch, but your server must also abort its upstream call when the client disconnects, for example by passing the request's abort signal to the SDK. Confirm in your provider's usage data that output tokens stop accruing after a cancel.

How should an AI interface show confidence?

Show evidence, not self-reported percentages. Inline citations to specific passages, honest retrieval coverage ("answered from 3 documents"), verification results ("tests passed") and a designed "couldn't find this" state are all grounded. Show a numeric confidence only if you have calibrated it against your own eval data.

How do I show progress for an AI agent that takes minutes?

Use a step timeline with labels written in the user's terms, live elapsed time for each step, and partial artefacts as they're produced. Run the agent off the request path so it outlives the tab, stream its events from a durable log so clients can reconnect, and notify the user when it finishes.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →