Streaming and AI UX: responses that don't bore
How to implement LLM streaming with SSE, improve UX, and stop users from leaving while waiting for an answer.
Table of Contents
Imagine you order a coffee and the barista disappears behind the machine for 40 seconds. You do not know if they are making your coffee or if they went home. In the end they hand you the perfect coffee, but you are no longer there: you left for another coffee shop.
That is how a user feels in front of an LLM that does not stream. The answer may be excellent, but if it takes 30 seconds to appear, the user closes the tab. The human brain does not tolerate uncertainty: if it sees no progress, it assumes something broke. Streaming does not make the answer faster; it makes it more tolerable.
The problem: perceived latency
An LLM generates tokens one by one, but most APIs wait until the entire response is finished before sending it. If the response has 500 tokens and the model generates 50 tokens per second, the user waits 10 seconds staring at a blank screen.
Real latency does not change with streaming: the model still takes the same time to generate. What changes is perceived latency. Seeing text appear word by word tells the user “it is working, be patient.” It is the difference between a barista who shows you the coffee being made and one who disappears.
How streaming works
The model generates tokens sequentially. With streaming, each token (or group of tokens) is sent to the client as soon as it is generated, without waiting for the end. The standard protocol is Server-Sent Events (SSE): an HTTP connection where the server sends text events as they occur.
SSE vs WebSockets vs fetch streaming
- SSE: unidirectional (server to client), automatic reconnection, works over standard HTTP. Ideal for LLMs, where the flow is unidirectional.
- WebSockets: bidirectional, more complex, useful if you need to send data to the server during generation (cancellation, adjustments). Overkill for most cases.
- Fetch streaming: uses the
fetchAPI withReadableStream. More flexible than SSE (allows custom headers, POST), but requires more code. The preferred option when you need to send a large body or authentication.
For most chat applications, SSE is enough. If you need to send a complex body (long context, files), use fetch streaming.
Backend: implementing streaming in Python
With FastAPI and OpenAI, streaming reduces to an async generator:
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
app = FastAPI()
client = AsyncOpenAI()
@app.post("/chat")
async def chat(prompt: str):
async def generate():
stream = await client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in stream:
content = chunk.choices[0].delta.content
if content:
yield f"data: {content}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(generate(), media_type="text/event-stream")
Three details that matter:
media_type="text/event-stream"is mandatory for SSE. Without it, the browser does not interpret the stream.- Each chunk must end with
\n\n. It is the SSE event delimiter. Without it, the client does not receive the event. - The generator must be async (
async def generate). If you use a sync generator with an async client, you block the event loop and lose the benefit of streaming.
Frontend: consuming the stream
With native SSE, consumption is simple:
const source = new EventSource("/chat?prompt=" + encodeURIComponent(prompt));
source.onmessage = (event) => {
if (event.data === "[DONE]") {
source.close();
return;
}
appendToChat(event.data);
};
source.onerror = () => {
source.close();
showError("Connection lost");
};
With fetch streaming (more flexible, allows POST):
async function streamChat(prompt) {
const response = await fetch("/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value, { stream: true });
// SSE parses "data: ..." lines
for (const line of text.split("\n")) {
if (line.startsWith("data: ") && line !== "data: [DONE]") {
appendToChat(line.slice(6));
}
}
}
}
UX: what makes streaming work
Technical streaming is only half. The other half is user experience. A poorly implemented stream is worse than no stream.
“Thinking” indicator
Before the first token, show an indicator that the system is processing. Without it, the user does not know if their message was sent. A spinner, three animated dots, or a blinking cursor is enough.
Auto-scroll
New text should keep the scroll at the bottom. But if the user scrolled up to read something earlier, do not force the scroll. Detect if the user is at the bottom; if so, auto-scroll; if not, let them read.
function autoScroll(container) {
const isAtBottom =
container.scrollHeight - container.scrollTop - container.clientHeight < 50;
if (isAtBottom) {
container.scrollTop = container.scrollHeight;
}
}
Cancellation
The user must be able to cancel generation. A “Stop” button that closes the SSE connection or aborts the fetch. Without this, the user is trapped waiting for a response they no longer want.
const controller = new AbortController();
fetch("/chat", { signal: controller.signal, ... });
// To cancel:
controller.abort();
Incremental markdown rendering
If the response includes markdown (bold, lists, code), rendering it token by token is problematic: an incomplete ** shows as stray asterisks. Solutions:
- Render only at the end: accumulate the full text and render markdown when finished. Loses the visual streaming effect, but text still appears.
- Render incrementally with debounce: every N tokens, re-render the accumulated markdown. Balance between smoothness and correctness.
- Use a tolerant parser: libraries like
markedorremarkhandle incomplete markdown reasonably well.
Code blocks
Code blocks are the hardest case. An incomplete code block looks bad and can confuse the user. Best practice: show code as plain text while generating, and apply syntax highlighting when the block closes (detect the closing triple backtick).
Time to first token (TTFT)
Time to first token is the most important UX metric. A TTFT of 2 seconds feels instant. A TTFT of 10 seconds feels broken, even if subsequent streaming is fast. Optimize TTFT by reducing prompt size and using faster models for the first token.
Common mistakes that ruin UX
- No loading indicator before the first token. The user does not know if their message was sent.
- Aggressive auto-scroll. Forces scroll even when the user is reading something above.
- No cancellation. The user is trapped.
- Rendering markdown token by token. Produces stray asterisks and broken code.
- Not handling connection errors. If the stream drops, the user sees incomplete text with no explanation.
- Ignoring TTFT. A stream that takes 10 seconds to start does not feel like streaming.
- Buffering in proxies. Nginx, Cloudflare, and other proxies can buffer the stream, eliminating the effect. Configure
X-Accel-Buffering: noandCache-Control: no-cache.
When NOT to stream
- Short responses (under 50 tokens). Streaming overhead is not justified; the response appears almost instantly.
- Classification or extraction tasks. The user does not need to see the process; only the result.
- Internal APIs with no end user. If the consumer is another service, streaming adds complexity without benefit.
- Environments with proxies that do not support SSE. If you cannot disable buffering, streaming will not work.
Checklist before putting streaming in production
- First token appears in under 2 seconds (TTFT).
- There is a loading indicator before the first token.
- The user can cancel generation.
- Scroll is automatic only if the user is at the bottom.
- Markdown renders tolerantly to incomplete text.
- Code blocks are highlighted on close, not during generation.
- Connection errors are handled and shown to the user.
- Proxies are configured not to buffer (X-Accel-Buffering: no).
- TTFT and total generation time are measured.
Streaming does not make your model faster. It makes your user more patient. And a patient user is a user who does not close the tab.
Related articles
By relevance
Guardrails and LLM security: prompt injection, jailbreaks, and defenses
Prompt injection, jailbreaks, and LLM defenses: why guardrails fail and how to design systems that resist manipulation.
AI costs in production: tokens, caching, and model routing
How to control LLM spend in production: tokens, prompt caching, model routing, and metrics that prevent surprises.
Go 1.26 Full-Stack Notes App: SolidJS, Auth, Hexagonal Architecture & DDD from Zero
Build a full-stack notes app in Go 1.26 with SolidJS, JWT auth, and Hexagonal Architecture. Step-by-step from zero to production with DDD, TDD, and BDD.
Go 1.26 Full-Stack TODO: SolidJS + Embed + Hexagonal Architecture
Build a full-stack TODO app with Go 1.26, SolidJS, and go:embed. Hexagonal Architecture, DDD, TDD, BDD, SQLite, query params, PATCH, env vars, httpie. Zero to production.