Streaming LLM Responses in a Web App: SSE, Tokens and UX Patterns
Streaming shows tokens as the model writes them, so users read while generation runs. Learn the SSE pipeline, token handling, cancellation and UX patterns.
By Galactic News Editorial · Published 2026-11-22T22:28:13+00:00 · Updated 2026-11-22T22:28:13+00:00
Streaming LLM Responses in a Web App: SSE, Tokens and UX Patterns
Streaming LLM responses in a web app means showing text as the model produces it. The user starts reading while generation is still running. The model does not get faster. The page feels faster because text appears as soon as it exists. This guide covers the pipeline: server-sent events, token handling, cancellation, and the interface patterns that make streaming feel smooth.
Without streaming, a long reply takes many seconds to arrive as one response. Users stare at a spinner. With streaming, the first tokens arrive quickly and the user reads along. That difference in perceived latency is why every serious chat product streams.
How Streaming Works: Tokens, Events and SSE
Three layers sit between the model and the screen. The model produces tokens. The provider wraps those tokens in server-sent events. The network delivers the events in chunks. Those three things are not the same. A token is a piece of text. An event is a message carrying a text delta. A network chunk is whatever bytes arrived together. The interface only needs to append each delta in order.
Server-sent events, or SSE, is the standard transport. An SSE response uses the text/event-stream content type. The server keeps the connection open and pushes small text blocks. Each event has fields such as event and data, separated by blank lines. Browsers have supported this format for years through the EventSource API.
OpenAI's streaming uses SSE as well. Set stream to true on the Responses endpoint and the API returns a stream of typed events. Key events include response.created, response.output_text.delta, response.completed, and error. The delta event carries the incremental text. The client appends each delta to the visible answer.
Streaming LLM Responses Web App: The Server Pipeline
The golden rule is to stream end to end. The chain has three hops. The provider streams chunks to your server. Your server streams chunks to the client. The client renders chunks as they arrive. If any hop buffers the whole response before passing it on, the benefit disappears. A common mistake is receiving a stream from the provider and then waiting for it to finish before responding to the browser.
Keep the API key on the server. Never call the model API from the browser with a secret key. Anyone who opens developer tools can read it. The browser sends the prompt to your server. The server checks the input, adds the key, and opens the stream to the provider.
A FastAPI backend shows the shape. An async generator yields each chunk as a server-sent event. FastAPI added native SSE support in version 0.135.0 through EventSourceResponse. Before that, developers used the sse-starlette package. The endpoint checks whether the client disconnected and closes the upstream stream when it has. That check stops wasted work on abandoned chats.
Validate input on the server before streaming. Reject empty prompts and cap prompt length. A simple limit such as 4,000 characters keeps abuse in check. Return a plain error response for invalid input. Do not open a stream for a request you will reject.
The Client: Rendering Tokens Without Blocking the Interface
Reading the stream is only half the client job. The other half is painting without blocking. Each event triggers a state update and a DOM write. Doing that work for every single token can stall the main thread. Batch small deltas and update the display on a short interval or with requestAnimationFrame. Users cannot read faster than the text arrives, so batching costs nothing in practice.
Two client APIs exist. EventSource is the native SSE reader. It is simple but it only supports GET requests, so it cannot send a prompt body. Fetch with a ReadableStream reader handles POST requests and gives full control. Most chat apps use fetch for that reason. Parse the stream with a buffered SSE parser that handles split events and both line endings.
Show the right status at each stage. A typing indicator before the first token tells the user the request is live. A blinking cursor during streaming shows progress. A stop button lets the user cancel. A clear done state marks the end. Each state needs a visible cue, or users will wonder whether the app froze.
Cancellation, Errors and Partial Output
Cancellation is a first-class feature. When the user clicks stop, abort the fetch and close the upstream stream. The server should listen for disconnects and stop the provider call. Without that step, the server keeps paying for tokens nobody reads.
Errors can arrive mid-stream. The connection can drop. The provider can return an error event. The client must handle a partial answer gracefully. Keep the text received so far. Show a short message that the response stopped early. Offer a retry button that resumes or restarts the request.
Partial output raises a moderation question. OpenAI notes that streaming makes content moderation harder because partial completions are harder to evaluate than full ones. Moderation scores arrive after the full output is available, not with the partial deltas. Plan for that gap if your app serves untrusted users.
Production Checklist
- Proxy through your server. Keep the provider key server-side. Never expose it in browser code.
- Stream every hop. Provider to server, server to client, client to screen. Test with a slow model call and watch tokens arrive.
- Validate input first. Check length and content before opening the stream.
- Handle disconnects. Close the upstream stream when the client leaves.
- Batch DOM updates. Append deltas in small batches so the interface stays responsive.
- Support cancellation. Wire the stop button to abort the fetch and the upstream call.
- Handle mid-stream errors. Keep partial text, show a clear message, and offer retry.
- Test with curl. Use curl with the no-buffer flag to watch raw events arrive one by one.
- Mind proxies and compression. Some proxies buffer SSE. Set cache-control to no-cache and disable transforming proxies for the stream endpoint.
- Plan for moderation. Remember that partial output is harder to moderate than a complete response.
When Not to Stream
Streaming adds complexity. It adds state, cancellation, and error recovery. If a smaller, faster model can answer without streaming, the simpler design may serve users better. Short answers do not need streaming either. A two-sentence reply arrives fast enough as one response. Stream when answers are long and users wait. Skip it when the answer is short and the model is fast.
Bottom Line
Streaming LLM responses in a web app is a pipeline discipline, not a single flag. Set stream to true on the provider call. Forward each delta over SSE from your server. Render tokens in batches on the client. Support cancellation and mid-stream errors. Keep the API key server-side and validate input before the stream opens. Done well, users read while the model writes, and the app feels fast without the model getting any faster.