Module 7 · AI infrastructureLesson 85 of 885 minIntermediate
Streaming inference
Send each token to the user the moment it's generated. The total time is the same, but the wait feels far shorter.
Try it
Compare "time to first word" in the two tabs. Notice the total time barely changes.
An LLM produces its answer one token at a time, over several seconds. Waiting for the end before sending anything wastes that time: the user stares at a spinner.
Streaming sends each token (or small group of tokens) as soon as it's generated.
Two latency numbers
- Time to first token (TTFT): from sending the request to seeing the first word. Driven by queueing and prefill. This is what makes an app feel responsive.
- Inter-token latency (or tokens per second): how fast text flows after that. People read about 5 to 10 tokens per second, so anything faster feels instant.
How it's done
- Server-Sent Events (SSE): a normal HTTP response that stays open and sends
data:lines as tokens arrive. One-way, simple, works through most infrastructure. Most LLM APIs use it. - WebSockets: two-way, useful when the client also sends events mid-stream (like interrupting).
- gRPC streaming between internal services.
Things to get right
- No buffering: reverse proxies, CDNs and some frameworks buffer responses by default and destroy streaming. Disable it on those routes.
- Cancellation: if the user stops or leaves, cancel the generation on the server too, or you pay for tokens nobody reads.
- Errors mid-stream: you've already sent
200 OK, so errors must be sent as stream events. - Partial content: if you post-process output (formatting, safety checks, structured data), decide how to handle half-finished text.
- Timeouts: long streams can exceed default idle timeouts on load balancers.