Browser-Only Streaming Chat App with a Stateless Relay
System DesignModel answerLast updated
Design a streaming AI chat product where conversation content lives only in the browser, a stateless relay protects provider keys, and refresh begins a fresh chat.
You are asked to design a conversational AI assistant for the web, with the client side as the main focus. The product must obey these rules:
- Messages and conversation history exist only inside the user's browser. No server-side database may hold them.
- Replies from the assistant must appear incrementally, token by token.
- Reloading the page begins an entirely new conversation. Nothing is restored.
- Users must be able to sign in, and the client must handle their credentials without ever exposing the secrets used to call the model provider.
Walk through your design and make sure it covers:
- Architecture and data flow: the browser app, an edge or relay layer, and the upstream model provider, plus the full path of one chat turn.
- Streaming: how tokens are delivered to the UI, and the trade-offs between Server-Sent Events and WebSockets.
- Session handling without a database: where conversation state and auth tokens live, and how a reload resets the conversation.
- Security: sign-in flow (OAuth/OIDC with PKCE), token lifetimes and scopes, protection of provider keys, and CORS, CSP and XSS concerns.
- Rate limiting and abuse control when there is no durable server-side store.
- Failure handling and retries: dropped connections mid-stream, 429 and 5xx responses, timeouts, expired tokens, and histories that grow too large for the context window.
- Trade-offs of the no-database approach: privacy and cost benefits versus lost continuity, bigger request payloads, and weaker analytics or personalization.
State any scale assumptions you make and justify the choices you consider most important.
Hints
Hint 1
Separate the conversation state (memory only, wiped on reload) from the authentication state (which may survive a reload so users are not forced to sign in again).
Hint 2
Native EventSource cannot send POST bodies or Authorization headers. Think about what you would use to read an event stream from a POST request, and what must happen if an error occurs after the 200 status has already been sent.
Hint 3
No database does not mean no counters. Consider short-lived, expendable rate-limit state, claims embedded in short-lived tokens, per-user concurrent stream caps, and hard limits on body size and output length.
Hint 4
Because the client resends the full history on each turn, think about how token cost grows with conversation length and how you would trim or summarize history on the client.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Browser-Only Streaming Chat with a Stateless Relay
1. Requirements and scale
Functional: sign in, send a message, watch the reply stream, stop or regenerate a reply, and get a clean slate on reload.
Non-functional: no persisted message content anywhere on the server (databases and logs), p50 time to first token under about 1 s, and provider secrets never reach the browser.
Illustrative scale: 1M daily users x 5 conversations x 10 turns is about 50M requests/day, roughly 600 RPS average and about 3k RPS at peak. If a reply streams for about 20 s, peak implies around 60k concurrent open streams, so the relay must be cheap per connection. Because the client resends the whole history, a turn-20 request may carry about 8k tokens, and cumulative input cost grows roughly quadratically with conversation length.
2. Architecture
Browser SPA --HTTPS (fetch + SSE)--> Stateless relay / BFF --HTTPS stream--> LLM provider
(in-memory state) (holds provider key) (zero-retention terms)
^ |
+---------- OIDC IdP (auth code + PKCE)
- SPA: owns all conversation state in a JS memory store, renders streamed tokens, handles sign-in.
- Relay: stateless workers that verify the token, enforce limits, attach the provider key from a secret manager, forward the request, and pipe the stream back.
- Provider: used under a zero-data-retention agreement so the privacy promise holds end to end.
One turn: the user submits, the SPA appends to messages[], trims to the context budget, and POSTs the full history. The relay validates, opens the upstream stream, and re-emits deltas as SSE events. The SPA appends each delta to the in-progress assistant message and finalizes it on done.
3. API sketch
POST /v1/chat with request_id, model, messages, max_tokens. The response is text/event-stream with delta, done and error events plus a comment heartbeat about every 15 s. Failures before the first byte use real HTTP codes (401, 413, 429, 5xx). Failures after streaming begins must be sent in-band as event: error, since the 200 is already committed.
4. Streaming: SSE vs WebSockets
I choose SSE framing read through fetch and a ReadableStream. Native EventSource is GET-only and cannot set an Authorization header, so it cannot carry the history. A turn is one request and one one-way stream, which is exactly SSE's shape.
| SSE over HTTP | WebSocket | |
|---|---|---|
| Direction | Server to client | Full duplex |
| Infra | Plain HTTP/2, CDN and proxy friendly, standard auth | Upgrade handshake, connection management |
| Scaling | Any node can serve any request | Long-lived stateful connections |
| Cancel | Abort the fetch | Cancel frame |
| Best for | Per-turn generation | Voice, collaboration, server push |
Operational details: disable proxy buffering, send heartbeats so idle timeouts do not kill slow generations, and batch DOM updates per animation frame rather than per token.
5. Session management with no database
Conversation state lives in a JS variable only. localStorage and IndexedDB persist and are readable by XSS; sessionStorage survives reload and would violate requirement 3. A reload destroys the heap, so a fresh conversation is automatic.
Auth state is separate, since a reload should not force re-login. Two options:
- BFF (preferred): the relay completes the OIDC code exchange and sets an
HttpOnly; Secure; SameSite=Strictcookie containing an encrypted, self-contained session. No server table is needed and the browser never sees tokens. - Pure SPA: authorization code with PKCE, access token in memory with a 5 to 15 minute life, and either a rotating, ideally sender-constrained refresh token or silent re-auth using the identity provider's own session.
6. Security
- Provider key: only in the relay's secret manager, rotated regularly. The browser never calls the provider.
- OIDC: validate
stateandnonce, exact-match redirect URIs, a narrow scope such aschat:write, and checkiss,aud,expand signature on every request. - CORS: allowlist the app origin only; no wildcard with credentials.
- CSP:
default-src 'self', nonce-based scripts,connect-srclimited to the relay and IdP,frame-ancestors 'none', Trusted Types. - Model output is untrusted: sanitize rendered Markdown (for example with DOMPurify), never assign raw text to
innerHTML, and blockjavascript:links. - Privacy in logs: record only metadata such as hashed user id, token counts, latency and status. Never log bodies.
7. Rate limiting without durable storage
"No database" means no persisted content, not no counters. Say that explicitly.
- Token buckets keyed by user and IP, held in memory per node or in an ephemeral TTL store (persistence off), limiting requests and tokens per minute.
- A cap of about 2 concurrent streams per user.
- Quota or tier claims inside short-lived JWTs, which also bound how long a revoked user keeps access.
- Hard caps on body size (for example 256 KB),
max_tokens, and allowed models. - A hashed user identifier forwarded to the provider so it can apply its own limits.
- Bot defenses such as a challenge on sign-up or anomalous traffic.
8. Failure modes
- Dropped stream: keep the partial text, show it as interrupted, and offer "continue" or "retry". Without server state, a retry resends the history, optionally with the partial reply as a prefill.
- 429: honor
retry_after, use exponential backoff with jitter, and show a clear message. - 5xx or timeout: retry only if no tokens were received, or the user asks; a
request_idhelps avoid duplicate work. - Token expiry: refresh once and replay the request; on failure, route to sign-in while keeping the in-memory chat.
- Oversized context: trim client-side by dropping oldest turns, keeping the system prompt, or summarizing older turns; the relay returns 413 as a backstop.
- User cancel: abort the fetch so the relay cancels upstream and stops billing.
9. Trade-offs
Gains: strong privacy story, minimal compliance surface, no storage cost, and a simple, horizontally scalable relay.
Costs: no continuity across reloads or devices, larger requests because the full history is resent each turn, higher input-token cost, little server-side analytics or personalization (mitigate with opt-in, content-free metrics), and harder abuse investigation.
Common mistakes: storing history in sessionStorage, using EventSource for a POST, putting the provider key in the client, forgetting in-band errors after the 200, logging request bodies, and rendering model output unsanitized.