Shipping a Persistent Streaming Chat Widget in a React App
System DesignModel answerLast updated
Plan how to build, test and safely release a streaming chat panel in a React dashboard, covering state, request races, token expiry, accessibility, feature flags and rollback.
Scenario
Your team is adding an in-app help chat panel to an operations dashboard used to monitor server infrastructure. Replies arrive as a live token stream over Server-Sent Events (SSE). The panel has to stay open, and keep its conversation, while the user moves between dashboard pages.
What to cover
Walk through a plan for each of the following areas.
-
State and performance
- Where does the conversation state live so that page navigation does not reset it?
- How do you keep rendering fast when the history becomes long and tokens arrive many times per second?
-
Concurrency and lifecycle
- What happens if the user sends a new message while a reply is still streaming?
- How do you cancel in-flight requests and release observers, listeners and timers when components unmount?
-
Testing and resilience
- How do you test incremental rendering, dropped connections and error states?
- How do you verify accessibility for screen-reader users, particularly live-region announcements?
-
Release and operations
- How do you roll the feature out gradually, cope with a backend that is only partly available, and provide an instant kill switch?
- How do you measure adoption without capturing personally identifiable information?
Constraints
- Updates must feel low-latency to the user.
- You need a fast, well-defined rollback path for serious regressions.
- Access tokens can expire while a stream is open, so say how you would handle that.
State any assumptions (message volume, token lifetime, tokens per second) before you design.
Hints
Hint 1
Think about what must outlive route changes: mounting the panel outside the routed area and holding the stream in a store or service, not in a component, solves most persistence questions.
Hint 2
For races, give every request an identifier and an abort handle, and make every state write check that its identifier is still the active one.
Hint 3
For accessibility, consider what a screen reader does if the whole growing message is a live region, and where a separate, quieter announcement channel could help.
Hint 4
For rollout, list your first lever (a remotely controlled flag), your guardrail metrics, and the exact thresholds that would trigger rollback.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing and assumptions
I would begin by stating assumptions, since they drive the design:
- Conversations typically hold tens to a few hundred messages; power users may reach thousands.
- Streams emit roughly 20 to 60 tokens per second.
- Access tokens live about 15 minutes, with a refresh token available.
- Surviving navigation is required. Surviving a full page reload is a bonus, served by server-side history.
- Target: the first token is visible almost as soon as it arrives, with no dropped frames while streaming.
1. Architecture and persistence
Placement. Mount the assistant provider and panel in the app shell, as a sibling of the router outlet. Route changes then never unmount it.
Store. Keep state in an external store (Zustand or Redux Toolkit) rather than a plain Context value. A Context change re-renders every consumer, while selectors let each component subscribe to only what it needs.
Normalized model.
sessions: map of session id to ordered message ids and a status.messages: map of id to role, content, status (streaming,done,error,cancelled) and the request id that produced it.activeRequest: request id plus abort controller, kept outside serializable state.
Performance.
- Only the in-flight message changes; finished messages are immutable and memoized, so a token append re-renders one row.
- Batch tokens: buffer chunks and flush once per animation frame, so 60 tokens per second does not mean 60 store updates per second.
- Parse markdown only for the streaming message, after each flush.
- Virtualize the list once history is long, and keep scroll anchoring sensible (stick to bottom only if the user is already there).
2. Races and lifecycle
Transport. Use fetch with a stream reader (or a library built on it) rather than native EventSource, which cannot set an Authorization header and is awkward to cancel.
New prompt during a stream. Choose one policy and state it. Cancel-and-replace is the usual one:
- Abort the previous controller.
- Mark the old message
cancelled, keeping the partial text. - Start a new request with a fresh request id.
Every write checks that its request id equals the active one. This stale guard stops chunks already queued in the event loop from landing in the wrong message.
send(prompt):
if active: active.controller.abort()
id = newId(); controller = new AbortController()
active = { id, controller }
for chunk in stream(prompt, controller.signal):
if active.id != id: return
buffer.push(chunk) # flushed per animation frame
Cleanup. The stream belongs to the store or service, so navigation intentionally does not stop it. Component effects still clean up after themselves: unsubscribe from the store, cancel pending animation frames, and disconnect any IntersectionObserver or ResizeObserver used for auto-scroll. When the panel is closed or the user logs out, abort the controller and cancel the reader.
Token expiry mid-stream.
- Refresh proactively before a request if the token expires within about a minute.
- An open stream normally continues, since the server validated the token on connect; confirm this with the backend.
- If the server ends the stream with a 401 or an auth-expired event, refresh once through a single-flight promise (so concurrent callers do not stampede), then resume from a cursor or last event id if supported, otherwise mark the message interrupted and offer Retry.
- Never loop on retries. If refresh fails, ask the user to sign in again and preserve their draft.
3. Testing strategy
| Layer | Focus |
|---|---|
| Unit | SSE parser (frames split across chunks, multi-byte characters, end marker), reducer transitions, stale-id guard, backoff math |
| Integration (Testing Library + mocked streaming responses) | Incremental rendering; second prompt aborts the first with no stale text; navigation keeps the stream alive; a mid-stream 401 triggers exactly one refresh |
| Failure injection | Connection drop yields partial text plus Retry; reconnect uses exponential backoff with jitter; 5xx and timeouts show a non-blocking error; malformed events are skipped and logged |
| End to end (Playwright) | Real streaming, route changes, offline toggling, throttled network |
| Accessibility | axe in CI plus a manual pass with a real screen reader and keyboard-only flow |
Accessibility details. Do not make the streaming text itself a live region, or the reader announces every token. Instead:
- Use a visually hidden polite status region updated at sentence boundaries or on completion.
- Announce errors with an alert role.
- Set
aria-busyon the message list while streaming. - Return focus to the input after sending.
- Test that the live region's text changes only at those moments.
4. Deployment and rollout
Flags. A top-level flag gates the whole panel and is the kill switch; it should default to off if the flag service is unreachable. A finer flag switches to non-streaming request/response mode, which handles a degraded streaming backend.
Progressive rollout. Internal users first, then 1%, 5%, 25%, 50%, 100%. At each step check guardrails: error rate, stream completion rate, frontend crash rate, and interaction latency (INP) on the dashboard pages. Define automatic rollback triggers in advance, for example stream failure rate above 2% for 10 minutes.
Partial backend availability. Use a health check or capability endpoint, degrade to non-streaming mode, show a clear "assistant unavailable" state, and never block the rest of the dashboard.
Rollback. The first lever is flipping the flag, which takes seconds and needs no deploy. Ship the panel as a lazy-loaded chunk so a disabled flag costs no bundle size. Keep immutable, versioned build artifacts so a full redeploy of the previous version is also quick.
Privacy-safe telemetry. Track events such as panel opened, message sent, stream completed, stream errored, with latency and length buckets. Never log message content or user identifiers; use a rotating anonymous session id, and scrub error payloads before sending.
Common mistakes
- Storing chat state in a component below the router, so navigation wipes it.
- Using one Context for fast-changing stream data.
- No stale-response guard after abort.
- Making the whole message an
aria-liveregion. - Retrying on 401 in a loop.
- A kill switch that requires a deploy, or that fails open when the flag service is down.
- Logging prompts "for debugging".
Follow-ups to be ready for
Resuming streams after reconnect, multi-tab synchronization (for example via BroadcastChannel), and how you would measure whether the feature actually helps users.