Streaming UI and Long-Running Task Interaction
The most recognizable part of an AI app's frontend: streaming tokens, progress for tasks that take minutes, and the ability to cancel and retry.
Core concepts
| Option | Direction | Good for |
|---|---|---|
| SSE (Server-Sent Events) | One-way push from server to client, over plain HTTP | LLM token streams, task progress updates |
| WebSocket | Two-way | Collaborative editing, clients that send messages frequently |
| Polling | The client requests on a timer | Simple, the most reliable through proxies; suits status of minute-long tasks |
Rule of thumb: use SSE for LLM answer streams; for long tasks (parsing + extraction taking tens of seconds to minutes) use "submit → get a task_id back → poll or subscribe to progress via SSE".
How it works
Two ways to read a stream in the browser
EventSource: the browser's native SSE client. GET only, no custom request headers (auth can only use cookies), automatic reconnection.fetch+ReadableStream: supports POST and custom headers, but you parse thedata:lines yourself; cancel withAbortController. LLM chat usually uses this one.
SSE data format
event: token
data: {"text":"Hello"}
event: done
data: {"stop_reason":"end_turn"}Each event ends with a blank line; the id: and retry: fields are used for reconnection.
In practice: reading a stream with fetch + cancellation
tsx
'use client'
import { useRef, useState } from 'react'
export function useStreamAnswer() {
const [text, setText] = useState('')
const ctrl = useRef<AbortController | null>(null)
async function start(question: string) {
ctrl.current = new AbortController()
setText('')
const res = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ question }),
signal: ctrl.current.signal,
})
const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader()
let buf = ''
while (true) {
const { value, done } = await reader.read()
if (done) break
buf += value
const events = buf.split('\n\n')
buf = events.pop()! // the last piece may be incomplete; keep it for next time
for (const e of events) {
const data = e.split('\n').find(l => l.startsWith('data: '))?.slice(6)
if (data) setText(t => t + JSON.parse(data).text)
}
}
}
const stop = () => ctrl.current?.abort() // the user clicks "Stop generating"
return { text, start, stop }
}The backend must stop the upstream LLM call when the client disconnects (see FastAPI SSE).
UI states checklist for long tasks
Queued → Processing (step n/6: parse / extract / validate…) → Awaiting human review → Done / Failed (show the reason + a retry button). Every state needs an empty state, a loading state and an error state.
Common pitfalls
- Calling JSON.parse on each chunk directly: network packets don't follow event boundaries. Buffer first, then split on blank lines.
- Reverse proxy buffering: Nginx buffers responses by default, so "streaming" arrives all at once. Turn buffering off (e.g. the response header
X-Accel-Buffering: noor theproxy_buffering offsetting). - Flickering Markdown rendering: re-parsing the full Markdown on every token is expensive; throttle rendering.
- Stopping only the frontend, not the backend: cancellation must reach the backend, or you keep paying.
Common interview questions
- How do you choose between SSE and WebSocket?
- What are the limits of
EventSource? Why does LLM chat usually read the stream with fetch? - How does "Stop generating" travel from the frontend to the backend to the LLM?
- How would you design the frontend experience for a task that runs for 3 minutes?
Sources
- MDN: Using server-sent events — event format,
EventSource - WHATWG HTML Standard: Server-sent events
- MDN: AbortController
- MDN: Streams API / ReadableStream
- Nginx Docs: proxy_buffering — the
X-Accel-Bufferingresponse header
