Skip to content
Goal: Proficient✓ Sources verified 2026-11-24SSEAbortControllerPolling

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 ​

OptionDirectionGood for
SSE (Server-Sent Events)One-way push from server to client, over plain HTTPLLM token streams, task progress updates
WebSocketTwo-wayCollaborative editing, clients that send messages frequently
PollingThe client requests on a timerSimple, 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 ​

  1. EventSource: the browser's native SSE client. GET only, no custom request headers (auth can only use cookies), automatic reconnection.
  2. fetch + ReadableStream: supports POST and custom headers, but you parse the data: lines yourself; cancel with AbortController. 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 ​

  1. Calling JSON.parse on each chunk directly: network packets don't follow event boundaries. Buffer first, then split on blank lines.
  2. 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: no or the proxy_buffering off setting).
  3. Flickering Markdown rendering: re-parsing the full Markdown on every token is expensive; throttle rendering.
  4. Stopping only the frontend, not the backend: cancellation must reach the backend, or you keep paying.

Common interview questions ​

  1. How do you choose between SSE and WebSocket?
  2. What are the limits of EventSource? Why does LLM chat usually read the stream with fetch?
  3. How does "Stop generating" travel from the frontend to the backend to the LLM?
  4. How would you design the frontend experience for a task that runs for 3 minutes?

Sources ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section