Streaming React Assistant Architecture, Testing, and Rollout

Medium · Software Engineering Fundamentals · Frontend Engineer · HR Screen

Prompt

You own the frontend technical design for an AI troubleshooting drawer embedded inside a colocation and infrastructure operations console. Replies arrive incrementally over Server-Sent Events (SSE), and an ongoing thread—including an active stream—must stay intact while operators switch across console views (such as rack power graphs, cross-connect orders, and incident queues).

Lay out an end-to-end engineering plan covering four areas:

  1. State Placement & Rendering Efficiency: Decide where thread history and active stream state live so route transitions do not drop messages or sever open streams, and explain how you keep frame rendering fast as threads grow large and updates arrive with low latency.
  2. Overlapping Submissions, Token Renewal, & Cleanup: Specify how the client behaves if an operator submits another question before an earlier SSE response finishes, how in-flight network calls are aborted cleanly, how browser/DOM observers are torn down on component unmount, and how mid-stream authentication token expiry is handled without losing context.
  3. Fault Tolerance, Verification, & Accessibility: Outline a layered test plan validating chunked streaming updates, mid-response connection drops or server errors, and screen-reader announcements using ARIA live regions.
  4. Staged Release, Emergency Shutoff, & Zero-PII Telemetry: Propose a production rollout and fast-rollback plan that handles partial backend outages gracefully, includes an immediate feature shutoff switch, and measures adoption and reliability without recording Personally Identifiable Information (PII).

Scope & Expectations

  • Anchor state ownership and component hierarchy choices around concrete latency, frame-budget, and cross-route persistence guarantees.
  • Address streaming transport edge cases explicitly, including overlapping requests, connection drops vs. clean stream completion, observer cleanup, and short-lived auth credentials.
  • Structure verification across unit, integration, accessibility (ARIA live behavior), and end-to-end tests so streaming tests remain fast and deterministic.
  • Pair staged rollout mechanics with operational safety controls (instant shutoff, asset-safe rollback, degraded read-only modes, and strict allowlist telemetry).

