Design: ChatGPT-style assistant at scale
Stateless chat servers build each turn's context under a token budget, route to a small or large model, stream tokens over SSE, and persist conversations in a sharded store behind per-user quotas.
Fundamentals you'll use
How it works
- Scale: ~10M DAU, ~150M messages/day, ~5k msg/s at peak, TTFT p50 under 1 s.
- Order context most-stable-first, so prompt caching covers everything except the newest messages.
- The router sends ~85% to a small model; the large-model 15% still drives ~75% of cost.
- The worst failure is cross-user exposure: scope every store by user_id in the key, never in the prompt.
- Set SLOs on TTFT p95 and stream completion rate: a stream dying at token 50 still logs HTTP 200.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your assistant's long chats show almost zero cached input tokens. The context builder sends a summary plus the last 20 turns, and both slide forward by one turn on every message. Cheapest fix?
Go deeper
Full explanation
Requirements
Functional: multi-turn chat with streamed answers; history (list, search, delete); file and image uploads; opt-in memory across sessions; free and paid tiers.
Non-functional: ~10M DAU, TTFT p50 < 1 s, 99.9% availability, a hard cost ceiling per free user, zero cross-user data exposure, and a safety policy enforced on input and output.
What I'd ask first:
- Free vs paid split, and which model and quota does free get?
- Our own GPUs, provider APIs, or both?
- Which modalities at launch: text, images, files, voice?
- Retention, regions and memory consent (GDPR)?
- Peak-to-average ratio and target TTFT?
Highest-cost failure: one user seeing another user's conversations. It ends trust overnight, and it has happened in production (ChatGPT, March 2023).
High-level design
Online path. The client opens an SSE stream (Streaming responses (SSE)) to a gateway that authenticates and enforces rate limits (Rate limiting) and the token quota. A stateless chat service loads the conversation: recent turns from Redis, the rest from a message store sharded by user_id. A context builder assembles the prompt under a token budget, always in the same order: system prompt, pinned memories, rolling summary, recent turns, retrieved file chunks (Context engineering). An input safety classifier runs in parallel with prefill. A router (Model routing & cascades) sends ~85% of messages to a small model and escalates hard prompts, or a user's Think request, to a large model or a reasoning model (Reasoning models & test-time compute). Tokens stream back through output moderation; on completion the service persists the message and its token counts.
Async path. A queue drives everything that can wait: title generation, summary refresh, memory extraction (Agent memory), file parsing and embedding, usage metering for quotas and billing, and sampled evals.
Code Context builder: fixed budget, cache-friendly order
# One turn's prompt under a fixed budget, ordered most-stable-first so the
# provider's prefix cache covers everything except the newest messages.
BUDGET = 16_000 # prompt tokens; the answer needs its own headroom
BLOCK = 10 # the summary absorbs old turns 10 at a time, never one by one
def build_context(conv, question: str) -> list[dict]:
msgs = [system(SYSTEM_PROMPT)] # same for every user: always cached
msgs += [system(m) for m in conv.pinned_memories] # chosen once per chat, not per turn
if conv.summary: # covers turns [0, summarized_upto)
msgs.append(system("Earlier in this chat: " + conv.summary))
live = conv.turns[conv.summarized_upto:] # verbatim tail, append-only
msgs += [t.as_message() for t in live]
if conv.file_index: # per-question, so it goes last
chunks = conv.file_index.search(question, k=6)
msgs.append(system("From the user's files:\n" + "\n".join(chunks)))
msgs.append(user(question))
used = count_tokens(msgs)
if len(live) >= BLOCK or used > 0.8 * BUDGET: # async: never on the hot path
enqueue("summarize", conv.id, upto=conv.summarized_upto + BLOCK)
if used > BUDGET: # rare: the summary job fell behind
msgs = drop_oldest_live_turns(msgs, BUDGET)
return msgsReal example
A free user sends message #31 in a chat about a 40-page PDF. The gateway checks the quota in Redis (~2 ms): 61k of 100k daily tokens left. The context builder assembles ~11k tokens: 1.5k system prompt and 0.5k pinned memories (both cached), a 1.5k summary of turns 1–20, turns 21–30 verbatim (4.5k) and 6 PDF chunks (3k). The input classifier finishes in ~30 ms, beside prefill. The router scores the question as easy, so the small model answers: first token at ~450 ms, 350 tokens at ~80 tok/s, ~4.8 s in total. The service stores the message, debits 11.1k input and 350 output tokens, and enqueues a summary refresh because 10 turns have piled up since the last one.
Trade-offs +4 · −4
+ You gain
- Small-by-default routing: at the assumed prices, ~5× cheaper than sending everything to the large model.
- Stateless chat servers scale horizontally; the message log is the single source of truth.
- A most-stable-first prompt order makes prefix caching pay off on every long chat.
- Token-based quotas turn free-tier cost into a bounded, tunable number.
− You pay
- Router mistakes are silent quality regressions; the router needs its own eval set and alerts.
- Summaries lose detail, so very long chats still degrade.
- ~30k long-lived SSE connections at peak complicate load balancing and deploys (draining, reconnects).
- A self-hosted small tier plus a provider's large tier means two serving stacks to run.
Use it when
Open-ended assistants with millions of users and a free tier, where cost per active user, TTFT and data isolation drive the architecture.
Avoid it when
Narrow single-call flows (extraction, form filling) or low volume: one model behind an API, without routing, memory or quotas, is cheaper to build and run.
Numbers to know 5
- Traffic: 10M DAU × 15 messages/day = 150M/day ≈ 1.7k msg/s; ×3 at peak ≈ 5k msg/s, or ~30k open SSE streams at ~6 s per answer.
- Tokens: ~3k input (system + history + files) and ~400 output per message → 450B input + 60B output tokens/day.
- Cost (assumed prices): 85% small at $0.15/$0.60 per 1M (~$88k) + 15% large at $2.50/$10 (~$259k) ≈ $350k/day ≈ $10M/month; large is 15% of traffic, ~75% of cost.
- Storage: 150M messages × ~1.5 KB ≈ 225 GB/day ≈ 80 TB/year before replication.
- TTFT budget ~1 s: gateway 20 ms + history 20 + memory/file retrieval 80 + router 20 + queue and prefill ~500; safety runs in parallel.
Common pitfalls 4
- Shared caches and connection pools leaking across users: in March 2023 a redis-py cancellation bug let some ChatGPT users see others' chat titles. Key everything by user and test cancelled requests.
- A changing prefix (a timestamp in the system prompt, a summary rewritten every turn) silently disables prompt caching and pays full price on every input token.
- Quotas in messages instead of tokens: a few users pasting 100k-token documents consume the free-tier budget.
- Treating a dropped stream as success: resume by message id (
Last-Event-ID) or regenerate, and alert on stream completion rate, not HTTP status.
Interview questions 3
Answer out loud first, then reveal.
A conversation has 300 turns. What do you send to the model?Show answer
Not 300 turns. I build each prompt under a fixed budget in a stable order: system prompt, memories pinned at chat start, a rolling summary of old turns, the recent turns verbatim, then file chunks for this question. The summary absorbs turns in blocks of ten, so the prefix stays cacheable between refreshes; a one-turn sliding window would miss the cache every time. Summaries drop details, so I also embed old turns and retrieve them when the user refers back, and I test this with long-chat recall evals, not single-turn ones.
Inference cost doubled last month while DAU grew 10%. How do you investigate?Show answer
I decompose cost per DAU into messages per user × tokens per message × price per token × route mix, straight from the metering log, and find the factor that moved. The usual suspects: a launch raised average input (uploads, more memories), the router's escalation rate drifted from 15% to 30%, a reasoning mode became the default, or the cache hit rate collapsed because someone put a timestamp in the system prompt. I fix that factor, then alert on each one separately so the next regression shows up in a day, not on the invoice.
Your main provider goes down at peak. What happens?Show answer
The system degrades instead of failing. The gateway has a priority order, paid before free, and a fallback chain: primary large model, then a second provider, then our self-hosted small model with a visible notice. Free-tier quotas tighten automatically under load. Per-provider circuit breakers and retries with jittered backoff matter most: without them, retries during a brownout multiply load and turn a partial outage into a total one. I'd rehearse it in a game day, because a fallback path that is never exercised is usually broken.
Deep dive 5
Conversations & context
Messages are an append-only log keyed by (user_id, conv_id, seq) and sharded by user_id, so one user's chats live on one shard and a deletion request touches one partition. A parent_id turns edits and regenerations into a tree. DynamoDB, Cassandra or sharded Postgres all fit; the last ~20 turns of active chats sit in Redis. Context goes most-stable-first so prompt caching (Prompt caching) covers everything but the newest messages: memories are pinned when the chat starts, and the summary absorbs old turns in blocks of ~10 instead of sliding by one, because a sliding window changes the prefix on every turn. Summaries lose detail (Lost in the middle & context rot), so long chats also embed old turns and retrieve them when the user refers back.
Routing & GPU capacity
Every message defaults to the small model; a classifier escalates coding, math, long documents or low-confidence cases, and a user-chosen Think goes to a reasoning model with a capped thinking budget. Evaluate the router on a labeled set: missing prompts that deserved escalation costs more trust than it saves. Capacity, if self-hosted: ~2M output tok/s at peak needs ~1.5k H100s, assuming ~2.5k tok/s per GPU for an ~8B model, ~400 for a ~70B model, and an 85/15 split. Most teams self-host the small tier, buy provisioned throughput for the large one, and keep a second provider behind an LLM gateway (LLM gateway) for failover. Under pressure, degrade instead of failing: free users fall back to the small model before anyone sees a 503.
Free tier: limits & quotas
Two layers at the gateway. Rate limits protect capacity: a token bucket per user and per IP (e.g. 20 messages/min) returning 429 with Retry-After. Quotas protect the budget: a token allowance per rolling window (e.g. 10 large-model messages per 5 h, then the small model), counted in Redis with atomic INCRBY and reconciled nightly against the metering log. Meter tokens, not messages: one question over a 100k-token PDF costs as much as 50 short chats. Reserve the worst case before the call (input + max_tokens) and settle the actual after, so ten parallel tabs can't overspend. Abuse control: phone verification for free sign-ups, device fingerprints, and anomaly detection on accounts that behave like resold API access.
Memory, files & images
Memory across sessions is an offline job: when a chat goes idle, a small model extracts durable facts ("vegetarian", "writes Go") into a per-user store with source and timestamp; new chats pin the most relevant few (~500 tokens). Users must see, edit and delete memories, and a temporary-chat mode skips both reads and writes. Files upload to object storage through a signed URL and are parsed, chunked and embedded asynchronously into a per-conversation index (Document ingestion & parsing, Chunking strategies); files under ~5k tokens go straight into context instead. Images go directly to a multimodal model (Multimodal models), after a known-CSAM hash match and an image safety classifier. Every store is scoped by user_id in the storage key, never by an instruction in the prompt.
Safety & observability
Input: a fast classifier (~10–50 ms) runs beside prefill and cancels the stream if it fires. Output: moderation every few hundred tokens and at completion, with a retract path for text already streamed. Guardrails (Guardrails: input, output, action) cover self-harm (answer with resources rather than refuse), jailbreak patterns and PII. Per request, log route, model, TTFT, tokens/s, input/cached/output tokens, cost and safety verdicts; keep prompt text only in sampled traces under the retention policy (LLM observability & tracing). Set SLOs on TTFT p95 and stream completion rate: a stream that dies at token 50 still logged HTTP 200. Online quality: thumbs, regenerate rate and abandonment, sliced by route, plus a nightly LLM-as-judge pass (LLM-as-a-judge) over sampled conversations.