Building a Production-Ready LLM Chat Web App: Streaming, Sessions, and Graceful Degradation
A practical engineering guide to building a chat web application for large language models. This article covers the four-layer architecture, SSE-based streaming with fetch, stop generation and upstream cancellation, session persistence, context truncation, rate limiting with token buckets, file upload parsing, voice input handling, and a pre-launch checklist—all with measurable acceptance criteria and degradation rules for real-world failure scenarios.
1. Audience and Prerequisites
This article assumes you are familiar with HTML, JavaScript or TypeScript, understand HTTP and JSON, can build a basic Node.js or Python service, and know the basics of Redis and relational databases. The approach described here is not tied to any specific model vendor. The examples use a service compatible with the Chat Completions protocol; integrating other services only requires replacing the adapter code in the model access layer.
A chat web page may look like nothing more than an input box plus a message list, but in production you will encounter streaming rendering, reconnection after disconnects, over-long context, exhausted quotas, file parsing failures, and denied microphone permissions. Each scenario needs an explicit handling rule.
2. Requirements with Testable Acceptance Criteria
Requirements should be written in verifiable form. Every feature should have a scenario, a judgment condition, and a test method. The numbers in the table below are suggested starting targets—confirm them through load testing in your own environment.
| Feature | Acceptance Metric | Suggested Target | Test Method |
|---|---|---|---|
| Basic chat | Follow-up answers can reference earlier context | Follow-up test pass rate ≥ 95% | Prepare 20 multi-turn test cases, judged manually |
| Streaming output | Time to first delta | P95 < 2 seconds (excluding model queueing) | Record elapsed time from request sent to first delta |
| Stop generation | Output stops after clicking stop | Frontend stops rendering within 1 second; server cancels upstream request within 3 seconds | Click stop mid-generation; check network and server logs |
| Session management | History recoverable after page refresh | 100% recovery success, message order consistent | Create a session, refresh, reopen browser, compare |
| File upload | Clear error on oversized or wrong-format files | Size and format limits clearly shown in UI | Upload oversized and invalid files, 5 times each |
| Voice input | Text path remains usable when mic is denied | Voice button disabled with hint; text input still sends | Deny permission in browser, then send text |
| Web search sources | Sources are traceable | Each citation includes a title and a working link | Spot-check citation link validity |
Priorities should also be marked. P0 means features without which the product cannot launch: basic chat, streaming output, stop generation, session recovery, and rate-limit notices. P1 means features that significantly affect the experience: file upload, regeneration, and theme settings. P2 means deferrable features: voice playback, session export, and web search.
3. Feature Structure and Priorities
Organize features into modules with clear boundaries to ease scheduling and test grouping.
Chat Web App├── Session layer: create, switch, rename, soft delete, search, export (P0 / P1 / P2)├── Input layer: text input, file upload & preview, voice input (P0 / P1 / P2)├── Conversation layer: streaming render, reasoning collapse, source citations, stop & regenerate├── Settings layer: model selection, voice playback toggle, theme & font size└── Account & quota layer: login state, remaining quota, rate-limit and error notices
Session export must only allow users to export their own sessions, in Markdown or JSON format. Before exporting, warn users that the file contains the full conversation and should be kept safe. Exported content must not include access keys, internal IDs, or other users’ data.
4. Four-Layer Architecture and Interface Boundaries
A four-layer structure is recommended, with each layer communicating only through explicit interfaces.
- Frontend display layer: handles input, rendering, and local state. Use
fetchto read the streaming response body rather than relying onEventSource, which only supports GET requests and cannot carry a message body. - Gateway layer: handles authentication, request validation, rate limiting, and access logs uniformly. Never store model service keys in the browser; keys exist only in server-side configuration or a key management system.
- Business service layer: manages session and message storage, assembles context, and injects file parsing and retrieval results.
- Model access layer: shields upper layers from field differences between services, exposing a unified message structure only.
The unified message structure can be defined as:
{"id": "msg_01H...","role": "user | assistant | system","parts": [{ "type": "text", "text": "..." },{ "type": "file_ref", "file_id": "f_...", "summary": "..." },{ "type": "source", "title": "...", "url": "..." }],"status": "pending | streaming | done | cancelled | error","created_at": "2026-11-24T10:00:00Z"}
The business layer only reads and writes this structure. The model access layer converts parts into the format required by the upstream service and converts upstream incremental responses into unified events.
4.1 Gateway Rate Limiting
The gateway uses a token bucket algorithm. Each user gets one bucket, with capacity equal to the allowed burst count, refilled at a fixed rate. Reading, deducting, and refilling tokens must be done atomically in a Redis Lua script—otherwise concurrent requests can slip through over the limit. Also set a looser bucket per IP to prevent abuse by unauthenticated requests.
When the limit is exceeded, return HTTP 429 with a Retry-After header. The frontend should show a countdown based on this value instead of simply reporting “request failed.”
4.2 Context Truncation
When the context exceeds the model’s window, handle it in this order:
- Always keep the system prompt and the most recent user message.
- Reserve
max_output_tokensfor the current response; the remaining budget goes to history. - Drop messages starting from the oldest until the budget is satisfied. Dropped turns can first be summarized, with the summary inserted as a system message.
- If file content exceeds the budget, inject only the first few parsed segments and note “content truncated” in the context.
Token counts can be computed with the tokenizer provided by the model vendor. Without one, roughly estimate ~1.5 tokens per Chinese character and ~1 token per 4 English characters, keeping a 20% margin.
5. Implementing Streaming Output
5.1 Event Protocol
The server pushes events in SSE format, setting Content-Type: text/event-stream in the response headers and disabling caching. Each event contains event, id, and data fields. Event types:
delta: incremental text,datais{"message_id":"...","seq":5,"text":"..."}.seqstarts at 1 and increases monotonically; the frontend uses it to detect loss and out-of-order delivery.reasoning: incremental reasoning content, same structure asdelta, rendered into a collapsible area.source: web search results, with title and link.done: generation finished;dataincludesfinish_reasonandusage.error: generation failed;dataincludescode(e.g.,rate_limited,upstream_timeout,context_too_long) and a user-facingmessage.
Every 15 seconds, the server sends a comment line : ping to prevent proxies or load balancers from closing the connection due to inactivity.
5.2 Reading the Stream on the Frontend
async function streamChat(body, onEvent, signal) {const res = await fetch('/api/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),signal,});if (!res.ok) throw new Error(`HTTP ${res.status}`);const reader = res.body.getReader();const decoder = new TextDecoder();let buffer = '';while (true) {const { value, done } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });let idx;while ((idx = buffer.indexOf('\n\n')) !== -1) {const raw = buffer.slice(0, idx);buffer = buffer.slice(idx + 2);const ev = parseSSE(raw);if (ev) onEvent(ev);}}}
parseSSE only needs to parse event: and data: lines; comment lines are ignored.
5.3 Stop Generation and Server-Side Cancellation
When the user clicks stop, the frontend calls AbortController.abort(), immediately stops reading, and marks the message status as cancelled. This only stops rendering—the server may still be consuming tokens. The server must therefore listen for connection close events.
// Pseudocode in the gateway or business servicereq.on('close', () => {if (!res.writableEnded) {upstream.abort(); // Cancel the upstream model requestdb.updateMessage(msgId, { status: 'cancelled' });}});
After cancellation, the partially generated content stays in the session, labeled “stopped.” The user can choose to regenerate.
5.4 Disconnects, Reconnection, and Degradation
SSE connections may break mid-stream. Handle it as follows:
- The server keeps a buffer of recent events for each in-progress message, retained for a configurable period (e.g., 60 seconds).
- The frontend records the last received
seq. After a disconnect, it requestsGET /api/messages/{id}/stream?after_seq=Nto resume. - If the buffer has expired, or resumption fails twice, mark the message as
error, display the partial content received, and offer a “Regenerate” button.
Do not resend the full request just to resume. Duplicate requests cause double billing and produce a different answer.
5.5 Incremental Rendering on the Frontend
Each item in the message list uses a stable key—the message ID, never the array index. On delta, update only the current message’s text node; do not rebuild the list. During scrolling, auto-follow if the user is already at the bottom; if the user scrolls up to read, stop auto-scrolling and show a “Jump to latest” button.
Rendering frequency can be batched with requestAnimationFrame, refreshing at most once per frame. This keeps the page from janking under high-frequency deltas due to reflow.
6. Session Management
The data model needs at least two tables:
sessions:id,user_id,title,created_at,updated_at,deleted_at.messages:id,session_id,role,content(JSON),status,seq,created_at.
Use soft deletion for sessions: rows with a non-empty deleted_at are no longer shown. This enables recovery after accidental deletion and supports auditing. Renaming only updates title and updated_at.
On page refresh, the frontend first requests the session list, then loads recent messages with cursor-based pagination. Messages are sorted by (session_id, seq) to guarantee stable ordering. Messages with status of streaming should be treated as interrupted on page load, following the rules in 5.4.
7. File Upload and Parsing
The upload flow has three steps—validation, storage, and parsing:
- The frontend validates size and extension with clear error messages. The server must validate again, checking the file header’s MIME type—never trust the extension alone.
- After validation, save the file to object storage, and record the file ID, owning user, and parsing status in the database.
- Parsing runs as a background task. When complete, the text is written to the
file_refsummary field, truncated per 4.2 if it exceeds the budget.
Suggested threshold examples: single file no larger than 10 MB, up to 3 files per message, and only PDF, TXT, Markdown, DOCX, and common image formats allowed. Display these limits in the UI so users see them before uploading.
If parsing fails, mark the file status as failed and show “Parsing failed—please try a different format.” The text input path is unaffected.
8. Rate Limiting, Quotas, and Degradation
Rate limiting, quota exhaustion, and upstream failures need separate handling, because the user-facing messages and responses differ.
- Rate limited (429): show a
Retry-Aftercountdown; automatically re-enable the send button when it ends. - Quota exhausted: show remaining quota and reset time, with an option to upgrade or wait. Don’t discover a lack of quota mid-request—check the quota endpoint before sending.
- Upstream timeout or 5xx: retry once after 500 ms to 1 second, with random jitter. After consecutive failures reach a threshold, open the circuit breaker and return a friendly message during the cooldown period to avoid overwhelming the upstream.
- Over-long context: the server truncates per 4.2 first; if still too long, return
context_too_longand prompt the user to start a new session or delete part of the history.
Circuit breaker thresholds must be set based on your upstream’s error rate and timeout before launch—don’t copy the example values.
9. Voice Input and Voice Playback
Voice features split into input (ASR) and output (TTS), both optional.
Voice input can use the browser’s speech recognition API or a server-side ASR. Either way, handle these cases:
- Microphone permission denied: disable the voice button and show “Microphone access is off—you can still type.” The input box and send button remain usable.
- Recording cancelled mid-way: discard the recording; do not send it to the server.
- Empty recognition result: prompt the user to record again; do not send an empty message.
Voice playback is off by default. When enabled, each answer is read aloud once upon completion. If playback fails, the message text still displays normally. Users can stop playback at any time.
TTS and ASR audio data are user privacy content. Inform users before upload and provide an opt-out in settings.
10. Testing and Launch Checklist
Go through this list before launch:
- Streaming disconnect: drop the network for 5 seconds mid-stream, then recover; the message should resume or be correctly marked as errored.
- Stop generation: stop mid-generation; the frontend stops rendering within 1 second and server logs show the upstream request was cancelled.
- Quota exhausted: with zero quota, the send button gives a clear message and no empty answer is produced.
- Rate limiting: rapid-fire sends beyond the threshold return 429; the frontend shows a countdown.
- Microphone denied: after denying permission, the voice button is disabled and text sending works.
- File limits: oversized and excess-count files are rejected with clear messages.
- Forged file format: an executable renamed to PDF should be rejected by the server.
- Over-long context: continuous follow-ups in a long conversation produce no errors; after truncation, answers still reference recent content.
- Session recovery: after refresh and after logging in on another device, history is complete and correctly ordered.
- Deletion and export: deleted sessions no longer appear; exported files contain no other users’ data.
- Key management: check frontend code and network requests to confirm no access keys are exposed. Check logs to confirm no keys or full user private content appear.
Each item should have a corresponding automated test case or a manual record. After launch, continuously monitor time to first token, error rate, 429 ratio, and circuit breaker trips as input for the next optimization round.
11. Risks and Precautions
Chat data typically contains user privacy and business information—encrypt it at rest and verify ownership on every access. A session ID must never serve as the sole authorization credential; check whether the current user owns the session on every read and write.
File upload is a common attack vector. Run parsers in isolated processes or containers with timeouts and memory limits to prevent malicious files from exhausting resources.
Do not log full user inputs or model outputs. Log only request IDs, latency, status codes, and error codes. When troubleshooting genuinely requires more, save it in redacted form with a retention period.
Finally, all the numbers and thresholds in this article are starting points. Every team faces different user scale, upstream services, and hardware—determine final parameters through load testing and gradual rollouts.
