Streaming Responses
Token streams that improve perceived latency via SSE or WebSockets.
In plain words
Instead of waiting for the AI to finish the whole answer, you see the words appear as it writes them.
Think of it like…
A restaurant that brings each dish as it is ready instead of delivering the whole meal at once: the total time is similar, but the table stops staring at an empty plate.
Where you’ve seen it
A chat answer of 420 tokens takes 0.6 s to first token plus 2.8 s of decoding (150 tokens per second), 3.4 s in total. Without streaming the user sees nothing for 3.4 s; with streaming, text begins at 0.6 s, and the whole answer is on screen by 3.4 s, long before the user finishes reading it (420 tokens is about 315 words, roughly 80 seconds at a typical 240 words a minute). The service handles 500 requests per second, so by Little's law it keeps 500 × 3.4 = 1,700 streams open on average, which pushes the team to async I/O workers rather than a thread per connection. Behind nginx the first deployment showed text arriving in one burst at the end because the proxy buffered the response; turning off proxy buffering for the route (proxy_buffering off and an X-Accel-Buffering: no header) fixed it, and a client disconnect now aborts the upstream request so cancelled generations stop billing.
Words you’ll hear
- Server-Sent Events (SSE)
- A one-way, text-based stream from server to browser over HTTP with automatic reconnection support.
- Chunk / delta
- A small piece of generated text (often a few tokens) sent as one event.
- Backpressure and buffering
- How slow clients and intermediate proxies hold or delay streamed data.
- Cancellation
- Aborting generation upstream when the client disconnects or presses stop.
Visual diagram
Theory & deep dive
Transports and implementation
SSE frames each message as data: ... followed by a blank line over a normal HTTP response with Content-Type: text/event-stream. It is simple, works through most proxies, supports automatic reconnect with an event id, and is enough when the client only listens. Because EventSource can only send GET requests without custom headers, many apps use fetch with a ReadableStream to POST the prompt and parse the SSE stream manually. WebSockets provide a full-duplex channel useful for voice, live interruption ("barge-in"), multi-user sessions and sending audio or events upstream, at the price of more state (connection management, heartbeats, reconnection) and some infrastructure constraints. Plain chunked HTTP or HTTP/2 streams are also used by gRPC-style APIs.
On the server, request stream: true from the model API, iterate the chunks as an async generator and forward each one immediately without accumulating the whole response. Send a small first event (headers and a request id) quickly, include periodic heartbeats (a comment line every 15 to 30 seconds) to keep idle connections alive through load balancers, and finish with a clear done event that carries usage (token counts) and the finish reason. For tool calls and structured output, accumulate partial argument deltas and parse only when complete: a half-received JSON object isn't valid.
event: start with a request id, then many data: {"delta": "Your"} chunks, a : ping comment every 20 s, and finally event: done with {"finish_reason": "stop", "input_tokens": 3100, "output_tokens": 420}.
Operating streams: errors, cancellation, safety and scale
Once the first byte is sent the HTTP status is fixed at 200, so failures mid-stream (provider timeout, content filter, internal error) must be signalled in-band with an error event, and the client should show partial text plus a retry option. Make clients resilient: handle network drops, de-duplicate on reconnect using event ids and don't append the same chunk twice. Render partial markdown carefully (an unclosed code fence or table flickers), escaping HTML to avoid injection, and consider smoothing output to a steady cadence because token bursts look jittery.
Implement cancellation: when the client disconnects or presses Stop, abort the upstream request promptly, otherwise the model keeps generating and you pay for tokens nobody sees. For safety, moderate output incrementally (check windows of text) or buffer enough to evaluate before showing; streaming makes it harder to retract text already displayed, so high-risk products may stream only after a first-pass check or label partial output. At scale, each stream holds a connection and server resources for its whole duration (Little's law: concurrent streams = arrival rate × duration), so use async servers, raise file-descriptor limits, apply per-user concurrency limits and make sure load balancers have long idle timeouts and don't buffer. Measure TTFT, inter-token latency, stream completion rate and abort rate.
500 requests per second × 3.4 s per stream = 1,700 concurrent connections. If average duration rises to 8 s during provider slowness, concurrency becomes 4,000, which can exhaust workers or file descriptors even though the request rate hasn't changed.
How it works, step by step
Step 1 of 41. Stream from the model
Call the model API with streaming enabled and iterate chunks with an async generator.
- Usage
- in the final event
When to use it & trade-offs
What it is
Streaming sends the model's output to the user as it is generated, token by token or in small chunks, instead of waiting for the full completion. The common transports are Server-Sent Events (SSE), a one-way text stream over plain HTTP that browsers consume with EventSource or fetch, and WebSockets, a two-way channel suited to voice, interruption and collaborative apps. Streaming doesn't make generation faster; it makes the response feel faster because the first words appear after the time to first token rather than after the whole answer is done.
Why it matters: LLM answers take seconds, and a blank screen for 3 to 10 seconds feels broken, while text that begins flowing within a second feels responsive and lets the user start reading, interrupt or abandon early. Streaming also changes backend design: long-lived connections, proxy buffering, mid-stream errors, cancellation (so you stop paying for tokens nobody reads) and moderation of partial output all need deliberate handling.
When to reach for it
- Chat and writing assistants
- Any answer that takes more than about a second to generate
- Interactive agents showing progress
When to avoid or be careful
- Letting proxies buffer the stream
- Continuing generation after the client disconnects
- Parsing partial JSON before it's complete
Streaming transports
Strengths: Simple, works over HTTP, auto-reconnect.
Watch out: One direction only; proxy buffering pitfalls.
Strengths: Full duplex, low overhead per message.
Watch out: More connection state and infrastructure work.
Strengths: Simplest; easy to validate before showing.
Watch out: Long blank wait for users.
Interview signals & numbers to know
When this topic comes up
- “The whole answer appears at once”
- “Users stare at a spinner”
- SSE versus WebSocket
- Cancel generation on disconnect
- Perceived latency
Benchmarks & rules of thumb
- 0.6 s vs 3.4 s
- time to first visible text vs full answer in the example
- 1,700
- concurrent streams at 500 req/s × 3.4 s
- 15 – 30 s
- typical heartbeat interval
Common mistakes & follow-ups
Common interview mistakes
- Seeing a burst of text at the end because nginx buffered the response.
- Returning a 200 and then silently dropping the stream on error.
- Forgetting that open streams consume workers for their full duration.
Likely interviewer follow-ups
- SSE or WebSocket for a chat UI, and why?
- How do you stop paying when a user closes the tab?
- How do you stream tool calls and structured output?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Streaming Responses with generative AI interview Q&A and hands-on practice.