Step-by-step walkthrough

  1. Clarify scope, side effects, and measurable targets

    Turn the prompt into concrete engineering targets before designing components or pipelines:

    • Cross-route persistence: Navigating between dashboard pages (for example, from cage power telemetry to cross-connect tickets) never interrupts an active stream or clears the chat. Reloading the browser restores saved turns from the backend and marks any cut-off turn "interrupted" with a manual Retry button.
    • Low-latency rendering: Target < 1.5 s p95 time to first token (TTFT) and keep main-thread work well inside a 60 Hz display's 16.7 ms frame budget (< 3–4 ms per frame for the assistant) so charts and tables on the host page stay responsive.
    • Single-stream invariant: At most one stream may be active per conversation. Clicking Stop, submitting a follow-up prompt, or signing out cancels the in-flight HTTP request immediately and prevents stale chunks from corrupting newer messages.
    • Operational safety & privacy: Support disabling the feature within 60 seconds without a redeploy, rolling back bad frontend builds within minutes, and recording usage metrics with zero PII (Personally Identifiable Information)—no prompt text, response text, emails, or raw URLs containing customer identifiers.

    Clarify early whether the assistant can trigger write actions (such as opening a maintenance ticket). Whenever a prompt can mutate state, attach a client-generated idempotency key (a unique UUID per submission so the server ignores accidental duplicate sends) and never silently replay a full prompt on network errors.

  2. Anchor chat state in an external store outside the route outlet

    Where the panel and state live. Mount <AssistantPanel /> inside the persistent top-level shell (AppLayout) as a sibling of the router's <Outlet />, rather than inside individual page components. When the user clicks between routes, only <Outlet />'s child swaps; AppLayout and <AssistantPanel /> stay mounted.

    AppRoot
     └── ChatStoreProvider (passes stable store reference via Context)
          └── AppLayout (never unmounts during dashboard navigation)
               ├── Sidebar
               ├── <main><Outlet /></main>   <-- unmounts & swaps on route change
               └── <AssistantPanel />        <-- stays mounted; stream continues uninterrupted
    
    // AppLayout.jsx
    export function AppLayout() {
      return (
        <div className="app-shell">
          <Sidebar />
          <main>
            <Outlet /> {/* Swaps between dashboard pages on navigation */}
          </main>
          <AssistantPanel /> {/* Sibling of Outlet: survives every route transition */}
        </div>
      );
    }
    

    Why pass a store reference in Context instead of raw message state: Whenever a React Context value changes, every component reading that Context re-renders—even components wrapped in React.memo. Storing streaming text directly in Context would re-render the entire panel tree on every incoming token! Instead, hold conversation state and the active stream inside a small external store (Zustand, Redux Toolkit, or a 60-line custom store) read via React's useSyncExternalStore. That gives two major wins: 1. Components subscribe to narrow slices (a header component reading isStreaming ignores token text updates). 2. Because the store owns the stream rather than the panel component, collapsing or minimizing the drawer does not kill an answer in progress.

    Keeping UI updates fast as state grows: - Coalesce tokens per animation frame (requestAnimationFrame): If 40 tokens arrive inside one 16.7 ms frame, buffer them in plain string memory and commit to React state once per frame. - Memoize finished messages & cache parsed Markdown blocks: Completed messages never change, so wrap <MessageItem /> in React.memo. During streaming, re-parsing an entire 2,000-token Markdown answer on every update does quadratic work—caching already-closed paragraphs/code blocks cuts parsing work by an order of magnitude:

    Update strategy on a 2,000-token answer       Total tokens parsed across the response
    ────────────────────────────────────────────  ───────────────────────────────────────
    Commit every token, re-parse whole message    2,000 commits x ~1,000 avg = ~2,000,000
    Commit once per 60 Hz frame (~20 s stream)    1,200 commits x ~1,000 avg = ~1,200,000
    Frame batching + parse only active tail block <= 1,200 commits x ~100    =   ~120,000
    
  3. Stream over fetch, cancel with AbortController, and prevent races

    Server-Sent Events (SSE) is a standard HTTP text-streaming format where the server keeps one response open and pushes blank-line-separated (\n\n) frames containing event:, data:, and id: lines.

    Why fetch + ReadableStream beats native EventSource: The browser's built-in EventSource only supports GET requests (putting prompts in URLs leaks sensitive text into proxy logs and hits URL length limits) and cannot send custom Authorization: Bearer headers. Using POST with fetch, decoding chunks via TextDecoderStream, and passing an AbortController signal (the standard Web API for cancelling in-flight fetch requests) gives custom headers, POST bodies, and clean cancellation:

    export class AuthError extends Error {}
    
    export function parseFrame(frame) {
      let type = "message";
      let id = null;
      const dataLines = [];
    
      for (const line of frame.split("\n")) {
        // Empty lines or ":" comment heartbeats carry no event payload
        if (line === "" || line.startsWith(":")) continue;
        const colon = line.indexOf(":");
        const field = colon === -1 ? line : line.slice(0, colon);
        let value = colon === -1 ? "" : line.slice(colon + 1);
        if (value.startsWith(" ")) value = value.slice(1);
    
        if (field === "event") type = value;
        else if (field === "data") dataLines.push(value);
        else if (field === "id") id = value;
      }
    
      if (dataLines.length === 0) return null;
      return { type, id, data: dataLines.join("\n") };
    }
    
    export async function readEventStream(response, onEvent) {
      const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
      let buffer = "";
      try {
        while (true) {
          const { value, done } = await reader.read();
          if (done) return;
          // Normalize CRLF across chunk boundaries; TCP chunks can split mid-line
          buffer = (buffer + value).replace(/\r\n/g, "\n");
          let boundary = buffer.indexOf("\n\n");
          while (boundary !== -1) {
            const event = parseFrame(buffer.slice(0, boundary));
            buffer = buffer.slice(boundary + 2);
            if (event) onEvent(event);
            boundary = buffer.indexOf("\n\n");
          }
        }
      } finally {
        // Release the underlying HTTP stream if onEvent throws or caller aborts
        reader.cancel().catch(() => {});
      }
    }
    
    export async function streamChat({ prompt, idempotencyKey, token, lastEventId, signal, onEvent }) {
      const headers = {
        "Content-Type": "application/json",
        Accept: "text/event-stream",
        Authorization: `Bearer ${token}`,
        "Idempotency-Key": idempotencyKey,
      };
      if (lastEventId) headers["Last-Event-ID"] = lastEventId;
    
      const response = await fetch("/api/assistant/stream", {
        method: "POST",
        headers,
        body: JSON.stringify({ prompt }),
        signal,
      });
      if (response.status === 401) throw new AuthError("token expired");
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      await readEventStream(response, onEvent);
    }
    

    Handling overlapping prompts without race conditions: If an operator sends a follow-up question before an in-progress stream finishes, we synchronously finalize the earlier reply as "stopped" (preserving partial text already received) and abort its AbortController. Because a decoded chunk already queued on the microtask queue could still fire onEvent right after abort(), every request also gets a monotonically increasing requestId, and any callback whose requestId !== active.requestId is ignored:

    export function createChatStore({ stream, schedule = (fn) => requestAnimationFrame(fn) }) {
      let state = { messages: [], streamingId: null };
      const listeners = new Set();
      let active = null; // { requestId, controller, messageId }
      let nextRequestId = 1;
      let pendingText = "";
      let flushScheduled = false;
    
      function emit() {
        for (const listener of listeners) listener();
      }
    
      function updateMessage(messageId, changes) {
        const messages = state.messages.map((m) => (m.id === messageId ? { ...m, ...changes } : m));
        state = { ...state, messages };
      }
    
      function flushText() {
        flushScheduled = false;
        if (!active || pendingText === "") return;
        const target = state.messages.find((m) => m.id === active.messageId);
        updateMessage(active.messageId, { text: target.text + pendingText });
        pendingText = "";
        emit();
      }
    
      function finish(requestId, messageId, status) {
        if (active && active.requestId === requestId) {
          flushText();
          active = null;
          state = { ...state, streamingId: null };
        }
        updateMessage(messageId, { status });
        emit();
      }
    
      function stop() {
        if (!active) return;
        const { requestId, controller, messageId } = active;
        // Transition state synchronously before abort() so two messages are never "streaming" at once
        finish(requestId, messageId, "stopped");
        controller.abort();
      }
    
      async function send(prompt) {
        stop(); // Cancel and finalize any in-flight stream first
        pendingText = "";
        const requestId = nextRequestId++;
        const controller = new AbortController();
        const messageId = `assistant-${requestId}`;
        active = { requestId, controller, messageId };
    
        state = {
          messages: [
            ...state.messages,
            { id: `user-${requestId}`, role: "user", text: prompt, status: "done" },
            { id: messageId, role: "assistant", text: "", status: "streaming" },
          ],
          streamingId: messageId,
        };
        emit();
    
        let sawDone = false;
        try {
          await stream({
            prompt,
            idempotencyKey: `turn-${requestId}`,
            signal: controller.signal,
            onEvent(event) {
              if (!active || active.requestId !== requestId) return; // Drop late chunks from aborted runs
              if (event.type === "token") {
                pendingText += event.data;
                if (!flushScheduled) {
                  flushScheduled = true;
                  schedule(flushText);
                }
              } else if (event.type === "done") {
                sawDone = true;
              } else if (event.type === "error") {
                throw new Error(event.data);
              }
            },
          });
          if (active && active.requestId === requestId) {
            // If TCP closed without an explicit "done" event, mark as interrupted, not complete!
            finish(requestId, messageId, sawDone ? "done" : "interrupted");
          }
        } catch (error) {
          if (active && active.requestId === requestId) {
            finish(requestId, messageId, controller.signal.aborted ? "stopped" : "interrupted");
          }
        }
      }
    
      return {
        getSnapshot: () => state,
        subscribe(listener) {
          listeners.add(listener);
          return () => listeners.delete(listener);
        },
        send,
        stop,
      };
    }
    

    Component unmount vs. session logout cleanup: - DOM observers owned by UI components (IntersectionObserver for sticky bottom-scroll detection, ResizeObserver for dynamic message heights) disconnect inside useEffect cleanup on component unmount: jsx useEffect(() => { const observer = new IntersectionObserver(([entry]) => setAtBottom(entry.isIntersecting)); observer.observe(bottomSentinelRef.current); return () => observer.disconnect(); }, []); - Session-level resources (the active SSE connection and conversation history) live in the store so hiding the panel keeps streaming alive, while user logout explicitly calls store.stop() and wipes memory. On the backend, detecting client disconnect (request.on("close")) stops LLM token generation immediately to save GPU budget.

  4. Handle auth-token expiration before, at, and mid-stream

    Short-lived access tokens (typically 15 minutes) can expire at three distinct points:

    1. Before opening the stream: If the token has < 2 minutes of remaining lifetime, refresh proactively before calling fetch.
    2. HTTP 401 on initial POST: No tokens have been generated yet, so refresh once via a single-flight refresh (deduplicating concurrent refresh calls into one shared Promise so parallel dashboard requests do not race and invalidate rotating refresh tokens) and retry the POST once.
    3. Expiration mid-stream: Most gateways validate auth at connection setup; if yours enforces continuous auth and closes an expired stream, have the server send event: error with data: token_expired after tagging token frames with sequential id values. The client refreshes the token and reconnects sending Last-Event-ID: <lastId>, letting the server replay buffered tokens after <lastId> without re-executing the prompt! If the refresh token itself is expired, preserve the partial transcript and display a "Sign in again" action.
    export function createTokenSource(refreshFn, initialToken) {
      let currentToken = initialToken;
      let inFlightRefresh = null; // Single-flight lock shared across concurrent 401 callers
    
      return {
        get: () => currentToken,
        async refresh() {
          if (!inFlightRefresh) {
            inFlightRefresh = refreshFn()
              .then((freshToken) => {
                currentToken = freshToken;
                return freshToken;
              })
              .finally(() => {
                inFlightRefresh = null;
              });
          }
          return inFlightRefresh;
        },
      };
    }
    
    export function createAuthedStream(tokens) {
      return async function authedStream(args) {
        let lastEventId = null;
        function onEvent(event) {
          if (event.id !== null) lastEventId = event.id;
          if (event.type === "error" && event.data === "token_expired") {
            throw new AuthError("token expired mid-stream");
          }
          args.onEvent(event);
        }
    
        try {
          await streamChat({ ...args, onEvent, token: tokens.get() });
        } catch (error) {
          if (!(error instanceof AuthError) || args.signal.aborted) throw error;
          await tokens.refresh();
          // Initial 401 has lastEventId = null; mid-stream expiry sends Last-Event-ID to resume cleanly
          await streamChat({ ...args, onEvent, token: tokens.get(), lastEventId });
        }
      };
    }
    
  5. Design accessible ARIA live announcements for streaming text

    An ARIA live region (role="status", role="alert", or aria-live) instructs screen readers to announce dynamic DOM text changes aloud without stealing keyboard focus.

    • Never put aria-live directly on the streaming message bubble: Updating a live region 60 times per second causes VoiceOver, NVDA, and JAWS to either stutter syllable fragments or queue a multi-minute speech backlog.
    • Mount one persistent, visually hidden role="status" announcer (aria-live="polite"): Render the container empty from initial mount (dynamically inserted live containers are frequently ignored by screen readers) and change its text only twice per turn—once when streaming begins ("Assistant is responding...") and once when the turn settles (done, stopped, or interrupted).
    • Use role="alert" (aria-live="assertive") only for blocking errors like session expiration, keep keyboard focus inside the prompt input on submit, and make Stop and Retry native <button> elements.
    function StreamAnnouncer({ messages, streamingId }) {
      const [announcement, setAnnouncement] = useState("");
      const prevStreamingId = useRef(null);
    
      useEffect(() => {
        if (streamingId) {
          setAnnouncement("Assistant is responding…");
        } else if (prevStreamingId.current) {
          const finished = messages.find((m) => m.id === prevStreamingId.current);
          if (finished?.status === "done") setAnnouncement(`Assistant replied: ${finished.text}`);
          else if (finished?.status === "stopped") setAnnouncement("Response stopped.");
          else if (finished?.status === "interrupted") {
            setAnnouncement("Response interrupted. Activate Retry to try again.");
          }
        }
        prevStreamingId.current = streamingId;
      }, [streamingId, messages]);
    
      return (
        <div role="status" className="sr-only">
          {announcement}
        </div>
      );
    }
    
  6. Verify resilience across unit, integration, accessibility, and E2E tests

    Make streaming tests fast and deterministic by injecting stream and schedule into createChatStore rather than sleeping on real wall-clock timers:

    Test layer Tooling Critical scenarios verified
    Unit Vitest / Jest parseFrame & readEventStream with TCP chunks split mid-line, \r\n endings, : heartbeats, and missing done frames; store race handling when prompt 2 aborts prompt 1; single-flight token refresh deduplicating 3 concurrent 401 errors into 1 call.
    Integration React Testing Library + MSW (ReadableStream) Token rendering across flushes (wrapping each chunk flush in its own act() so intermediate states render); mid-stream socket close preserving partial text + Retry; 401 -> refresh -> Last-Event-ID resume; survival across <MemoryRouter> route transitions; observer disconnect() spies on unmount.
    Accessibility jest-axe + RTL + manual AT Zero axe violations; asserting role="status" mutates text exactly twice across a 10-chunk stream; manual pass in VoiceOver + NVDA before general launch.
    End-to-End Playwright + scripted SSE stub Navigate across 3 dashboard routes while tokens stream; click Stop; page reload restoring transcript; context.setOffline(true) mid-stream gracefully marking "interrupted"; performance trace confirming < 16.7 ms frame commits over 3,000 history turns.
  7. Roll out safely with feature flags, canary guardrails, kill switches, and fast rollback

    Deploy dark (flag OFF, React.lazy chunk, ErrorBoundary)
      ──► Staff dogfooding ──► 1% canary ──► 5% ──► 25% ──► 100% GA
                                 │
                Guardrail breach? ├──► Flip kill-switch flag OFF (< 60 s, no deploy)
                Bundle regression?└──► Repoint index.html to previous immutable build (< 3 min)
    
    • Decouple deploy from release: Code-split the panel with React.lazy behind a feature flag (assistant.enabled) so disabled accounts download zero assistant JavaScript, and wrap <AssistantPanel /> in a React ErrorBoundary so an unexpected render bug degrades to "Assistant unavailable" without crashing data-center monitoring views.
    • Sized canary stages: Roll out by hashing accountId (staff -> 1% -> 5% -> 25% -> 100%) so all users at a customer site get a consistent experience. Hold each stage until statistically meaningful volume passes—for instance, detecting a jump from a 1% baseline stream failure rate to 2% (80% power, 5% one-sided significance) requires ~800–900 streams; at 1% of 40,000 daily users sending 5 prompts/day (2,000 streams/day), one business day gives ample signal. Monitor global JS errors, INP (Interaction to Next Paint), LCP (Largest Contentful Paint), TTFT, and stream interruption rate.
    • Two-sided kill switch:
      1. Frontend: Poll or stream flag updates every 60 s; flipping assistant.enabled off calls store.stop() and hides the composer within a minute. Default to false if the flag service is unreachable on cold start.
      2. Backend: Return 503 Service Unavailable with Retry-After at the API gateway so week-old browser tabs with stale flags stop hitting inference servers immediately.
    • Instant rollback without broken lazy chunks: For feature bugs, toggle the flag (< 60 s). For bundle regressions, repoint index.html on the CDN to the prior immutable release (< 3 min) while retaining previous content-hashed JS/CSS chunks on object storage for at least 7–14 days so already-open tabs never fail lazy imports with ChunkLoadError.
  8. Degrade gracefully on partial outages and track usage without PII

    Partial backend availability: - History service healthy, LLM streaming down: Render past conversations read-only with a clear degraded-mode banner and disable the prompt input. - Stalled stream: Show "Still working..." after 5 s without a first token, and treat 30 s without any bytes (including : SSE heartbeat comments sent every 15 s) as a dead connection. - Client circuit breaker & safe retries: A circuit breaker temporarily halts outbound calls after repeated failures (for example, 5 failures within 30 s pauses calls for 30 s before testing a single probe request), protecting an overloaded backend from retry storms. Use exponential backoff with random jitter (~1 s, 2 s, 4 s) only for idempotent reads (GET history or Last-Event-ID resume)—never auto-resubmit raw user prompts.

    Zero-PII telemetry: - Strict allowlist schemas: Emit only enumerated operational fields—such as assistant_stream_finished { status, ttft_ms, token_count, duration_ms, prompt_char_bucket: "100-499", route_template: "/cages/:cageId/power" }. Drop unknown properties in the client SDK and at the ingestion collector. - Route templates, never raw URLs: Log /cages/:cageId/power rather than /cages/acme-west-04/power?search=john@acme.com, and never send prompt or completion text to product analytics. - Random analytics IDs, not hashed emails: Hashing an email (SHA-256(email)) is pseudonymization, not true anonymization—anyone with the customer email list can brute-force match the hashes, and privacy laws like GDPR still classify it as personal data. - Scrub crash reports: Configure Sentry/Datadog beforeSend hooks to strip Authorization headers, POST request bodies, and DOM input breadcrumbs before telemetry leaves the browser.

