Streaming UX: making slow models feel fast
Why streaming changes perceived latency, how Server-Sent Events carry tokens from model to browser, the OpenAI-style chunk format, proxies that buffer, rendering partial Markdown, stopping generation, streaming tool calls and structured output, and a runnable server and client that measure time to first token.
By Sandip Maity, Applied AI Engineer
A local 14B model writing a 400-token answer at 30 tokens per second takes about 13 seconds. Shown all at once, that feels broken. Streamed, the first words appear in under a second and the user reads along while the rest arrives. Streaming does not make the model faster; it changes when the user sees progress, and for chat interfaces that is most of the experience.
#Two numbers the user feels
- Time to first token (TTFT): request to first visible text. Dominated by queueing and prefill, so it grows with prompt length (prefill and decode).
- Token rate: how fast text arrives after that. Anything faster than reading speed (roughly 5 to 8 tokens per second) feels fine for prose; code and agent loops want much more.
Without streaming the user experiences total time. With streaming they experience TTFT, then a steady flow.
Without streaming
With streaming
At 30 tok/s text arrives faster than most people read (about 6 tok/s), so after the first token the wait is barely noticed.
Streaming does not shorten generation. It moves the first visible words from the end of the wait to the start.
#How tokens reach the browser
- 1Model serveremits tokens as they are decoded
- 2Your backendrelays chunks, adds auth, logs, guardrails
- 3Proxy / CDNmust not buffer
- 4Browserparses events, renders incrementally
Most LLM servers (llama.cpp, vLLM, Ollama's OpenAI-compatible endpoint, hosted APIs) stream with Server-Sent Events (SSE): a long HTTP response with Content-Type: text/event-stream where each event is a data: line followed by a blank line. The OpenAI-style chat format sends JSON chunks with a delta and ends with data: [DONE]:
data: {"choices":[{"index":0,"delta":{"content":"Refunds "}}]}
data: {"choices":[{"index":0,"delta":{"content":"are "}}]}
data: [DONE]SSE is one-way (server to client), runs over plain HTTP, and reconnects easily. WebSockets are only worth it when the client also streams continuously, as in real-time voice (voice pipelines).
#A server and client you can run
The server streams a fake model's tokens with a 0.3 s "prefill" and 30 ms per token. The client measures TTFT and total time, then presses Stop after five tokens to show cancellation reaching the server.
llm_apps/streaming_sse.py · MIT licensed, on GitHub
"""Streaming LLM output with Server-Sent Events (SSE), standard library only.
A fake model emits tokens with a fixed prefill delay and a per-token delay. The server streams them as SSE
`data:` lines in the OpenAI chat-completions chunk shape and ends with `data: [DONE]`. The client parses the
stream, measures time to first token (TTFT) against total time, and shows that closing the connection early
stops generation on the server (so you stop paying for tokens nobody reads).
"""
import http.client
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PREFILL_S, PER_TOKEN_S = 0.30, 0.03
TOKENS = ("Refunds are accepted within 7 days of purchase, as long as less than 20% of the course "
"has been opened. Duplicate purchases are refunded at any time.").split(" ")
generated = {"count": 0}
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a): # keep the demo output clean
pass
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length", 0)))
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("X-Accel-Buffering", "no") # tell nginx-style proxies not to buffer the stream
self.end_headers()
time.sleep(PREFILL_S)
try:
for i, tok in enumerate(TOKENS):
chunk = {"choices": [{"index": 0, "delta": {"content": tok + (" " if i < len(TOKENS) - 1 else "")}}]}
self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
self.wfile.flush()
generated["count"] += 1
time.sleep(PER_TOKEN_S)
self.wfile.write(b"data: [DONE]\n\n")
except (BrokenPipeError, ConnectionResetError):
pass # client went away: stop generating
def stream(port, stop_after=None):
conn = http.client.HTTPConnection("127.0.0.1", port)
t0 = time.perf_counter()
conn.request("POST", "/v1/chat/completions", body=json.dumps({"stream": True}), headers={"Content-Type": "application/json"})
resp = conn.getresponse()
ttft, text, n = None, [], 0
for raw in resp:
line = raw.decode().strip()
if not line.startswith("data: "):
continue
data = line[6:]
if data == "[DONE]":
break
delta = json.loads(data)["choices"][0]["delta"].get("content", "")
if ttft is None:
ttft = time.perf_counter() - t0
text.append(delta); n += 1
if stop_after and n >= stop_after:
conn.close() # user pressed Stop
break
return ttft, time.perf_counter() - t0, "".join(text), n
if __name__ == "__main__":
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
port = srv.server_address[1]
ttft, total, text, n = stream(port)
print(f"full answer : {n} tokens, TTFT {ttft:.2f} s, total {total:.2f} s")
print(f" without streaming the user would stare at a blank screen for {total:.2f} s")
generated["count"] = 0
ttft, total, text, n = stream(port, stop_after=5)
time.sleep(0.3)
print(f"stopped : client read {n} tokens, server generated {generated['count']} of {len(TOKENS)} before noticing")
srv.shutdown()$ python3 streaming_sse.py
full answer : 27 tokens, TTFT 0.31 s, total 1.22 s
without streaming the user would stare at a blank screen for 1.22 s
stopped : client read 5 tokens, server generated 6 of 27 before noticingThe server notices the closed connection on its next write, so it generates a token or so beyond what the client read and then stops. With a real model server, make sure cancellation propagates all the way down: your backend must close its upstream request when the browser disconnects, or the GPU keeps working for nobody.
#Production checklist
- Disable buffering on every hop: reverse proxies (
X-Accel-Buffering: nofor nginx), serverless platforms and CDNs. Do not gzip event streams. - Send headers early and a first byte quickly; some load balancers close idle connections, so send a comment line (
: keep-alive) every 15 to 30 s during long tool calls. - Set timeouts per phase: a TTFT timeout and an idle-between-tokens timeout, rather than one total timeout that kills long answers (timeouts and retries).
- Propagate cancellation from the browser to the model server.
- Do not retry a half-streamed answer blindly; the user has already read part of it. Show an error and offer to continue.
- Log the whole answer at the end of the stream, plus TTFT, tokens and the finish reason.
#Rendering partial output
- Markdown: a half-written code fence or table can break the page. Use a renderer that tolerates incomplete input, or temporarily close open fences before each render.
- Throttle renders to animation frames (about 60 per second) rather than one per token, or long answers become slow to display.
- Keep scroll position sensible: follow the bottom only if the user has not scrolled up.
- Show state: "thinking", "searching documents", "calling tool" events between text chunks tell users the app is working.
#Streaming tool calls and structured output
Tool calls stream too: the function name arrives first and the JSON arguments arrive in fragments that must be concatenated before parsing. Do not execute a tool until its arguments are complete and valid.
For structured output (structured output), you can show progress by parsing partial JSON with a tolerant parser, but validate only the final object. With reasoning models, decide whether to stream the thinking (often hidden or summarised) or only the answer.
#Common mistakes
- Testing locally, where nothing buffers, then shipping behind a buffering proxy.
- One total timeout that kills long but healthy streams.
- Not cancelling upstream when the user leaves.
- Re-rendering the entire Markdown document on every token.
- Executing a streamed tool call before its arguments are complete.
#Exercises
- Change
PREFILL_Sto 2.0 andPER_TOKEN_Sto 0.01. Which number dominates the experience now, and what would you show the user during the wait? - Add an
event: statusline before the first token that says "searching documents", and make the client print it. - Put the server behind a local nginx with default settings, observe the buffering, then fix it.
Quick quiz
+10 XP per correct answer, +25 XP for a perfect score
1. An answer takes 1.3 s in total and the first token arrives at 0.3 s. What does streaming change?
2. Tokens arrive in bursts after you deploy behind a reverse proxy. The likely cause?
3. The user presses Stop. What should happen on the server?
4. How does an OpenAI-compatible stream mark the end?
5. Why is rendering streamed Markdown tricky?
Up next · 14 min · Pro, first part free
Cost and latency budgets for LLM features
Turn a feature into numbers before you build it: tokens per request, calls per request, cost per thousand requests and per month, latency as the sum of sequential calls, prompt caching, routing to a small model, agent cost growth, and a runnable calculator comparing five designs.
Continue →Found this useful?
Send it to someone who is learning the same thing.