Home / Insights / Generative AI and LLMs

Generative AI and LLMs

Streaming LLM Responses in Web and Mobile Apps: UX, Cancellation and Errors

Streaming makes an LLM feature feel fast because users see words within moments instead of waiting for the full answer. It also introduces problems that request-response features never had: half-finished answers, errors after a success status, users who leave mid-stream and screen readers that announce every token. This guide covers how to design streaming end to end in web and mobile apps.

TopicsGenerative AI and LLMsWeb and SaaS DevelopmentMobile App Development

Key takeaways

  • Stream through your own backend, not directly from the client to the model provider, so you can authenticate, validate, log, moderate and cancel in one place.
  • Model providers can send errors inside a stream after an HTTP 200, so clients must handle in-stream error events and partial output, not only status codes.
  • Cancellation must propagate end to end: the user’s stop action should abort the client request, the backend request and the upstream model call, or you keep paying for tokens nobody reads.
  • Render streamed text in batches, keep layout stable, and announce completion to screen readers rather than every fragment.
  • Decide which outputs should not be streamed at all, such as structured data, tool results and content that must pass checks before display.

When we build LLM features, the first request from product teams is usually to make the answer appear as it is generated. That is the right instinct: for long answers, waiting several seconds for a blank screen to fill feels broken, while text that starts flowing within moments feels responsive. But streaming changes the contract between client and server. A response can now succeed and then fail halfway. A user can stop it, edit their question, lose signal in a lift or background the app. Each of those cases needs a deliberate design, or the feature becomes fragile and expensive.

This article is for CTOs, product leads and engineering managers planning or reviewing streaming in web and mobile products. It covers when to stream, transport and architecture choices, rendering and accessibility, cancellation, error handling and recovery, mobile-specific concerns, and a testing checklist. It reflects how we approach LLM application development, where production features need retries, timeouts, typed outputs and fallbacks as much as a good prompt.

When streaming helps, and when it does not

Streaming improves perceived speed for open-ended text that users read from top to bottom: chat answers, explanations, drafts and summaries. It adds little, or causes harm, in other cases.

Output typeStream it?Reason
Conversational answers and long explanationsYesUsers start reading immediately; perceived wait drops
Drafts the user will edit (emails, notes)UsuallyLets users stop early if the draft is going in the wrong direction
Structured output (JSON, form values, classifications)Rarely to the UIPartial JSON is not useful; validate the whole object first
Answers that must pass checks first (citations, policy, regulated advice)Buffer, or stream with a hold-backText already shown cannot be unshown
Short replies (a sentence or two)OptionalOverhead may outweigh benefit
Agent steps with tool callsStream progress, not raw outputShow ‘checking your order’ status; tool inputs arrive as partial JSON

The moderation point matters. OpenAI’s streaming guide notes that streaming makes moderation harder because partial completions may be more difficult to evaluate. If your product must check output before users see it, design a hold-back buffer (for example, release text sentence by sentence after a quick check) or do not stream that feature.

Latency also depends on the model. Reasoning models may think for a while before the first visible token; our article on reasoning models in production discusses when that wait is worth it and how to show progress during it.

Architecture and transport choices

The safest pattern is to stream from the model provider to your backend, and from your backend to the client. Calling the provider directly from a browser or app exposes keys and removes your ability to enforce limits, log usage and cancel centrally.

Backend responsibilities

  • Authenticate the user and apply rate and spend limits before calling the model.
  • Assemble context and call the provider with streaming enabled.
  • Translate provider-specific events into a small, stable event format for your clients.
  • Log usage, latency to first token, total duration, completion reason and errors.
  • Propagate cancellation upstream when the client disconnects or sends a stop request.

Client transport options

TransportStrengthsLimitationsGood fit
Server-sent events via EventSourceSimple, text-based, built-in reconnectionConstructor takes a URL, not a request body; per-browser connection limit on HTTP/1.1Read-only streams triggered by a separate POST
fetch with a streamed response bodyPOST with a JSON body, works with AbortController, full control of parsingYou implement parsing and reconnection yourselfMost chat and drafting features
WebSocketsBidirectional, low overhead for many messagesMore infrastructure; harder through some proxies; you build your own protocolReal-time collaboration, voice, multi-party sessions

MDN’s guide to server-sent events explains the event stream format, automatic reconnection with a configurable retry interval, and a key operational limit: when not used over HTTP/2, browsers allow a very low number of open SSE connections per browser (six), shared across tabs. Serving streams over HTTP/2 avoids most of that problem. Whichever transport you choose, check that every proxy, load balancer and CDN in the path passes streamed responses through without buffering, and that idle timeouts are longer than your slowest expected response.

For server-side API design, including versioning and limits for AI endpoints, see building APIs for AI features.

Rendering and UX: making streamed text pleasant to read