Intuition & how it works

Think of the conversational assistant like a technician's belt-clipped walkie-talkie inside a multi-floor data center. Because the radio is clipped to the technician's belt (AppLayout above the router) rather than bolted to the wall of one room (a single page route), walking from the power-monitoring room to the ticket-queue room never cuts off an incoming voice transmission. Inside the radio, fast bursts of words are buffered onto the screen once per display frame (60 Hz), pressing the talk button for a new question hangs up the previous transmission first (AbortController + request ID guard), and a master dispatch switch can silence all radios within seconds if interference hits.

Naive React setups fail here in predictable ways. Storing chat messages inside a page component destroys the conversation and drops the network connection on every route change, while stuffing rapidly streaming text into a top-level React Context value forces every consumer across the app to re-render on every single token. Using native EventSource prevents sending POST bodies or Authorization headers, relying on controller.abort() without a request ID lets already-queued chunks leak into the next reply, and putting aria-live directly on a streaming paragraph floods screen readers with broken word fragments.

Trace one realistic multi-step user journey through our design: 1. Prompt & route change: An operator asks "Summarize power alerts in Cage B" (requestId = 1) and clicks over to /tickets. <Outlet /> swaps pages, while <AssistantPanel /> and the external chat store stay mounted; incoming Server-Sent Events (SSE) tokens buffer in memory and flush once per requestAnimationFrame (<= 60 commits/second). 2. Follow-up interruption: Halfway through answer 1, the operator submits "Only critical alerts" (requestId = 2). store.stop() synchronously flushes buffered text onto answer 1, marks answer 1 "stopped", and aborts controller 1 before creating answer 2—any late microtask chunk from stream 1 sees active.requestId !== 1 and is discarded. 3. Mid-stream auth expiry & screen reader output: Ten minutes into a session, the access token expires mid-stream; the server emits event: error (token_expired) after id: 42, our single-flight token manager refreshes once, and streamChat reconnects with Last-Event-ID: 42 to resume seamlessly. Meanwhile, a persistent role="status" announcer speaks "Assistant is responding…" once at start and the finished reply once at event: done.

