Sub topic 8
Streaming for perceived latency
This chapter assumes you can call an LLM API from Python and know the split between prefill (the model reading your prompt) and decoding (the model producing output tokens one at a time). It builds on the latency chapter and the measurement chapter.
What streaming changes
Without streaming, the API returns nothing until the whole answer is finished. The user waits for prefill plus every decoded token. With streaming, the server sends tokens as they are produced, usually as server-sent events (a long-lived HTTP response that delivers small chunks).
Streaming does not make the model faster. Total generation time stays about the same. What changes is when the user sees the first words. A 10-second answer that starts appearing after 0.6 seconds feels much faster than a blank screen for 10 seconds.
Measure the two numbers
Time to first token (TTFT) is the delay before the first chunk arrives. It covers queueing and prefill, so it grows with prompt length. Total time adds the decoding time, which grows with output length. Wrap any stream to record both:
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}
def fake_stream():
time.sleep(0.5) # simulated queue and prefill
for word in "Streaming shows words as they are made".split():
time.sleep(0.1) # simulated decoding
yield word + " "
print(time_stream(fake_stream()))Replace fake_stream() with the iterator your provider's SDK returns when you enable streaming. A chunk is not always exactly one token, so treat the chunk count as approximate.
When streaming helps
Streaming fits interactive interfaces where a person reads the answer as it appears: chat, writing assistants, and code explanations. It adds little when:
- The caller is another program that needs the complete result, such as a batch job.
- The output is short, so there is little to show early.
- The output must be validated before anyone sees it, such as JSON that must parse or text that passes a safety check.
Common errors
- Buffering proxies. A reverse proxy or gateway may collect the response and send it all at once. Disable response buffering for streaming routes, then confirm that TTFT in the browser matches TTFT in your server logs.
- Missing token counts. Many APIs report usage only in the final chunk, and some require an option to include it. If you skip that chunk, your cost records will be wrong.
- Wasted generation after a disconnect. If the user closes the page, stop reading and close the connection. Otherwise you may keep paying for tokens nobody sees.
- Retrying mid-stream. A retry after a partial answer can duplicate text. Retry only before the first chunk, or discard the partial output and start over.
- Parsing partial structure. Do not parse half a JSON object. Collect the full text first, or use a parser designed for incremental input.
Exercise
A streamed answer has a TTFT of 0.8 s and a total time of 9 s. You shorten the prompt by half, and TTFT drops to 0.5 s. Total time barely changes. Why, and what would reduce total time?
Show answer
Prompt length affects queueing and prefill, which is what TTFT measures. Most of the 9 s is decoding, which depends on the number of output tokens. To cut total time, limit or shape the output (a lower max token limit, a more concise instruction, or a smaller model).