Painting every fragment as it arrives looks lively in a demo and tiring in daily use. A few rules make streamed text easier to read.

Rendering rules

  1. Batch updates. Buffer incoming text and render on animation frames or at a short fixed interval rather than on every event. This reduces layout work and flicker, especially on lower-end phones.
  2. Keep layout stable. Reserve space for the response area and avoid content jumping when markdown headings, lists or code blocks complete.
  3. Handle partial markdown. An unclosed code fence or table can make the whole message render wrongly until it completes. Use a renderer that tolerates incomplete syntax, or render completed blocks and keep the trailing block as plain text.
  4. Respect the user’s scroll position. Auto-scroll only if the user is already at the bottom; if they scroll up to reread, stop following and show a ‘jump to latest’ control.
  5. Show state clearly. Distinguish ‘thinking’, ‘writing’, ‘stopped by you’, ‘interrupted’ and ‘complete’. Users need to know whether an answer is finished.
  6. Make stop obvious. A visible stop control during generation is expected and saves cost.

Accessibility

Screen reader users experience streaming very differently. MDN’s guidance on ARIA live regions recommends aria-live='polite' for most updates, reserving assertive announcements for critical information, and suggests the log role for chat logs. Announcing every streamed fragment would be overwhelming. A practical pattern is to keep the streaming text out of the live region while it is generated, announce ‘response started’ and ‘response complete’ through a polite status region, and let users read the finished message at their own pace. Make sure the live region exists in the page before updates begin, since assistive technologies generally announce changes rather than newly inserted regions.

For broader UX guidance on trust, explanations and corrections in AI features, see designing UX for AI features.

Cancellation that actually stops the work

Users stop generation constantly: the answer is going the wrong way, they spotted a typo in their question, or they found what they needed in the first paragraph. If the stop button only hides the text, your backend and the model provider keep generating tokens you pay for.

End-to-end cancellation path

  1. Client. On the web, pass an AbortController signal to fetch. MDN’s AbortController documentation explains that abort() can cancel fetch requests, consumption of response bodies and streams, and that one signal can cancel several requests at once. On mobile, cancel the task or coroutine that owns the network call.
  2. Backend. Detect client disconnects and explicit stop requests, then cancel the upstream provider request. Many frameworks expose a request-aborted signal; make sure your handler checks it.
  3. Provider. Closing the upstream streaming connection is generally how you stop generation. Verify with your provider’s usage reporting that cancelled requests stop accruing output tokens.
  4. State. Save the partial response with a ‘stopped’ status so the conversation history is accurate and the user can continue or regenerate.

Edge cases to design for

  • Edit and resend: cancel the in-flight request before starting the new one, and ignore late events from the old one using a request identifier.
  • Navigation: leaving the screen or closing the tab should cancel, unless the product intends background completion.
  • Double submissions: disable send while streaming, or queue explicitly.
  • Billing and quotas: count usage from provider-reported tokens, including partial responses, so quotas stay fair.

Errors mid-stream and how to recover

Streaming breaks a common assumption: that an HTTP 200 means success. Once the stream has started, the status code is already sent, so later failures must be expressed as events.

What can go wrong

  • Provider errors inside the stream. Anthropic’s streaming documentation shows an overloaded_error arriving as an error event during high load, and notes that because the HTTP status is already 200, clients must check for error events in the stream. It also documents ping events and advises handling unknown event types gracefully. OpenAI’s Responses API similarly emits typed events such as response.output_text.delta, response.completed and error.
  • Network drops. Mobile users move between Wi-Fi and cellular, enter lifts and tunnels, or background the app.
  • Timeouts. Proxies and load balancers close connections they consider idle, especially during long thinking phases with no output.
  • Truncation. The model stops because it hit a token limit; the stream completes normally but the answer is incomplete.

A recovery policy

FailureUser seesSystem does
Error before first tokenShort retrying indicator, then a clear error with retryAutomatic retry with backoff, possibly to a fallback model
Error after partial outputPartial text kept, marked ‘interrupted’, with ‘continue’ and ‘retry’ optionsStore partial output; continue from it or regenerate on request
Network drop on mobile‘Reconnecting’ state; resumes or offers retryReconnect with the request identifier; fetch the completed answer if the backend finished it
Truncated by token limitNotice that the answer was cut short, with ‘continue’Detect the stop reason; request continuation
Idle timeout during thinkingUnchanged ‘thinking’ stateSend keep-alive comments or pings from the backend

Anthropic documents resuming an interrupted stream by saving the content received before the error and sending a new request that includes the partial response, so the model continues rather than starting again. It notes that tool use and thinking blocks cannot be partially recovered. Whatever provider you use, record the stop reason and partial output so recovery is possible and incidents can be analysed.

Mobile-specific concerns