Key points

  • Mount above the router, store outside Context values: Render <AssistantPanel /> beside <Outlet /> in AppLayout, pass only a stable store reference via Context, and read slices with useSyncExternalStore (or Zustand) so token arrivals re-render only the active message bubble.
  • Bound work per 16.7 ms frame: Coalesce incoming tokens with requestAnimationFrame, wrap completed messages in React.memo, and cache already-parsed Markdown blocks so streaming a 2,000-token answer parses only the growing tail block instead of re-parsing from scratch on every frame.
  • Stream via POST fetch + ReadableStream + AbortController: Native EventSource lacks POST bodies and custom Authorization headers; fetch supports both, normalizes TCP chunk boundaries (\r\n and split lines), enforces a single active stream via AbortController + requestId, and treats streams ending without event: done as "interrupted".
  • Three-tier auth-token resilience: Refresh proactively before long streams, deduplicate initial 401 token refreshes through a single-flight Promise, and resume mid-stream token expirations via Last-Event-ID (with an Idempotency-Key header so prompts with side effects never execute twice).
  • Polite, two-event ARIA announcements: Keep one persistent role="status" ARIA live region (an element screen readers announce dynamically without moving focus) that updates only on stream start and stream completion, reserving role="alert" for actionable errors.
  • Deterministic layered testing: Inject stream and schedule into the store for instant unit tests on chunk splitting and races, pair React Testing Library with Mock Service Worker ReadableStream responses for drops and 401 retries, verify accessibility with axe-core plus manual VoiceOver/NVDA checks, and run Playwright E2E tests across route changes and offline drops.
  • Flagged canary rollout, dual kill switches, and zero-PII telemetry: Lazy-load behind a feature flag inside an ErrorBoundary, ramp by accountId hash with statistical guardrails, back a client flag kill switch with a server 503 switch, retain old asset chunks during HTML rollbacks, and emit strict allowlist telemetry (route templates, latency buckets, random IDs—zero prompt text or PII).

