Streaming responses (SSE)

In one sentence

Send tokens to the user as they are generated, over Server-Sent Events, so they start reading at time-to-first-token instead of waiting for the whole answer; total time is unchanged.

Analogy: A waiter bringing each dish as it leaves the kitchen instead of holding the whole order until dessert is ready.

The server relays each delta as an SSE event; when the client leaves, it must cancel the upstream call or keep paying for tokens.

How it works

  • Decode runs ~50–100 tokens/s, so a 500-token answer is 5–10 s of blank screen without streaming.
  • JSON and tool-call arguments arrive as fragments: accumulate the deltas and parse when the block ends.
  • When the client disconnects, abort the upstream call, or you keep paying for tokens nobody reads.
  • nginx, CDNs and gzip middleware may hold chunks: turn off buffering with proxy_buffering off or X-Accel-Buffering: no.
  • The 200 status is already sent, so mid-stream errors travel as in-band events.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your SSE chat endpoint streams token by token on your laptop. In production behind nginx, the whole answer appears at once after ~7 s. TTFT measured at the app server is ~400 ms. Most likely cause?

Go deeper

Full explanation

Streaming returns the answer token by token while the model decodes, instead of one JSON body at the end. LLM APIs (OpenAI, Anthropic, vLLM's OpenAI-compatible server) use Server-Sent Events (SSE): one long-lived HTTP response with Content-Type: text/event-stream, where each chunk is a data: {...} line followed by a blank line.

Why it matters: decode is slow and sequential. At ~50–100 tokens/s, a 500-token answer takes 5–10 s. Users judge speed by time to first token (TTFT), usually a few hundred ms, and they read slower than the model writes, so after the first token they rarely wait again. See Prefill vs decode and Latency metrics: TTFT, TPOT, throughput.

What gets harder:

  • Partial structure: JSON and tool-call arguments arrive as fragments. Accumulate deltas and parse when the block ends.
  • Cancellation: when the client disconnects, abort the upstream call or you keep paying for tokens nobody reads.
  • Buffering: nginx, CDNs, load balancers and gzip middleware may hold chunks. Disable it (proxy_buffering off, X-Accel-Buffering: no).
  • Errors mid-stream: the 200 status is already sent, so errors travel as in-band events.
  • Moderation: text is shown before you can check it. Buffer by sentence, or don't stream high-risk output.

SSE is one-way and plain HTTP; use WebSockets only when the client must also talk mid-stream, as in voice.

Code FastAPI SSE relay with cancellation
pythonFastAPI SSE relay with cancellation
import json
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI

MODEL = "gpt-4.1-mini"  # any chat model
client = AsyncOpenAI()
app = FastAPI()

def sse(obj: dict, event: str = "message") -> str:
    return f"event: {event}\ndata: {json.dumps(obj)}\n\n"

@app.post("/chat")
async def chat(req: Request):
    body = await req.json()
    async def events():
        stream = None
        try:
            stream = await client.chat.completions.create(
                model=MODEL, messages=body["messages"], stream=True)
            async for chunk in stream:
                if await req.is_disconnected():  # user hit Stop
                    break                          # stop paying for tokens
                delta = chunk.choices[0].delta.content if chunk.choices else None
                if delta:
                    yield sse({"text": delta})
            yield sse({}, "done")
        except Exception:
            yield sse({"msg": "upstream failed"}, "error")  # 200 already sent
        finally:
            if stream:
                await stream.close()  # closes the upstream HTTP connection

    return StreamingResponse(events(), media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
Real example

A support assistant returns ~400-token answers at ~60 tokens/s: ~7 s of blank screen, and users retry or leave. With SSE, the first words appear at ~400 ms TTFT and the answer fills in faster than people read. After deploy behind nginx, though, the whole answer still arrives at once at the 7 s mark: proxy_buffering was on. One header (X-Accel-Buffering: no) fixes it. Wiring the Stop button to abort the upstream call also stops billing for answers users already abandoned.

Trade-offs +3 · −3

+ You gain

  • Perceived latency drops from total generation time to TTFT.
  • Users can stop a wrong answer early, which saves output tokens.
  • SSE is plain HTTP: works through standard proxies and auth once buffering is off.

− You pay

  • Partial JSON and tool-call fragments complicate parsing and validation.
  • Output is visible before it can be moderated or validated.
  • Long-lived connections hit idle timeouts, buffering proxies and per-origin connection limits.

Use it when

Any human-facing generation longer than a sentence or two: chat, assistants, summaries, code generation.

Avoid it when

Machine-to-machine calls that need a complete, validated object, short classifications, batch jobs, or high-risk output that must be checked before anyone sees it.

Numbers to know 4
  • Nielsen's response-time limits: ~0.1 s feels instant, ~1 s keeps the flow of thought, ~10 s loses attention. Aim for TTFT under ~1 s.
  • Rule of thumb: hosted models decode ~50–100 output tokens/s per stream, so a 500-token answer is 5–10 s unstreamed.
  • Browsers allow ~6 HTTP/1.1 connections per origin; open SSE streams count against it, so serve them over HTTP/2.
  • AWS ALB's default idle timeout is 60 s: send heartbeat comments during long pauses such as reasoning.
Common pitfalls 4
  • A buffering proxy, CDN or gzip middleware delivers the whole stream at the end, and it works fine locally.
  • Not aborting upstream on client disconnect: you pay for every abandoned generation.
  • Calling json.loads on each chunk, or running a tool on partial arguments. Accumulate per tool-call index, act at the end.
  • Using EventSource for chat: it only does GET without custom headers. Use fetch with a ReadableStream for POST bodies and auth.
Interview questions 3

Answer out loud first, then reveal.

Streaming doesn't make the model any faster. Why bother?Show answer

Right, total latency is the same or slightly worse. What changes is perceived latency: users start reading at TTFT, a few hundred ms, instead of staring at a spinner for 5 to 10 seconds, and since they read slower than the model decodes they rarely wait again. It also lets them cancel early, which saves tokens. The costs are partial JSON, errors after a 200, moderating text already shown, and infra that buffers. For machine-to-machine calls that need a full object, I don't stream.

How do you moderate output that you're streaming?Show answer

I pick by risk. Low risk: stream raw, run an async check on the full text and retract the message if it fails. Medium risk: buffer by sentence, release each sentence once a fast classifier passes it, which costs about one sentence of delay. High risk, like regulated advice or minors: don't stream the visible answer; generate, check, then show, with a progress indicator meanwhile. Input guardrails run before generation in every case, so output checks only handle what slips through.

How do you handle tool calls in a streamed response?Show answer

They arrive as deltas. OpenAI sends the function name first and the arguments as string fragments keyed by tool-call index; Anthropic sends input_json_delta events per content block. I accumulate per index and only parse and execute when the block or message finishes: finish_reason tool_calls, or content_block_stop. Executing on partial arguments is a correctness bug. For the UI, I show 'searching...' as soon as the tool name arrives, which keeps the perceived-latency win.