Sub topic 8
Streaming for Perceived Latency
This chapter assumes you can call an LLM API with chat-style requests, read basic Python, and understand HTTP and JSON. It also assumes you have read the earlier chapters on latency anatomy and measurement. You should know that total latency splits into queueing, prefill, and decoding, and that time to first token (TTFT) is the delay before any output appears.
What streaming changes and what it does not
Without streaming, the API holds the response until the model finishes. The user sees nothing for the whole duration, then the full text appears at once. With streaming, the server sends the output in small pieces as the model produces them. The user starts reading after the TTFT, not after the total time.
Streaming changes when the user sees output. It does not change how long the model takes to generate it. The total generation time stays about the same, and sometimes it grows slightly because of per-chunk overhead. Streaming also does not reduce token counts or price. A streamed request costs the same as a non-streamed one with the same input and output.
This makes streaming a tool for perceived latency, the delay a person feels, and not for real latency, the time until the work is complete. Consider a response of 400 output tokens that decodes at 50 tokens per second, with a TTFT of 0.6 seconds:
| Mode | User first sees text | Response complete |
|---|---|---|
| Non-streaming | about 8.6 s | about 8.6 s |
| Streaming | about 0.6 s | about 8.6 s |
The arithmetic is TTFT + tokens / rate = 0.6 + 400 / 50 = 8.6 seconds. Streaming turns an 8.6-second blank wait into a 0.6-second wait followed by readable progress. People read at roughly 4 to 8 tokens per second, so a model decoding at 50 tokens per second is already faster than the reader. The user never waits for text after the first moments.
When streaming helps and when it does not
Streaming fits when a human reads the output as it arrives. Chat interfaces, writing assistants, and code explanation panels are typical cases.
Streaming gives little or no benefit in these cases:
- Machine consumers. If a program needs the complete JSON object before it can act, partial output is not usable. The program waits for the end anyway.
- Short outputs. A 10-token classification label finishes about as quickly as its first chunk would arrive.
- Post-processing that needs the full text. Moderation checks, format validation, and citation checks often need the complete answer. Showing unchecked partial text can display content you would have blocked.
- Batch jobs. Nobody watches these, so perceived latency does not matter. Use the batching approach from a later chapter.
Streaming helps most when the output is long and the TTFT is small compared with total time. If your baseline shows that prefill dominates (a very long prompt, a long queue), streaming cannot hide it, because no chunk can arrive before prefill ends. In that case, trim the prompt or use prompt caching first.
Measuring a stream
Your baseline should record TTFT and total time as separate numbers. A streamed response lets you measure both from the client. This function wraps any iterable of chunks:
import time
def time_stream(chunks):
"""Measure time to first chunk and total time for any iterable of streamed chunks."""
start = time.perf_counter()
first = None
count = 0
for _ in chunks:
if first is None:
first = time.perf_counter() - start
count += 1
total = time.perf_counter() - start
return {"ttft_s": first, "total_s": total, "chunks": count}Start the timer immediately before the request is sent, not before the generator is created. Many client libraries create the stream lazily, so the network call happens on the first iteration. If you build the iterator earlier and start the clock later, or the reverse, your TTFT is off.
You can derive a decode rate from the result: roughly output_tokens / (total_s - ttft_s). This is an approximation. A chunk is not always one token. Some providers batch several tokens into one event, so use the provider's reported token count and not the chunk count.
Consuming a stream correctly
Most APIs stream with server-sent events (SSE). This is a plain HTTP response that stays open, where the server writes lines starting with data: and the client reads them as they arrive. Each event holds a small JSON object with a text fragment, called a delta. Client libraries parse this for you and give you an iterator.
The usual pattern is to print or forward each delta immediately and also collect the pieces so you have the full text at the end:
def consume(stream, on_text):
"""Forward each text fragment as it arrives and return the full text.
`stream` is any iterable of strings (text deltas).
`on_text` is called with each fragment, for example to update a UI.
"""
parts = []
for delta in stream:
if delta:
on_text(delta)
parts.append(delta)
return "".join(parts)
# Example with a fake stream so the code runs without an API key.
fake_stream = iter(["Stream", "ing ", "shows ", "text ", "early."])
text = consume(fake_stream, lambda piece: print(piece, end="", flush=True))
print()
print(len(text))With a real client, you adapt the provider's event objects to a plain iterator of strings. The shape differs between providers, so check your SDK's documentation for where the text delta sits in each event.
Edge cases and failure modes
Usage data arrives at the end. Token counts are often only known when the stream finishes. Some APIs send them in a final event, and some require you to opt in with a request option. If your cost tracking reads usage from the response, confirm that your streaming code path still records it. A common bug is a dashboard that undercounts cost because streamed requests logged zero tokens.
Mid-stream failures. A connection can drop after half the answer. The HTTP status was already 200 when the stream began, so the error shows up as a broken connection or an error event, not a status code. Decide what to do in advance:
- Show the partial text with a clear "response interrupted" state.
- Retry the whole request, discarding the partial text. Retrying costs the input tokens again and some output tokens.
- Never silently present the partial text as complete.
You are usually billed for the tokens generated before the failure, so frequent mid-stream drops have a cost.
Cancellation. If the user closes the tab or presses stop, close the connection. Many providers stop generating when the connection closes, which saves output tokens. If your server keeps reading the stream after the client has gone, you pay for text nobody sees. Propagate cancellation from the browser to your server to the provider.
Buffering proxies. Reverse proxies, load balancers, and some CDNs buffer responses by default. The model may stream, but the user still sees everything at once because an intermediate layer holds the chunks. If TTFT measured at the provider is good but TTFT measured in the browser is bad, look for buffering. Disable response buffering for streaming routes, and check any gateway timeouts that assume short responses.
Partial structured output. A half-received JSON object does not parse. If you stream structured data, either wait for the end, or use a format that is readable in pieces, such as one JSON object per line, or send the human-readable text and the structured data as separate fields.
Rendering partial Markdown. An unclosed code fence or a half-written link can make a UI flicker or render incorrectly. Many chat UIs use a renderer that tolerates incomplete Markdown, or they buffer until a line or word boundary.
Guardrails and moderation. If every answer must be checked before display, streaming conflicts with the check. Options include checking in windows (for example every sentence) and cutting the stream if a window fails, or not streaming for the sensitive route.
Decision criteria
Use streaming when all of these are true:
- A person reads the output as it arrives.
- The output is long enough that the full wait would be noticeable (a few seconds or more).
- You do not need the whole answer before showing any of it.
- Your infrastructure passes chunks through without buffering.
Skip it, or stream only part of the flow, when a machine consumes the output, when the response is short, or when full-text validation must come first.
Summary
Streaming reduces the delay a person feels by showing output after the TTFT instead of after the full generation. It does not change cost, token counts, or the time the model needs to finish. Measure TTFT and total time separately, record usage on the streamed path, handle mid-stream failures and cancellation, and check that no proxy buffers the chunks.
Exercise
A request has a TTFT of 1.2 seconds and 300 output tokens decoded at 60 tokens per second. (a) How long until the user sees the first text, and how long until the response is complete, with streaming? (b) Without streaming? (c) Your browser-side TTFT is 6 seconds even though the provider reports 1.2 seconds. What is the most likely cause and what do you check?
Show answer
(a) The first text appears at 1.2 s. The response completes at 1.2 + 300 / 60 = 6.2 s. (b) Without streaming, the user sees nothing until 6.2 s, when everything appears at once. Total time is the same. (c) An intermediate layer, such as a reverse proxy, load balancer, or CDN, is probably buffering the stream. Check the proxy's response buffering settings for the streaming route and any gateway timeouts, then re-measure TTFT in the browser.
Exercise
Your cost dashboard shows streamed requests costing nothing, though the provider's invoice includes them. Give a likely reason and a fix.
Show answer
Token usage is often reported only in the final event of a stream, or only when you enable a usage option on the request. The streaming code path is probably not reading or logging it. Enable the usage option if the API requires one, read the usage from the final event, and record it with the same fields as non-streamed requests.