Common mistakes

  • Storing chat state inside route-level components or unmounting streams in panel UI effects. Navigating pages or collapsing the drawer then kills active streams; keep session streams in the external store and reserve useEffect cleanup for DOM observers (IntersectionObserver, ResizeObserver).
  • Putting live message arrays directly into Context.Provider value={...}. Every Context consumer re-renders on every flushed token regardless of React.memo.
  • Assuming AbortController.abort() prevents all late callbacks. Chunks already read from the stream before abort() can still invoke onEvent asynchronously and append text to the next answer unless guarded by requestId and synchronous state finalization.
  • Treating { done: true } from reader.read() as a complete answer. Load balancers and reverse proxies drop idle or long HTTP connections cleanly at the TCP layer; without requiring an explicit event: done frame from the backend, half-finished answers get saved as complete.
  • Putting aria-live="polite" directly on the streaming message element. Screen readers either stammer broken tokens or build a massive speech queue that keeps talking minutes after streaming ends.
  • Implementing a kill switch only in frontend JavaScript. Long-lived data-center dashboard tabs that cached yesterday's flag state—or fail to reach the flag CDN—keep hitting the backend unless paired with a server-side 503 switch.
  • Purging previous JS chunks from the CDN immediately on deploy. Already-open browser tabs that open the lazy-loaded assistant after a deploy will request old content-hashed chunk filenames and crash with ChunkLoadError.
  • Hashing user emails (SHA-256(email)) and calling telemetry "anonymous." Hashed identifiers can be reversed against a known customer list (pseudonymization, still regulated as personal data under GDPR); generate a separate random analytics ID and never log prompt text or raw URLs.

