Streaming Responses
Send tokens to the user as they are generated so a 20-second answer feels instant, and handle the events and errors that come with it.
Beginner · about 5 hours · difficulty 3/5
Learn first: Messages APIs and Provider SDKs, Async I/O and Concurrency
Without streaming, the user stares at a spinner until the whole answer is done. With streaming, the first words appear within a second or two. Time to first token is the latency number users actually feel.
How it works
Providers stream over Server-Sent Events: a long-lived HTTP response delivering small events such as message start, content delta (a few characters or tokens), tool call deltas, and message stop with final usage. SDKs wrap this in iterators or event handlers.
Building a streaming path end to end
- Your server calls the model with streaming enabled.
- It forwards deltas to the browser, typically via SSE, a streaming fetch response or WebSockets.
- The client appends text as it arrives and renders markdown progressively.
Things that go wrong
- Proxies and buffering: some reverse proxies and serverless platforms buffer responses, killing the streaming effect. Disable buffering.
- Mid-stream errors: the connection can fail after partial output. Decide whether to retry, resume or show the partial answer with an error.
- Tool calls and structured output arrive in fragments; accumulate them before parsing.
- Cancellation: when the user clicks stop, abort the upstream request so you stop paying for tokens.
- Usage totals usually arrive in the final event; log them there.
Good enough to move on
You can stream a response from a model through your own backend to a browser page, support a stop button, and log final token usage.
Key concepts
- Stream events and deltas
- Time to first token
- Forwarding streams via SSE
- WebSockets
- Cancellation and abort signals
- Mid-stream error handling
- Proxy buffering issues
Mini project
Create a FastAPI or Express endpoint that streams a model response over SSE to a simple HTML page, with a working stop button that cancels the upstream request.
Check yourself
Why does cancelling the model request on the server matter even after the user has closed the browser tab?
Free resources
- Anthropic docs: streaming messages (Anthropic)
- OpenAI docs: streaming (OpenAI)
- MDN: Server-sent events (MDN)