Case brief
Understand the scenario, task, and constraints.
A conversation product around a stateless model
Design a consumer chat assistant for web and mobile. Many people send many messages, watch answers arrive token by token and expect to reopen a conversation days later with its history intact. The GPU bill has to stay under control while all of that happens.
The difficulty is that the model is stateless and the product is not. A large language model (LLM) receives one prompt, returns one answer and keeps nothing between calls. The service around it must store every turn, scope it to the right user, rebuild a bounded prompt for the next turn and stop spending compute when nobody is reading. Every token the service remembers and re-sends is paid for again on the next turn, so state and cost are the same problem seen from two sides.
The core idea fits in one sentence: store every turn, send the model only what this turn needs, and stream the answer back. The figure below draws that path. A request is either rate limited or admitted; an admitted turn loads its conversation, builds a bounded context, waits in a fair queue for the model pool, and is streamed back while its text is persisted.
Follow Sam's message through one turn
The source traces a single message from Sam, a free-tier user. Sam presses send. Admission and quota checks run first, and paid users may be served ahead of Sam when capacity is tight. The service then loads Sam's conversation, including any deletion rules that apply to it. If the whole history will not fit in the prompt, it is not pasted in raw; the service sends a summary and the recent turns instead.
Input moderation checks the message before any GPU time is spent. A GPU pool generates the answer and streams tokens back, while batching and fair queues keep a burst from one group of users from stalling everyone else. Output moderation checks the stream on its way to Sam's screen. If the turn uses tools such as files, search or code, they run sandboxed and with a cap on steps. The finished turn is stored. If inference fails partway, the service fails over to another pool or region and keeps the saved partial answer; it never pretends the turn did not happen.
That gives the path you will draw on the whiteboard: admit, load state, infer and stream, moderate, persist.
What you need to design
The prompt arrives as one line: "Design ChatGPT." Candidates report it from OpenAI interviews, and a variant, "Design the Claude chat service", from Anthropic interviews. Neither comes with a worked design or a workload. The source builds one design that answers both. The Claude wording uses the same architecture with more interview time on batching, GPU capacity, queues and failover.
This case covers one slice of the product: sessions, streaming, admission, moderation and cost. Training a foundation model is out of scope; the design serves models that already exist, so leave "we'll train a new model" out unless the interviewer asks. Every scale figure is a whiteboard assumption, not a measurement of any real service. Treat each number as a placeholder for measured throughput.
You should be comfortable with LLM serving basics (tokens, batching and streaming), caching, rate limiting and basic cloud architecture. The source draws on related designs for parts of the answer: the Enterprise Knowledge Assistant for user-filtered retrieval, the Secure Multi-Tenant AI Platform for quotas, fair queues and regional control, and Observability and Production Diagnosis for stage timing and abandonment. By the end you should be able to explain the system end to end at interview depth and answer follow-ups on sizing, conversation state and context, streaming and cancellation, model routing, quotas and fair queues, moderation, regions and release gates.
Next: build the answer in interview order.
Start the walkthroughDesign walkthrough
Follow the reasoning from discovery to delivery.
1. Clarify what the chat product includes
The question bank lists jumping to architecture before clarifying scope as the first failure mode for this prompt. One OpenAI Forward Deployed Engineer (FDE) candidate reported the interviewer stopping them with: "What questions would you ask the customer before designing anything?" Since "Design ChatGPT" gives you nothing else, ask what it means in this room before drawing.
Start with the mission. The framework on the same page asks: "Are we optimising for response time, cost, accuracy, or equity of coverage? Who's the primary user?" Then ask the six questions below. If the interviewer does not confirm an answer, state the assumption aloud and design to it. The table shows the source's assumed answers and the part of the design each one decides.
Source assumptions and the architecture each one changes.
| Question | Assumed answer | What it decides |
|---|---|---|
| Consumer app, API, or both? | Consumer web and mobile chat | Sessions and UX matter; API quotas are out of scope |
| How many users? | 100M daily active users | Sizing, sharding and multi-region from day one |
| Free and paid tiers? | Yes, with different models and quotas | Routing and rate limits are per tier |
| Multi-turn memory? | Yes, within a conversation; optional across conversations | Conversation store plus a user-scoped memory store |
| File uploads and tools? | Files, web search, a code sandbox | Untrusted content enters the prompt; sandboxing |
| Do we train the model? | No, we serve given models | The design is serving, state and safety, not training |
A weak answer draws a load balancer in front of a model and stops. It forgets that the model is stateless and the product is not. A strong answer names three hard problems in the first two minutes: conversation state that grows every turn, streaming at very high concurrency, and cost that scales with tokens rather than requests. The source's opening line for the interview is: "The model is stateless and the product is not. The design is conversation state, streaming, admission control and cost, with the model as one expensive dependency behind them."
2. Make experience and safety testable
A requirement that cannot fail a test is a preference. "Fast" is a preference. "Time to first token under one second at p95" is a constraint, and only constraints shape the architecture. Functional requirements say what the system does; non-functional requirements say how well and under what limits.
There are six must-haves. Send a message and receive a streamed answer. Keep and list conversation history per user, with rename and delete. Carry context across turns within a conversation. Enforce per-user and per-tier usage limits. Moderate input and output. Stop generation when the user presses Stop or the client disconnects.
The should-haves make the product competitive: file uploads, web search, a code sandbox, cross-conversation memory the user can inspect and erase, regenerate and edit-and-resend, and sharing a conversation by link. Voice and image generation come later. Each of these is a follow-on feature, not part of the first answer.
The next table restates the non-functional side as testable constraints. The latency and availability numbers are constructed interview targets, not any product's service level agreement.
Source service constraints for latency, availability, isolation, durability, fairness and privacy.
| Constraint | Stated so it can be tested |
|---|---|
| Latency | Time to first token under 1 s p95 for the default model; steady streaming after that; no UI freeze before the first token |
| Availability | 99.9% for send-and-stream; a regional outage degrades to another region, not to an error page |
| Durability | An acknowledged message and a completed answer are never lost in the home region; a partial answer survives a disconnect |
| Isolation | Zero cross-user reads of conversations, files or memory; user_id comes from auth, never from the model |
| Safety | Input and output moderation on every turn; measured false-positive and false-negative rates |
| Fairness | A burst from one user or tier cannot starve another tier's queue |
| Cost | Cost per daily active user tracked by tier; cache-read share of input tokens tracked as a first-class metric |
| Privacy | Content excluded from logs by default; deletion propagates to history, memory, files and caches |
A p95 first-token target of one second means 95% of measured turns begin streaming within a second. It does not mean the whole answer finishes in a second. The durability row is a promise about acknowledged writes: the conversation service acknowledges a message only after it is durably stored in the user's home region. History is copied to a second region asynchronously (step 7), so losing a whole region can drop only the most recent writes not yet copied, within a stated recovery-point objective.
Every must-have then needs an owner in the architecture, so nothing is left to "the model will handle it".
Components accountable for the core user actions.
| Requirement | Primary component(s) |
|---|---|
| Streamed answers | Streaming gateway, inference pool |
| History and context across turns | Conversation service, conversation store, context builder |
| Usage limits | Rate limiter and quota service at the gateway |
| Moderation both ways | Input moderation before admission, output moderation on the stream |
| Stop on request or abandon | Streaming gateway cancellation, propagated to inference and tools |
| Isolation | Auth service, namespaced stores, retrieval filter on uploads |
If the interviewer asks "What are the requirements?", the source's short answer is: "Functionally, stream a turn, store the thread, moderate both ways, cancel cleanly. Non-functionally, first token fast, no cross-user leak, fair queues, and the model stays stateless; the product holds state."
3. Turn daily users into streams and tokens
Say the arithmetic aloud. It shows why multi-region serving and caching are required rather than optional, and the interviewer is scoring the method, not the numbers. Every value below is an assumption for the whiteboard.
At ten messages per user per day, 100 million daily active users (DAU) send one billion messages. Divide by 86,400 seconds for about 11,600 messages per second on average, and assume a threefold peak of about 35,000 per second. At 400 output tokens per answer that is about 14 million output tokens per second at peak. At 2,000 input tokens per turn (system prompt, summary and recent turns) it is about 70 million input tokens per second, most of it a prefix the model has already processed.
At a decode speed of 50 tokens per second, a 400-token answer takes eight seconds to stream. Little's Law says that in a stable system, concurrency equals throughput times the time each item spends in the system. So 35,000 turns per second × 8 seconds ≈ 280,000 open streams. If one batched model replica holds 100 concurrent streams, the first pass is about 2,800 replicas at peak. Real prefill and decode throughput, key-value (KV) cache memory, queueing and failure headroom can push that higher. Two quick checks show how. Prefill time also holds a slot: about one second to first token adds roughly 35,000 × 1 ≈ 35,000 in-flight turns, about 350 more replicas. And slots are not compute: 70 million input tokens a second over 2,800 replicas is 25,000 input tokens a second per replica if nothing is cached, on top of 100 × 50 = 5,000 output tokens a second of decode. Only a high prefix-cache hit rate keeps that prefill load affordable, which is why caching belongs in the sizing rather than in a later optimisation pass.
Complete source sizing assumptions and their calculated consequences.
| Step | Assumption | Result |
|---|---|---|
| Daily active users | 100M | Starting assumption |
| Messages per user per day | 10 | 1B messages a day |
| Average rate | 1B ÷ 86,400 s | ≈ 11,600 messages/s |
| Peak | 3× average | ≈ 35,000 messages/s |
| Output per answer | 400 tokens | ≈ 14M output tokens/s at peak |
| Input per turn | 2,000 tokens (system prompt, summary, recent turns) | ≈ 70M input tokens/s at peak, most of it a repeated prefix |
| Decode speed per stream | 50 tokens/s | 8 s to stream one answer |
| Concurrent streams | Little's Law: 35,000/s × 8 s | ≈ 280,000 open streams |
| Streams per model replica | 100 concurrent, batched | ≈ 2,800 replicas at peak |
| Storage | ~2 KB text per message | ≈ 2 TB of conversation text a day |
Two consequences come straight out of the table. Little's Law turns latency work into capacity work: halving the answer length halves the concurrent streams you must provision. And the input line is why prefix caching matters more in chat than almost anywhere else, because 70 million input tokens a second are mostly history the model processed on the previous turn. Storage, at about 2 KB of text per message, grows by roughly 2 TB a day before indexes, replication and retention.
Before going further, split latency into its two phases. Prefill processes the whole prompt in parallel and sets the time to first token, so it scales with input tokens. Decode generates one token at a time and sets the total time, so it scales with output tokens. A bloated history is a first-token problem; a verbose answer is a completion-time and concurrency problem. Report both numbers, not one request latency. The prefix deep dive follows what this means for caching.
4. Trace admission, assembly, streaming and persistence
Draw a clear division of labour first. The LLM generates text. Ordinary code owns identity, quotas, context assembly, routing, moderation, tool scope, persistence and cancellation. The model is stateless between turns; the product stores full history but sends only selected context.
The organising rule is admit, assemble, stream, persist, and each verb decides one thing. Admission decides whether a request may use a GPU at all. The context builder decides what the turn costs. The stream decides what the user feels. Persistence decides what survives.
The figure below shows the main path with its decision edges. Input moderation can block a turn before it reaches the model, output moderation can halt a stream, and a disconnect or Stop cancels model and tool work and frees KV cache.
Follow one turn through it. The client is routed to a healthy region. The regional streaming gateway authenticates the user, applies per-user and per-tier token budgets and runs input moderation before GPU admission. The conversation service reads the user's durable history, persists the new message and later saves partial output as tokens arrive, so a reconnect has something to resume. The context builder sends a versioned stable prompt prefix, a rolling summary, recent turns, relevant inspectable memory and the user's own file chunks; full history stays in storage. A router picks a model the user's tier allows and the task needs. A bounded fair queue protects each tier and prefers a warm replica only while that replica has capacity. The pool generates with continuous batching and prefix/KV reuse. Optional search, file or code tools run under step limits, and untrusted file content never gains the authority of an instruction. Output moderation checks streamed chunks before delivery, and the gateway sends server-sent events (SSE) to the client. Regional failover is possible but may be cold and slower.
The source draws the same flow a second way, adding the edge layer and showing the inference pools as small, default and premium model sizes behind the router.
The third view groups the same components into planes. The control plane versions the model catalogue, tier routing and quotas, prefix-stable system prompts, moderation thresholds, the region map, flags, evaluation gates, budgets and alerts. The conversation-state plane stores history, titles and partial answers sharded by user_id, and a memory store namespaced by user_id. Conversation state replicates according to each user's home region, control-plane configuration replicates everywhere, and inference pools are independent per region. Observability records stage timings, tokens, cache reads, abandonment and moderation events without conversation text.
The table reads the components in request order. The third column matters as much as the second: each component has a defined way to fail.
Original component responsibilities and failure responses.
| # | Component | Responsibility | Fails how |
|---|---|---|---|
| 01 | Client | Renders the stream, resumes on reconnect | Degrades: shows the persisted partial answer |
| 02 | Edge + GeoDNS | Sends the user to the nearest healthy region | Fails over to the next region |
| 03 | Streaming gateway | Holds the SSE connection, auth, rate limit, quota, cancellation | Closed on auth; sheds free-tier traffic first under load |
| 04 | Input moderation | Blocks severe harm and abuse before a GPU is used | Closed for severe categories; logs and allows on a timeout for low-risk tiers |
| 05 | Conversation service | Owns messages, titles and partial answers | Closed for writes; history reads degrade to a cache |
| 06 | Conversation store | Durable history, sharded by user_id |
Replicated; home-region failover |
| 07 | Memory store | Cross-conversation facts, inspectable and erasable | Degrades: answer without memory, say nothing false |
| 08 | Context builder | Assembles the prompt in prefix-stable order | Degrades: fewer turns, same order |
| 09 | Model router | Chooses the model by tier and task | Degrades to the default model |
| 10 | Scheduler + fair queue | Admits work per tier, keeps a conversation on a warm replica | Sheds lowest tier first; never drops an admitted stream silently |
| 11 | Inference pools | Continuous batching, prefix/KV cache | Fails over region or model; circuit breaker on a sick pool |
| 12 | Output moderation | Checks the stream in chunks, can halt it | Closed: halts the stream and says why |
| 13 | Tools | Search, sandbox, file retrieval under step caps | Degrades: answer without the tool, say so |
| 14 | File pipeline | Scan, parse, embed per user | Degrades: file unavailable, never cross-user |
| 15 | Observability | Stage timings, tokens, cache reads, abandonment | Degrades: request still served, gap logged |
While the diagram is up, point at three boundaries. The admission boundary sits at the gateway: nothing reaches a GPU without passing auth, quota and input moderation. The isolation boundary sits at every store, because each one is namespaced by a user_id that comes from authentication. The cost boundary sits at the context builder, because it decides how many tokens each turn re-sends.
5. Persist the conversation and bound each prompt
Store everything and send little. Trimming bounds what reaches the model, not what is stored, and the model cannot be billed for history the context builder never sent.
The conversation service writes every message durably, keyed by (user_id, conversation_id). It also persists the partial answer as tokens stream, so a user who disconnects reconnects to the text generated so far rather than to nothing. Each stream carries a message ID: a reconnect resumes that message rather than silently paying for a second answer. The store is sharded by user_id, so one user's history lives on one shard and a list-conversations call touches one partition.
The context builder assembles each turn in a fixed order: system prompt, rolling summary, recent turns, memory facts, retrieved file chunks, then the new message. Take turn 40 of a long conversation. Sending all 40 turns would make prefill slower and more expensive every turn. The growth is quadratic over the conversation. If each turn adds about 500 tokens of question and answer, re-sending the full history means turn k carries about 500 × k tokens, so 40 turns send 500 × (1 + 2 + … + 40) = 500 × 820 = 410,000 input tokens to deliver about 20,000 tokens of new text. A bounded prompt of about 2,000 tokens caps the same conversation at about 80,000. A sliding window of the last few turns keeps the prompt small but loses anything that scrolls out. Summarisation keeps a condensed record once the buffer crosses a threshold, at the cost of one extra model call per compression. The memory guide's worked answer folds the buffer at about 15 turns. That is an illustrative threshold to tune, not a rule, and it keeps cost flat on long chats. Volunteer the failure mode: the summariser can drop a detail it judged unimportant. Recent turns and user-visible memory are the recovery path.
Cross-conversation memory is a different store with a different key. A checkpoint key answers "which conversation"; a user namespace answers "which person". Semantic memory holds stable facts, such as a preferred language, under a stable key that overwrites in place. Episodic memory appends one record per completed task and is pruned. The two have different update rules, so do not share one write path.
The memory guide's isolation rule has no exceptions: read user_id from the server-side session on every request, never from a tool argument the model could set. Make memory visible and erasable in the product, because a user who cannot see a remembered fact cannot correct it. A deletion request propagates to the conversation store, memory, uploaded files and caches.
6. Stream useful work and cancel abandoned work
Stream every answer, and treat a closed connection as a cost signal. Streaming buys perceived latency, not real latency. Total generation time is unchanged, but the first token can arrive within the one-second target instead of after the whole answer.
Use SSE for the chat stream. After the request, traffic flows one way, from server to client. SSE runs over plain HTTP, so it passes most proxies that do not buffer responses, and the browser's EventSource client reconnects on its own. Keep WebSockets for paths that need both directions at once, such as voice. One implementation note the source does not cover: EventSource issues only GET requests, so a chat API that sends the message as a POST usually reads the SSE stream with a fetch reader and handles reconnect and resume itself, using the message ID.
A user who leaves mid-answer is still costing GPU time. The source's cost notes name the scenario directly: "cancel the stream + any in-flight tool calls on abandon — otherwise you pay for tokens nobody read." The gateway detects the closed connection and sends a cancel to the inference request. That frees the batch slot and its KV cache (the attention state the model keeps for the sequence so far) and stops any tool call in flight. The Stop button uses the same path. Middleware can swallow a disconnect, so test that the cancel actually reaches the inference worker; the source's reference list cites a vLLM issue where abort-on-disconnect broke behind middleware.
Measure abandonment against first-token time and answer length. A rising abandon rate is often a first-token problem in disguise: users leave because nothing appeared, not because the answer was bad. The Observability and Production Diagnosis case makes the same point. Track tokens generated after abandon as a cost line.
7. Admit fairly, moderate both ways and recover regionally
Three controls sit around the serving path, and each has a deep dive.
Admission and fairness. A token bucket per user, sized by tier, decides whether a request may proceed. A weighted fair queue per tier decides in what order admitted requests run. Count tokens, not only messages. Under saturation, bound the queue and reject early with a retry signal instead of letting it grow, and keep your own quota 429 separate from a provider or pool capacity event.
Moderation and untrusted content. Input moderation blocks severe requests before they spend GPU time. Output moderation checks the stream and can halt it, because the model can repeat something sensitive from an earlier turn. Files and fetched pages are data and never gain instruction authority; retrieval over uploads is filtered by user_id, tools are step-capped and the code sandbox has no network or credentials.
Regional recovery. Each region has independent gateway and inference capacity, and each user has a home region for history. Failover may lose warm KV state and some asynchronously replicated history, so the first recovered turn can be slower. Residency rules may restrict which regions are eligible. Use circuit breakers and reserved capacity instead of assuming new GPUs start instantly.
8. Prove the product before expanding a release
Measure time to first token, not only total latency, because first-token time is what a chat user feels. When latency moves, the first tool is a per-stage trace: the Observability and Production Diagnosis case's triage section decomposes a slow request into queue wait, prefill, decode, moderation and tools. Record stage timings, token counts, cache reads, abandonment and moderation outcomes, and keep message text out of ordinary telemetry by default, as section 2 of that case recommends.
The question bank's second failure mode is hand-waving evaluation. Tie every design choice to a number. The table pairs each worry with the metric that answers it.
User-facing questions and the metric that answers each one.
| Worry | Metric that answers it |
|---|---|
| Does it feel fast? | Time to first token p50/p95 by tier and region |
| Is it answering well? | Thumbs-down rate, regenerate rate, edit-and-resend rate |
| Is caching working? | Cache-read share of input tokens; hit rate by prompt version |
| Is moderation calibrated? | False-positive rate on a labelled sample; false negatives from red-team runs |
| Are users leaving mid-answer? | Abandonment against first-token time and answer length |
| Is it affordable? | Cost per daily active user by tier; tokens generated after abandon |
| Is it isolated? | Cross-user read tests at zero, run before every release |
Read these metrics with care. A falling regenerate or thumbs-down rate supports a quality improvement, but compare it by user segment and alongside completion; neither is a perfect label. Queue wait and service time should be reported separately, so a scheduling problem is not mistaken for a model problem.
Ship model, routing and prompt changes through a release gate with a canary slice, as the Evaluation and Release Gating case designs it. Gate on quality, safety, latency and cost together, so a cheap route whose users keep regenerating does not pass. Keep a fast rollback to the previous version. A system-prompt change is a release, because it also changes the cache prefix and therefore the cost line; watch the cache hit rate during the canary.
Technical deep dives
Examine mechanisms, alternatives, and operational consequences.
Prefill, decode and byte-stable prefix reuse
Chat is the best case for prefix caching, because each turn is the previous turn plus a little. Prefill processes the input and builds attention state before the first output token; decode extends the answer one token at a time. If the provider or the serving engine can reuse the prefill of a prefix it has already seen, turn 41 pays prefill only for what is new.
The matching rule is strict. The cost notes describe it for Claude's API: cache matching is byte-exact on the prefix, which is rendered in the order tools, then system prompt, then messages. One changed byte invalidates everything after it. OpenAI's prompt cache also matches exact prefixes, and both vendors scope caches to a model. Provider caches also expire. Claude's default cache entry lives five minutes and is refreshed each time it is read, with a one-hour option whose cache write costs more; OpenAI's automatic cache typically keeps a prefix for 5 to 10 minutes of inactivity, with longer retention on some models. A chat user who pauses longer than the lifetime pays full prefill on the next turn, so the gap between turns matters as much as byte stability.
So build the prompt with the stable parts first and never move them. Freeze the system prompt per version. Order the tool list deterministically and serialise JSON keys in a fixed order. Put timestamps, request IDs and the user's new message after the last cache breakpoint. The source lists the silent invalidators behind a sudden drop in cache hits:
- a
datetime.now()value in the system prompt; - unsorted JSON keys;
- a tool list whose order varies between requests;
- a prompt-version bump;
- a model swap.
Prove the cause with the cache-read token counter rather than by guessing.
A cache is only warm on the machine that holds it. Route every turn of a conversation to the replica that served the previous one, so its KV cache may still hold the history. A self-hosted prefix cache keeps a finished sequence's blocks only until memory pressure evicts them, least recently used first, so a user who replies ten minutes later on a busy replica will often find them gone. Measure the hit rate against the gap between turns rather than assuming affinity guarantees a hit. This soft session affinity trades some load-balancing freedom for a large cut in prefill work, and it yields to capacity and health. When that replica is gone, the turn still succeeds, only slower, because a new replica must prefill the whole history from the durable store. On self-hosted serving, KV reuse saves compute; it is not a per-token price discount the way a provider's cache-read rate is.
Summarisation interacts with caching too. Rewriting the summary changes the prefix after it, so folding history every turn would defeat the cache. Fold in large steps, where quality allows.
Model routing can sacrifice cache savings
Route on two axes: the user's tier and the turn's difficulty. The tier sets which models a user may reach and at what quota. The task sets which of those models a turn needs. A greeting does not need the premium model; a long proof might.
The source's cost notes put a number on this lever. On Claude's list prices as of September 2026, output costs five times input on every tier; other vendors' ratios differ. Opus 5.5 is listed at $4 input and $20 output per million tokens, and Haiku 4.5 at $1 and $5. A router that moves 80% of traffic from Opus 5.5 to Haiku 4.5 cuts unit cost on that slice by about four times. The source advises saying that sentence in the answer, because it turns "model routing" into a number. With the same token mix, the saving across all traffic is smaller than the slice figure: 0.2 + 0.8 × 0.25 = 0.4 of the original unit cost, about 2.5 times cheaper, before cache effects. Treat the prices as the case's dated inputs, not current offers. Haiku 4.5 is now a previous-generation model: Claude's pricing lists Haiku 5.5 at $0.10 input and $0.50 output per million tokens for prompts up to 100K tokens, which keeps the five-to-one output ratio but changes the routing arithmetic, so recompute with the prices on the day.
Then name the trade-off. Prompt caches are scoped to a model, so a cheap-to-medium-to-premium cascade keeps a separate cold prefix on each model. On a chat product whose input is mostly repeated history, a cascade can forfeit more in cache reads than it saves in price, and every escalation adds an attempt. The source's rule: measure one strong model at lower effort before building the cascade. Route at the start of a conversation where possible, and keep a conversation on one model unless the user changes it. Compare options on cost per successful conversation and regenerate rate, not on list price per token.
Admission, fair queues and two kinds of 429
A rate limit and a fair queue answer different questions, and a consumer service needs both. Section 7 of the Secure Multi-Tenant AI Platform case draws the line. A rate limit decides whether this request may proceed at all. A fair queue decides in what order admitted requests are served under load.
Put a token bucket per user at the gateway, sized by tier: messages per window and tokens per day. A token bucket refills at a fixed rate and lets a request through only while tokens remain, which allows short bursts but caps the average. Count tokens, not only requests, because one long request can cost as much as, say, fifty short ones.
Behind admission, feed a weighted fair queue per tier into the shared inference pools. Each tier gets a share of service in proportion to its weight, so a free-tier surge waits longer while paid users keep their latency, and no tier is starved outright. Keep the queues bounded: reject or defer before the wait would break the latency objective, and never drop an admitted stream silently.
When load spikes, separate the two kinds of HTTP 429 (too many requests). As the cost notes put it: "Separate provider 429s from your own gateway limits." A 429 your gateway issued is a policy decision. A 429 from a model provider or a full pool is a capacity event. In the short term, retry with jitter onto a fallback model or region and shed non-interactive traffic. In the long term, buy capacity and queue non-urgent work rather than retrying into the same wall.
Abuse is a rate-limit problem too. Apply per-account and per-IP limits, detect anomalous bursts, and give new or unverified accounts stricter quotas.
Moderation, files and tools as untrusted input
Moderate input before it reaches a GPU and output before it reaches a screen. The production guide explains why both: the model can repeat something sensitive the user said two turns ago, and an input-only check never sees that response. Input-only moderation is cheaper, because it classifies only the user's message, but only input plus output catches the multi-turn case, and a consumer chat product is multi-turn by definition.
Input moderation runs as a fast classifier at the gateway, before admission, so a blocked message never spends GPU time. It fails closed for severe categories; for low-risk tiers the source allows logging and passing the message if the classifier times out. Output moderation runs on the stream in chunks and can halt it mid-answer with an explanation. Text already shown cannot be withdrawn, so choose the chunk size by how much exposure the policy tolerates.
Moderation APIs score a fixed set of categories, and at default thresholds milder or app-specific abuse can still pass; the thresholds and the policy are the application's job. The guide names two independent layers, the model's trained refusals and the moderation classifier, and neither substitutes for an app-specific policy. Measure false positives as closely as false negatives on a labelled sample, because over-blocking is the failure users notice first.
Files and tools carry indirect prompt injection: instructions hidden in a document or web page that try to steer the model. The question bank lists it as a Tier 2 probe. An uploaded PDF or a fetched page is data, and data must not gain the authority of instructions. The figure shows the upload pipeline and the bounded tools.
Store uploads in object storage, scan them, parse asynchronously, then chunk and embed them per user. Retrieval over them is filtered by user_id at query time, the same two-layer idea as section 6 of the Enterprise Knowledge Assistant case. Tool steps are capped per turn and each tool call has a timeout. The code sandbox runs with no network and no credentials, and is destroyed after the session.
Regional recovery has data and capacity limits
Serve each user from the nearest healthy region, and let a regional failure cost latency, not availability. GeoDNS or anycast sends the client to a regional edge. Each region runs its own gateway, services and inference pools, so one region's failure does not queue behind another's.
Give each user a home region for the conversation store and replicate it asynchronously to a second region. A failover then reads slightly stale history rather than none. Inside the home region the acknowledged-write rule still holds; the recovery-point objective states how much recent history a whole-region loss can drop. Keep the control plane central for policy and regional for enforcement, the balance section 8 of the Secure Multi-Tenant AI Platform case argues for. Residency rules can pin some users' data to a region; the region map in the control plane records them, and failover must not bypass them.
Failover is cold by nature. The new region has no KV cache for the conversation and may have less spare capacity. Accept the slower first turn, shed the free tier before the paid tier, and hold reserved capacity while new GPUs warm. Put a circuit breaker on a sick pool so requests stop paying to rediscover a failure. The production guide gives its three states: closed during normal operation, open after repeated failures, and half-open to let one probe through after a cooldown.
A model outage degrades to another model in the same tier. It never degrades to an error page while any healthy model the user may reach remains. If no permitted path is left, show an explicit unavailable-and-retry state with the saved conversation still readable.
Answer the Claude-service wording
"Design the Claude chat service" is the same prompt as "Design ChatGPT", and the design above answers it unchanged; the source records no content difference. The emphasis differs, and saying so shows you read the room. The question bank frames the Anthropic questions directly: "AI/ML framing, but they fundamentally test distributed-systems fundamentals: batching, queuing, load balancing." Neighbouring Anthropic prompts include inference batching, GPU routing and a 100,000-requests-per-second token service, which the source groups with the LLM Inference Serving case.
For this wording, spend more of the hour on four parts: the Little's Law sizing, the fair queue, continuous batching with session affinity, and failover. Expect two follow-ups from the batching prompt in the same bank: "how do you determine which GPU has capacity?" and "how do you handle failover?" For the first, the scheduler tracks per-replica queue depth and free KV memory and prefers the replica already holding the conversation.
The Tier 2 safety probe carries extra weight here: circuit breakers, rate limiting and graceful degradation when the model is unavailable. Have the degradation ladder ready to say as a list:
- Shed free-tier and non-interactive traffic before paid traffic.
- Open the circuit breaker on the sick pool and stop sending it work.
- Fall back to another healthy model in the same tier.
- Fail over to another eligible region, accepting a cold first turn.
- Only when no permitted model remains, show an explicit unavailable state with the saved conversation.
Source references and limits
The source fact-checked its serving, cancellation, pricing, cache and moderation claims on 27 September 2026. Each reference below supports a specific claim in this case. Treat the prices as dated arithmetic, and verify cancellation, transport and cache behaviour for your actual runtime and middleware before launch.
- Artificial Analysis LLM leaderboard (TTFT column): real first-token times range from hundreds of milliseconds to over a second, not a few milliseconds.
- WHATWG HTML Standard: Server-sent events: SSE over plain HTTP, EventSource auto-reconnect, and proxies that drop idle connections.
- vLLM docs: OpenAI-compatible server: a disconnect aborts the request and frees its slot; when self-hosted, KV reuse saves compute rather than earning a per-token price.
- vLLM issue #10087: abort on disconnect can break behind middleware, so cancellation must be propagated and tested.
- Claude docs: Models overview: Opus 5.5 is the current Opus model; Opus 5 is legacy.
- Claude docs: Pricing: Opus 5.5 at $4/$20 and Haiku 4.5 at $1/$5 per million tokens, a 4× gap; output is 5× input on every Claude tier.
- Claude docs: Prompt caching: caches are per model, matched on an exact prefix in tools, system, messages order, and broken by volatile content.
- OpenAI API docs: Prompt caching: exact-prefix matching and per-model caches at a second vendor.
- OpenAI API docs: Moderation: moderation returns category scores; thresholds and policy remain the application's job.
Supporting references: Claude prompt caching for the five-minute and one-hour lifetimes, Claude pricing for current model prices, OpenAI prompt caching for cache retention, and vLLM automatic prefix caching for least-recently-used eviction of cached blocks.
Practice
Attempt the case before revealing the worked reasoning.
Attempt one complete turn and one failure
On a blank page, derive the token load and open streams from the sizing assumptions, then trace one message through admission, context assembly, routing, the fair queue, moderation and persistence. Then close the tab halfway through the answer and describe which state survives and which compute stops. This exercise is authored for the casebook. The twelve questions below are the source's self-checks; answer each before opening it.
Work through your answer
This local worksheet is a prototype addition. Notes save in this browser. Nothing is submitted or scored.
Check your reasoning
Reveal the self-assessment rubric
This checklist is an authored addition. Assess what you can explain without reopening the walkthrough.
0 of 8 reasoning checks covered.
Why is "the model is stateless and the product is not" the opening line?
It names where the design effort goes: conversation state, streaming and admission, with the model as one expensive dependency. Durable history, bounded context and cancellation all live in the service around the model, so a load balancer in front of a model pool does not make a chat product.
Walk the sizing from 100M daily users to open streams.
Ten messages each gives 1B messages a day, about 11,600 per second on average and about 35,000 per second at a 3× peak. A 400-token answer at 50 tokens per second takes 8 s, so Little's Law gives 35,000 × 8 ≈ 280,000 open streams. At 100 streams per replica that is about 2,800 replicas before measured throughput and KV checks.
Why does time to first token depend on history length?
Prefill processes the whole prompt before the first token, and history is most of the prompt. The context builder bounds that work by sending a summary and recent turns instead of every stored message, and a stable prefix lets cached prefill be reused.
What does the context builder send on turn 40 of a conversation?
The frozen system prompt, a rolling summary, the recent turns, relevant user memory and file chunks, then the new message, in that order. The fixed order keeps the stable parts first so prefix caching keeps working.
Why SSE rather than WebSockets for chat?
The stream is one-way after the request. SSE runs over plain HTTP, so it passes most proxies that do not buffer, and the browser's EventSource reconnects on its own. WebSockets fit paths that need both directions at once, such as voice.
What happens when a user closes the tab mid-answer?
The gateway detects the closed connection and cancels the inference request and any tool call, freeing the batch slot and KV cache. The partial answer is already persisted, so a later reconnect shows it. Test that the cancel survives middleware, and count tokens generated after abandon.
Why can a model cascade raise cost on a chat product?
Prompt caches are scoped to a model, so each model in the cascade starts cold on a prompt that is mostly repeated history. The lost cache reads and the extra attempts can outweigh the cheaper unit price. Compare cost per successful conversation.
How do a rate limit and a fair queue differ?
The limit decides whether a request may proceed at all; the queue decides the order in which admitted requests are served under load. A per-user token bucket does the first, a weighted fair queue per tier the second.
Why moderate output as well as input?
The model can repeat something sensitive from an earlier turn, which an input-only check never sees. Output moderation runs on the stream and can halt it with an explanation.
Name three silent prefix-cache invalidators.
A timestamp in the system prompt, unsorted JSON keys and a tool list whose order varies. A prompt-version bump or a model swap also invalidates the prefix. Confirm with the cache-read token counter.
What changes when the prompt is "Design the Claude chat service"?
Nothing in the design. More of the hour goes to batching, queuing, GPU capacity and failover, with the degradation ladder ready as a spoken list.
What is the sixty-second cost answer?
Chat cost is history times turns plus answers nobody finished. Keep a stable prefix so history is a cache read, summarise in steps, keep answers short by default, route easy turns down and cancel on abandon. Prove it with cost per daily active user and cost per successful conversation.
Rehearse the hour and the follow-ups
Spend the hour on state, streaming, admission and cost, because those are the parts a generic answer skips. The model choice is a sentence. The source's timing plan:
Source plan for a sixty-minute round.
| Minutes | Phase |
|---|---|
| 0–7 | Clarify: the six questions and the stated assumptions (step 1) |
| 7–12 | Requirements and the sizing arithmetic aloud (steps 2 and 3) |
| 12–20 | The diagram and one message walked end to end (step 4) |
| 20–40 | Deep dive: conversation state, streaming and cancel, routing, limits (steps 5, 6, routing, admission) |
| 40–50 | Safety, caching, regions (moderation, prefix, regions) |
| 50–60 | Metrics, the release gate, the cost pivot (step 8, cost pivot) |
The source's two-minute spoken answer, which you can adapt into your own words:
I would start by saying the model is stateless and the product is not. At 100 million daily users and ten messages each, peak is around 35,000 messages a second, and with eight-second answers that is about 280,000 open streams, so admission, streaming and cost dominate. A streaming gateway holds each SSE connection and does auth, per-user token-bucket limits, tier quotas and input moderation before anything reaches a GPU. The conversation service stores every message durably, sharded by user, and persists partial answers so a reconnect resumes. A context builder sends only what the turn needs: a frozen system prompt, a rolling summary, recent turns and user memory, in a prefix-stable order so prompt caching works. A router picks the model by tier and task, and a fair queue per tier feeds inference pools that batch continuously and keep each conversation on a warm replica. Output moderation runs on the stream and can halt it. When the client leaves, the gateway cancels generation and tool calls, because tokens nobody reads still cost money. Each region is independent, with a home region for history and cold failover. I would prove it with time to first token, regenerate and abandon rates, moderation error rates and cost per daily active user.
The lines that carry the round:
- "The model is stateless and the product is not."
- "Store everything, send little."
- "Streaming buys perceived latency, not real latency."
- "Cancel on abandon. Tokens nobody reads still cost money."
- "A rate limit decides whether; a fair queue decides in what order."
- "Prefix caching is a byte-exact prefix match. Stable first, volatile last."
- "A cascade forfeits the cache. Measure one model at lower effort first."
- "Failover is cold, not closed."
The follow-ups below come from the question bank's Tier 2 probes and the neighbouring prompts. Answer each aloud before opening it.
Stateless or stateful servers?
Stateless services, with state in the conversation store. The only affinity is soft, to keep the KV cache warm, and it yields to capacity and health.
How do you handle a model outage?
Circuit breaker on the pool, a fallback model in the same tier, shed the free tier first, and never an error page while a healthy model remains.
How do you stop a runaway tool loop?
A step cap per turn, per-tool timeouts, and cancel on abandon.
How do you keep long-term memory from getting polluted?
Stable keys that overwrite, pruned episodic records, memory the user can see and erase, and user_id taken from auth only.
Prompt injection through a file or web page?
Treat the content as data, not instructions; scope retrieval to the user; run the sandbox with no credentials; and keep output moderation on the stream.
How do you version and roll back prompts?
Versioned system prompts behind the release gate with a canary slice. A prompt bump is also a cache and cost event, so watch cache-read share during the canary.
Which GPU has capacity?
The scheduler tracks per-replica queue depth and free KV memory, and prefers the replica already holding the conversation.
How would you know it works?
Use the worry-to-metric table in step 8: time to first token by tier and region, regenerate and edit-and-resend rates, cache-read share, moderation false positives and negatives, abandonment, cost per daily active user and zero cross-user reads, each tied to the design choice it tests.
The level calibration below shows how the same answer sounds at senior, staff and principal level, and what each level still tends to miss.
Source calibration for senior, staff and principal answers.
| Level | Sounds like | Missing |
|---|---|---|
| Senior | Says the model is stateless and the product is not, sizes 100M daily users down to about 280,000 open streams, and walks admit, assemble, stream, persist: gateway quotas and input moderation, a durable conversation store, a bounded context builder, and SSE that cancels on abandon. | Fairness between tiers under overload, cache-aware routing, and what a regional failover costs. |
| Staff | Adds the operational judgement: a rate limit decides whether and a fair queue decides when, a byte-exact stable prefix with soft session affinity, a cascade weighed against the cache it forfeits, and cold failover that sheds the free tier first. Treats a system-prompt change as a release that also moves cache and cost. | Who owns quotas, prompts and moderation thresholds as policy, and how deletion and residency hold across every store. |
| Principal | Keeps policy central and enforcement regional, steers by cost per daily active user and cost per successful conversation, and makes memory the user can inspect and erase a product commitment. Plans how files, search, a code sandbox and later voice join without widening the trust boundary. | Real per-replica throughput, KV memory and traffic shape; every sizing figure here is a placeholder until measured. |
Explain a bill rising faster than users
The interviewer's pivot: "the bill is growing faster than users." No ready-made drill covers this group, so the source supplies a self-drill grounded in the main cost drivers. Before opening the card, name the dominant driver, the cheapest lever, the metric that proves it and the move to avoid.
Open the source cost-pivot card.
Source cost-pivot self-drill card.
| Card field | Source answer |
|---|---|
| Dominant driver | Input tokens re-sent every turn as history grows, and output tokens at consumer volume, including tokens generated after the user has left |
| Cheapest lever first | Prefix-stable prompt with session affinity so history is a cache read; summarise history in large steps; short default answers with expansion on demand; route easy turns and the free tier to a small model; cancel on abandon |
| Metric that proves it | Cost per daily active user by tier; cache-read share of input tokens; output tokens per answer; tokens generated after abandon; time to first token p95 |
| Do not | Re-send the full history every turn, or build a three-model cascade that forfeits the prompt cache |
| 60-second line | Chat cost is history times turns plus answers nobody finished. Keep the prefix stable so history is a cache read, summarise in steps, keep answers short by default, route easy turns down, and cancel the moment the user leaves. |
Two drivers explain almost every surprise here. Input tokens grow with the conversation: teams count the user's question and ignore the system prompt and hidden history, so the bill rises while traffic stays flat. Output tokens grow with verbosity: teams measure requests, not generated tokens. Streaming improves perceived latency but does not reduce total compute cost.
Quote cost per successful conversation rather than per request, as the cost notes insist: a cheaper model that needs a regenerate is not cheaper. A strong cost answer follows four verbs in order. Measure tokens and stage timings first. Route each turn to the model its tier and task need. Bound history, answer length and tool steps. Cache safely, with a stable prefix and the user's scope in every cache key.
Return to the decisions you could not explain.
Review the essentialsQuick review
Recall the decisions, failure responses, and closing answer.
Recall the turn and its limits
Ask first: consumer or API? Daily active users and turns? Tiers? History and memory? Files and tools? Serve or train models?
Whiteboard path: client → regional gateway with auth, quota and input moderation → conversation store → bounded context → tier and task router → fair queue → LLM pool → output moderation → SSE stream with partial persistence. Disconnect cancels model and tools. User scope comes from authentication at every store and retrieval boundary.
Assumed sizing, not production data: 100M DAU × ten turns = 1B a day ≈ 11.6K/s average and 35K/s at a 3× peak, with 70M input and 14M output tokens per second. Eight-second answers imply about 280K open streams, and 100 streams per replica implies about 2,800 replicas before token-throughput and KV checks.
Five lines to remember:
- The model is stateless; the product is not. Store every turn, send only the summary, recent turns and relevant memory.
- A rate limit decides whether a request runs; a fair queue decides when.
- A stable byte-exact prefix and a warm replica save input prefill; a model cascade may lose that cache.
- Streaming improves perceived latency; cancellation saves actual GPU cost.
- Sixty-second close: "Admit safely, assemble bounded user-scoped context, stream from continuously batched pools, persist partial answers and cancel abandoned work. Measure first-token latency, fairness, isolation and cost per user."
Decisions and failure responses
- Clarify the product and state assumptions before drawing; the prompt gives nothing else.
- Requirements are testable: first token under a stated p95, zero cross-user reads, measured moderation error rates.
- The sizing walk from daily users to open streams to replicas shows why admission, streaming and caching are mandatory.
- One diagram shows admit, assemble, stream, persist, with boundaries at the gateway, the stores and the context builder.
- Store every message durably; send the model only a summary, recent turns and user-scoped memory. Summaries can drop a detail.
- Stream with SSE, persist partial answers, and cancel generation and tools when the client leaves.
- Route by tier and task, and count the prompt cache a cascade forfeits.
- A per-user token bucket decides admission; a weighted fair queue per tier decides order. Keep your 429s separate from provider 429s.
- Moderate input and output, and treat every file and fetched page as untrusted data.
- Keep the prefix byte-stable and each conversation on a warm replica, so history is a cache read.
- Serve per region with a home region for history. Failover is cold, not closed; residency still holds.
- Measure time to first token, regenerate and abandon rates and cost per daily active user, and gate every prompt change.
- The Claude wording is the same design, with more time on batching, queuing and failover.
- The cost pivot: stable prefix, stepped summaries, short answers, route down, cancel on abandon.
The short spoken answer to close on:
I would clarify the product and request shape first, then say the model is stateless but the product is not. A regional gateway authenticates, rate-limits and moderates before GPU admission. A conversation service stores every turn and partial answer, while a context builder sends only a stable prompt prefix, summary, recent turns and user-scoped memory. A tier/task router feeds a bounded fair queue and continuously batched LLM pools. Output is moderated as it streams; disconnect cancels generation and tools. I would size from messages per second to open streams and GPU capacity, but label those figures as assumptions. The hard trade-offs are history versus token cost, cache warmth versus model routing, and fairness versus latency under overload. I would prove the design with first-token latency, abandon rate, isolation tests and cost per daily active user.