Making AI Features Feel Fast: Streaming, Latency and UX
Time to first token vs output speed, streaming from the model to the browser in Next.js, the UX details that make streaming feel polished, and the changes that genuinely cut latency. With an interactive race between waiting and streaming.
Users don't measure your AI feature with a stopwatch. They measure how long they stare at a spinner.
Language models are slow compared with almost everything else in a web app. A database query takes milliseconds; a long model answer can take several seconds. You can't make that disappear, but you have a lot of control over how it feels, and a fair amount over how long it actually takes.
This article covers both: the two numbers that make up AI latency, how to stream answers end to end in a Next.js app, the small UX details that make streaming feel polished, and the changes that genuinely cut the wait.
The two numbers behind every wait
- Time to first token (TTFT). How long until the model sends the first piece of its answer. It grows with prompt length and model size, and it's what users feel as “is anything happening?”.
- Output speed. Tokens per second once it starts. Total time is roughly TTFT plus the number of output tokens divided by this speed.
That formula explains most latency problems. A long answer from a slow model is slow mostly because it is long. Halving the output length often saves more time than any infrastructure change.
Human perception adds the other half. The classic response-time limits from usability research still hold: about 0.1 seconds feels instant, about 1 second keeps someone's train of thought, and past about 10 seconds people lose focus and start doing something else. An AI answer that takes four seconds sits right in the uncomfortable middle, unless something is happening on screen.
Same model, same total time, very different feel
Here's one answer delivered two ways. Pick a speed and send the question.
Model speed
First token after 0.9s, then 60 tokens a second. About 109 tokens in this answer.
Wait for the whole answer
Nothing on screen for 2.7s
Stream it
First words at 0.9s, finished at 2.7s
Illustrative speeds. Real numbers depend on the model, prompt length, load and region.
Both finish at exactly the same moment. But on the right, the user is reading within a second, and if the answer is heading the wrong way, they can stop it and rephrase. On the left they get a spinner and then a wall of text. With the slow setting the difference is stark: words after two and a half seconds instead of a blank box for six.
Streaming end to end
Every major provider can stream responses as server-sent events. The job is to pass those chunks through your server to the browser without buffering them. In a Next.js route handler:
// app/api/answer/route.ts
import Anthropic from "@anthropic-ai/sdk"
const client = new Anthropic()
export async function POST(request: Request) {
const { question } = await request.json()
const stream = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: question }],
})
const encoder = new TextEncoder()
const body = new ReadableStream({
async start(controller) {
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
controller.enqueue(encoder.encode(event.delta.text))
}
}
controller.close()
},
cancel() {
stream.controller.abort() // the user pressed Stop: stop paying for tokens
},
})
return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } })
}And on the client, read the body as it arrives:
const controller = new AbortController() // wire controller.abort() to a Stop button
const response = await fetch("/api/answer", {
method: "POST",
body: JSON.stringify({ question }),
signal: controller.signal,
})
const reader = response.body!.getReader()
const decoder = new TextDecoder()
while (true) {
const { done, value } = await reader.read()
if (done) break
setAnswer((text) => text + decoder.decode(value, { stream: true }))
}Two details matter more than they look. Keep the API key on the server, always. And make sure nothing between the model and the browser buffers the response: some proxies, compression settings and serverless configurations collect the whole body before sending it, which quietly turns streaming back into waiting.
The UX details that make streaming feel good
Give a Stop button
Abort the request and the upstream model call. Users stop wrong answers early, and you stop paying for them.
Don't fight the scroll
Auto-scroll only if the user is already at the bottom. If they scrolled up to read, leave them there.
Render partial Markdown safely
A half-finished code fence or table shouldn't break the layout. Use a renderer that tolerates incomplete input.
Show steps, not just a spinner
For agents, “Searching orders…”, “Reading 3 documents…” turns dead time into visible progress.
Announce politely
Screen readers shouldn't hear every token. Announce “Answer ready” or update a live region in sentences.
Keep partial answers on errors
If the stream fails halfway, keep what arrived and offer “Continue” or “Retry”, rather than wiping it.
Structured output is the exception. A half-finished JSON object isn't useful to show, so for structured steps show progress and a skeleton of the result, then render it once it's complete and validated.
Making it actually faster
Streaming fixes perception. These change the real numbers, roughly in order of impact:
Ask for less output
Output time is linear in length. “Answer in two or three sentences”, a tighter max_tokens, or a structured result instead of prose can cut seconds. Users rarely want the long version anyway.
Use the smallest model that's good enough
Small models start sooner and write faster. Route easy requests to them and keep the big model for the hard ones. How to pick tiers is in choosing the right AI model.
Cache long prompt prefixes
A long system prompt or document has to be processed before the first token. With prompt caching, repeat requests skip most of that work, which lowers time to first token as well as cost.
Run things in parallel
Retrieval, independent tool calls and separate checks don't need to wait for each other. Three sequential one-second steps become one second. Chains of model calls are the most common hidden cause of slow AI features.
Don't make users wait for work that can wait
Summaries, tags and reports can be generated in the background and ready before anyone asks. For bulk work, batch APIs trade speed for half the price.
Measure what users feel
Log time to first token, total time and output tokens for every request, and look at the slow end (p95), not the average. Measure in the browser too: what matters is when text appears on the user's screen, not when your server got it. Set a budget, for example first words within a second for chat, and alert when you drift. Treat latency like any other quality signal, next to the evals and the guardrails covered in shipping AI features to production.
Frequently Asked Questions
What is time to first token?
The time from sending a request until the model returns the first piece of its answer. It's driven by prompt length, model size, load and network, and it's what users feel as 'is anything happening?'.
Does streaming make an LLM faster?
No, the total time is the same. Streaming shows the answer as it's generated, so users start reading after the first token instead of waiting for the last one. It makes the feature feel much faster and lets people stop a wrong answer early.
How do I stream LLM responses in Next.js?
Call the model with streaming enabled in a route handler, forward each text chunk into a ReadableStream, and return it as the response. On the client, read the body with a stream reader and append each chunk to state. Use an AbortController so users can stop it.
How can I reduce LLM latency?
Ask for shorter outputs, use a smaller model where it's good enough, cache long stable prompt prefixes, run independent steps in parallel, and avoid chains of sequential model calls. Output length is usually the biggest factor.
Should I stream structured JSON output?
Only if you can show something useful from partial data. Usually it's better to show progress for structured steps and stream only the human-readable text. If you do stream JSON, use a parser built for partial JSON and validate the final result.
The short version
Total time is time to first token plus output length divided by speed. Stream everything users read, end to end, with a Stop button and calm scrolling, and show steps instead of a spinner. Then make it truly faster by asking for shorter answers, using smaller models where they're good enough, caching long prompts and running independent work in parallel. Measure time to first token in the browser, at p95.
Continue Reading
Explore more articles on software engineering and technology
Prompt Injection and AI Security: A Practical Guide for App Developers
Why LLMs can't reliably tell instructions from data, how indirect injection hides in emails and web pages, the lethal trifecta, and the layered defences that hold: fewer capabilities, real confirmation, output control, quarantine and testing. With an interactive attack demo.
Structured Output and Tool Calling: Getting Reliable JSON from LLMs
Prompt-only vs JSON mode vs structured outputs, how Claude, OpenAI and Gemini do it, schema design that helps the model, the validation you still need, and how tool calling works under the hood. With an interactive demo of what each layer catches.
Evals for LLM Features: How to Know Your Prompt Change Didn't Break Anything
Build a test set from real data, pick the right grader for each check, compare runs case by case instead of by average, run evals in CI and keep watching in production. With an interactive eval diff where the score goes up and the feature gets worse.