Streaming on iOS and Android raises issues that rarely appear in a desktop browser.

  • HTTP client support. Confirm your networking stack exposes the response body incrementally rather than buffering it. Test this in your actual cross-platform framework, not only in a native prototype.
  • Backgrounding. When the app is backgrounded, the operating system may suspend or close network connections. Decide whether generation should continue on the server and be fetched on return, or be cancelled. For long tasks, server-side completion plus a fetch-on-resume or push notification is more reliable than holding a stream open.
  • Battery and rendering. Frequent UI updates are costly on mobile. Batch text updates and avoid re-rendering the whole conversation list for each fragment.
  • Network transitions. Use a request identifier so the client can reconnect and retrieve the result after a drop, rather than starting a new generation and paying twice.
  • Offline and poor signal. Detect connectivity before sending, queue clearly or tell the user, and avoid spinners that never resolve.

Server-side completion pattern

For mobile, a robust pattern is to treat each generation as a job with an identifier. The backend streams to the client while connected, keeps generating if the client drops (within a time and cost limit), stores the result, and lets the client resume or fetch the completed answer. It costs a little more to build but removes most ‘lost answer’ complaints.

Testing, monitoring and a release checklist

Streaming bugs hide in timing and network conditions, so they need deliberate tests. Our readiness checklist for LLM features covers the wider production picture; the items below are specific to streaming.

Tests to automate

  1. Replay recorded provider streams, including ping events, unknown event types and in-stream errors, through your parser.
  2. Inject errors at the first event, mid-stream and just before completion.
  3. Simulate slow, fragmented and dropped connections; confirm the UI states and recovery paths.
  4. Verify that stopping on the client cancels the backend and upstream request, using provider usage data.
  5. Check proxies and CDNs do not buffer streams in staging and production configurations.
  6. Run screen reader checks on web, iOS and Android for start, completion and error announcements.

Metrics to monitor

  • Time to first token and total generation time, by model and feature.
  • Share of responses stopped by users, interrupted by errors or truncated.
  • Tokens generated after a client disconnect (should be near zero).
  • Retry and fallback rates.

Release checklist

  • Streaming used only where it helps; structured and must-check outputs buffered.
  • Backend proxies the stream with authentication, limits, logging and a stable client event format.
  • Transport chosen deliberately, served over HTTP/2 where using SSE, with no buffering in the path.
  • Batched rendering, stable layout and tolerant markdown handling.
  • Stop control visible; cancellation propagates to the provider.
  • In-stream errors, network drops, truncation and timeouts handled with clear UI states.
  • Partial responses saved with status for continue and retry.
  • Accessibility: polite announcements for start and completion, not per fragment.
  • Mobile backgrounding and reconnection behaviour defined and tested.

Frequently asked questions

Should we use server-sent events or WebSockets for an AI chat feature?

For most chat and drafting features, a streamed fetch response or server-sent events is simpler and sufficient, because data flows mainly from server to client. WebSockets make sense for real-time collaboration, voice or multi-party sessions.

Does cancelling a stream stop us paying for tokens?

Only if cancellation reaches the model provider. Hiding the text in the UI is not enough. Abort the client request, detect the disconnect on your backend and close the upstream connection, then confirm in usage data that output stops.

Can the client call the model provider directly to reduce latency?

We do not recommend it for production. It exposes keys and removes central control over limits, logging, moderation and cancellation. A well-placed backend adds little latency compared with model generation time.

How do we stream answers that need fact or policy checks?

Buffer them, or stream with a hold-back: check completed sentences or sections before releasing them. Text already shown to the user cannot be withdrawn.

What should happen if a mobile user loses signal mid-answer?

Keep the partial text, show a reconnecting state, and use a request identifier so the app can resume or fetch the completed answer from the backend instead of starting and paying for a new generation.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. MDN Web Docs: Using server-sent events — accessed 9 November 2026. Event stream format, automatic reconnection and retry, and the six-connection per-browser limit without HTTP/2.
  2. MDN Web Docs: AbortController — accessed 9 November 2026. Aborting fetch requests, response body consumption and streams; one signal for several requests.
  3. Anthropic documentation: Streaming messages — accessed 9 November 2026. Event flow, ping events, in-stream overloaded errors after HTTP 200, handling unknown events and resuming interrupted streams.
  4. OpenAI API documentation: Streaming API responses — accessed 9 November 2026. Typed streaming events (delta, completed, error) and the difficulty of moderating partial completions.
  5. MDN Web Docs: ARIA live regions — accessed 9 November 2026. Polite versus assertive announcements, the log role for chat and creating live regions before updating them.

Is your streaming LLM feature ready for flaky networks and impatient users?

Share your current design or prototype, and we will review transport, cancellation, error handling and accessibility, and propose fixes.