Follow-up questions

  • What techniques keep scrolling and token updates smooth once a thread reaches thousands of turns? Add list virtualization (windowing with TanStack Virtual + ResizeObserver for variable-height bubbles) so the DOM holds only the ~25 visible messages (~1,000 DOM nodes) instead of 3,000 * 40 = 120,000 nodes. Split the active streamingText into its own dedicated store slice separate from the immutable completedMessages array—otherwise mapping over a 3,000-element array 60 times per second copies 180,000 references/second unnecessarily—so token flushes re-render only the single active tail component while React.memo and cached Markdown ASTs freeze finished turns. Finally, paginate older history from the server as the operator scrolls up (preserving scroll offset on prepend) and auto-scroll on new tokens only when an IntersectionObserver sentinel confirms the user is already pinned to the bottom.
  • Which operational and user-facing signals would you track to evaluate reliability and answer usefulness? Track three PII-free buckets with explicit alert thresholds: (1) System & UX health—time to first token (p50/p95), stream completion rate (done streams divided by non-user-stopped streams), interruption rate broken down by cause (network drop, 5xx, auth failure), Last-Event-ID resume success rate, and host-page INP / LCP comparing sessions with vs. without the panel; (2) Answer quality—explicit thumbs-up ratio, regenerate/stop-early rate, quick-rephrase rate (another prompt within 15 seconds after an answer), and action follow-through rate (whether operators clicked cited runbooks or opened linked cage views); and (3) Adoption—weekly active accounts and 4-week retention.
  • How would you keep conversation state consistent when an operator has the same thread open across multiple browser tabs? Make the backend the source of truth by assigning a monotonic turnSequence integer to every conversation turn: each POST sends the tab's expectedSequence, and if Tab B already advanced the conversation, the server returns 409 Conflict so Tab A syncs the latest turns instead of overwriting or forking history. Inside the browser, connect same-origin tabs over a BroadcastChannel so the tab running an active stream mirrors flushed token batches live to sibling tabs (showing "Responding in another tab…" with a shared Stop control), and coordinate shared background work like token refreshes through the Web Locks API (navigator.locks.request) so only one leader tab refreshes credentials at a time.

Follow-up questions

Similar questions

More Equinix interview questions

All 2 Equinix questions →