Skip to content
Forward Deployed

Forward Deployed

Consumer-Scale Chat Service

Build durable conversations and responsive streams while controlling user isolation, admission and token cost.

Kind
Case study
Level
Advanced
View
Interview prep
Sections
4
By
Sourav Banerjee
Last updated
20 Nov 2026

Report an issue

Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.

Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.

Case brief

The case in one line: a consumer chat assistant where the model is stateless and the product is not, so state, streaming and GPU cost are the design.

30-Second Cheat Sheet

  • The product: a consumer chat assistant for web and mobile. Answers stream token by token, and a conversation reopens days later with its history intact.
  • The hard part: the model is stateless, the product is not.
  • State and cost are one problem: every token the service remembers and re-sends is paid for again on the next turn.
  • The core idea: store every turn, send the model only what this turn needs, and stream the answer back.
  • The whiteboard path: admit → load state → infer and stream → moderate → persist.
  • The prompt: "Design ChatGPT" (OpenAI) or "Design the Claude chat service" (Anthropic). One design answers both.
  • Scope: sessions, streaming, admission, moderation and cost. Training a model is out of scope.
  • Every scale figure is a whiteboard assumption, not a measurement of any real service.

1. A conversation product around a stateless model

The product

  • Design a consumer chat assistant for web and mobile.
  • Many people send many messages.
  • They watch answers arrive token by token.
  • They expect to reopen a conversation days later with its history intact.
  • The GPU bill has to stay under control while all of that happens.

Why it's hard

  • 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 each turn to the right user.
    • Rebuild a bounded prompt for the next turn.
    • 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 terms that carry the case

Term Meaning
Stateless model The LLM keeps nothing between calls; each call gets one prompt and returns one answer
Turn One user message and the answer to it
Bounded context The prompt the service rebuilds for this turn: only what this turn needs, never the raw full history
Admission The check that decides whether a request may proceed at all, or is rate limited
Fair queue The queue in front of the model pool that stops one group's burst from stalling everyone else
Streaming Sending the answer back token by token as it is generated
Persist Storing the turn (and any partial answer) durably so it survives

The core idea in one sentence

Store every turn, send the model only what this turn needs, and stream the answer back.

Admitted?

  • No → rate limited.
  • Yes → load conversation → bounded context → fair queue and model pool → stream and persist.

2. Follow Sam's message through one turn

The user: Sam, a free-tier user, presses send.

  1. Admission and quota checks run first.
    • When capacity is tight, paid users may be served ahead of Sam.
  2. Load state.
    • The service loads Sam's conversation, including any deletion rules that apply to it.
    • If the whole history won't fit in the prompt, it is not pasted in raw: the service sends a summary and the recent turns instead.
  3. Input moderation checks the message before any GPU time is spent.
  4. Infer and stream.
    • A GPU pool generates the answer and streams tokens back.
    • Batching and fair queues keep a burst from one group of users from stalling everyone else.
  5. Output moderation checks the stream on its way to Sam's screen.
  6. Tools, if used (files, search or code) run sandboxed and with a cap on steps.
  7. Persist. The finished turn is stored.
  8. If inference fails partway:
    • The service fails over to another pool or region.
    • It keeps the saved partial answer.
    • It never pretends the turn did not happen.
  • The path to draw on the whiteboard: admit → load state → infer and stream → moderate → persist.

3. What you need to design

The prompt

  • It arrives as one line: "Design ChatGPT."
    • Candidates report it from OpenAI interviews.
  • A variant: "Design the Claude chat service", reported 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.

Scope

  • In: one slice of the product: sessions, streaming, admission, moderation and cost.
  • Out: training a foundation model. The design serves models that already exist.
    • Leave "we'll train a new model" out unless the interviewer asks.

Caveat: every scale figure is a whiteboard assumption, not a measurement of any real service. Treat each number as a placeholder for measured throughput.

What it assumes you know

  • LLM serving basics: tokens, batching and streaming.
  • Caching.
  • Rate limiting.
  • Basic cloud architecture.
Design What it supplies
Enterprise Knowledge Assistant User-filtered retrieval
Secure Multi-Tenant AI Platform Quotas, fair queues and regional control
Observability and Production Diagnosis Stage timing and abandonment

By the end you should be able to

  • Explain the system end to end at interview depth.
  • Answer follow-ups on:
    • Sizing
    • Conversation state and context
    • Streaming and cancellation
    • Model routing
    • Quotas and fair queues
    • Moderation
    • Regions and release gates
  • Self-checks, the follow-up bank and the cost pivot are in the full casebook.

Quick Recall: Lines to Say in the Interview

  • "The model is stateless and the product is not."
  • "Store every turn, send the model only what this turn needs, and stream the answer back."
  • "State and cost are the same problem: every remembered token is paid for again next turn."
  • "Admit, load state, infer and stream, moderate, persist."
  • "Moderation runs before any GPU time is spent."
  • "If inference fails partway, fail over and keep the partial answer; never pretend the turn didn't happen."
  • "We serve existing models; training is out of scope."
  • "Every number I use is a whiteboard assumption, a placeholder for measured throughput."

Design walkthrough

The goal: a consumer chat service that streams fast, keeps every conversation, never leaks across users and keeps GPU cost per user under control.

30-Second Cheat Sheet

  • Clarify first: jumping to architecture is the first failure mode. Ask the six scope questions, state assumptions aloud.
  • Name three hard problems in the first two minutes: conversation state that grows, streaming at very high concurrency, cost that scales with tokens, not requests.
  • Testable requirements: time to first token under 1 s p95, 99.9% send-and-stream, zero cross-user reads.
  • Size it aloud: 100M DAU → ≈ 35,000 messages/s peak → ≈ 280,000 open streams → ≈ 2,800 replicas before prefill and KV checks.
  • The organising rule: admit, assemble, stream, persist. Each verb decides one thing.
  • Store everything, send little: a bounded ~2,000-token prompt instead of the whole history.
  • Stream with SSE and cancel on abandon: tokens nobody reads still cost money.
  • Prove it with numbers: first-token p95, regenerate rate, cache-read share, cost per DAU, cross-user reads at zero, behind a release gate.

Opening line (source's version): "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."


1. Clarify what the chat product includes

Why ask first

  • 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?"
  • "Design ChatGPT" gives you nothing else, so 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 doesn't confirm an answer, state the assumption aloud and design to it.
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

Weak vs strong

  • Weak: draws a load balancer in front of a model and stops. Forgets the model is stateless and the product is not.
  • Strong: names three hard problems in the first two minutes:
    1. Conversation state that grows every turn.
    2. Streaming at very high concurrency.
    3. Cost that scales with tokens rather than requests.

2. Make experience and safety testable

  • A requirement that can't fail a test is a preference.
    • "Fast" is a preference.
    • "Time to first token under one second at p95" is a constraint. Only constraints shape the architecture.
  • Functional = what the system does. Non-functional = how well and under what limits.

Must-haves (6)

  1. Send a message and receive a streamed answer.
  2. Keep and list conversation history per user, with rename and delete.
  3. Carry context across turns within a conversation.
  4. Enforce per-user and per-tier usage limits.
  5. Moderate input and output.
  6. Stop generation when the user presses Stop or the client disconnects.

Should-haves (competitive, follow-on features, not the first answer)

  • File uploads, web search, a code sandbox.
  • Cross-conversation memory the user can inspect and erase.
  • Regenerate and edit-and-resend.
  • Sharing a conversation by link.
  • Later: voice and image generation.

Non-functional constraints, stated so they can be tested

Caveat: the latency and availability numbers are constructed interview targets, not any product's service level agreement (SLA).

Constraint Stated so it can be tested
Latency Time to first token under 1 s p95 for the default model; steady streaming after; no UI freeze before the first token
Availability 99.9% for send-and-stream; a regional outage degrades to another region, not 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 as a first-class metric
Privacy Content excluded from logs by default; deletion propagates to history, memory, files and caches

p95 first token of one second = 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 (RPO).

Recovery-point objective = the most recent data you accept losing in a disaster, stated up front.

Give every must-have an owner

  • Nothing is left to "the model will handle it".
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

Spoken answer: "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, not optional.
  • The interviewer is scoring the method, not the numbers.

Caveat: every value below is an assumption for the whiteboard.

The walk

  1. Messages: ten messages per user per day × 100 million DAU = one billion messages.
  2. Average rate: ÷ 86,400 seconds ≈ 11,600 messages/s.
  3. Peak: a threefold peak ≈ 35,000/s.
  4. Output: 400 output tokens per answer ≈ 14 million output tokens/s at peak.
  5. Input: 2,000 input tokens per turn (system prompt, summary, recent turns) ≈ 70 million input tokens/s, most of it a prefix the model has already processed.
  6. Stream time: at 50 tokens/s decode, a 400-token answer takes eight seconds to stream.
  7. Open streams (Little's Law): 35,000 turns/s × 8 s ≈ 280,000 open streams.
  8. Replicas: at 100 concurrent streams per batched replica, the first pass is ≈ 2,800 replicas at peak.

Little's Law: in a stable system, concurrency = throughput × time each item spends in the system. Name it.

Why the real number is higher: two quick checks

  • Prefill also holds a slot.
    • About one second to first token adds roughly 35,000 × 1 ≈ 35,000 in-flight turns.
    • That is about 350 more replicas.
  • Slots are not compute.
    • 70 million input tokens/s over 2,800 replicas = 25,000 input tokens/s per replica if nothing is cached.
    • That is on top of 100 × 50 = 5,000 output tokens/s of decode.
    • Only a high prefix-cache hit rate keeps that prefill load affordable.
    • So caching belongs in the sizing, not in a later optimisation pass.
  • Real prefill and decode throughput, key-value (KV) cache memory, queueing and failure headroom can all push the replica count higher.

The full sizing table

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 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.
  • Prefix caching matters more in chat than almost anywhere else. The 70 million input tokens/s are mostly history the model processed on the previous turn.
  • Storage: about 2 KB per message grows by roughly 2 TB a day, before indexes, replication and retention.

Split latency into its two phases

Phase What it does Sets Scales with
Prefill Processes the whole prompt in parallel Time to first token Input tokens
Decode Generates one token at a time Total time 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

Division of labour

  • 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: admit, assemble, stream, persist

Verb Decides
Admit Whether a request may use a GPU at all
Assemble (context builder) What the turn costs
Stream What the user feels
Persist What survives

The decision edges

  • Input moderation can block a turn before it reaches the model.
  • Output moderation can halt a stream.
  • Disconnect or Stop cancels model and tool work and frees KV cache.

Follow one turn through it

  1. The client is routed to a healthy region.
  2. The regional streaming gateway authenticates, applies per-user and per-tier token budgets and runs input moderation before GPU admission.
  3. The conversation service reads durable history, persists the new message, and later saves partial output as tokens arrive, so a reconnect has something to resume.
  4. 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.
  5. A router picks a model the user's tier allows and the task needs.
  6. A bounded fair queue protects each tier and prefers a warm replica only while that replica has capacity.
  7. The pool generates with continuous batching and prefix/KV reuse.
  8. Optional tools (search, file, code) run under step limits. Untrusted file content never gains the authority of an instruction.
  9. Output moderation checks streamed chunks before delivery; the gateway sends server-sent events (SSE) to the client.
  10. Regional failover is possible but may be cold and slower.

SSE (server-sent events) = a simple way for a server to stream an answer to the browser as it is written, over plain HTTP.

The two other views the source draws

  • Request-order view: adds the edge layer (edge and GeoDNS) and shows the inference pools as small, default and premium model sizes behind the tier and task router, with a per-tier fair scheduler with warm KV affinity.
  • Planes view: groups the same components into control, edge, serving, conversation-state and tools-and-files planes, with pass, block, halt and client-closed edges.

What each plane owns

Plane Owns
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
Conversation-state plane History, titles and partial answers sharded by user_id; a memory store namespaced by user_id
Tools and files Web search, code sandbox, bounded steps, per-user upload, scan, parse, embed
Observability Stage timings, tokens, cache reads, abandonment and moderation events without conversation text
  • Replication: conversation state follows each user's home region; control-plane configuration replicates everywhere; inference pools are independent per region.

The fifteen components, in request order

Read the last column aloud. Each component has a defined way to fail.

# 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

Point at three boundaries while the diagram is up

Boundary Where Why
Admission The gateway Nothing reaches a GPU without passing auth, quota and input moderation
Isolation Every store Each one is namespaced by a user_id that comes from authentication
Cost The context builder 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.
  • The model can't be billed for history the context builder never sent.

What the conversation service writes

  • Every message, durably, keyed by (user_id, conversation_id).
  • The partial answer as tokens stream, so a user who disconnects reconnects to the text generated so far, not 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: one user's history lives on one shard, and a list-conversations call touches one partition.

The fixed assembly order

system prompt → rolling summary → recent turns → memory facts → retrieved file chunks → new message

Why bound it: turn 40 of a long conversation

  • Sending all 40 turns makes prefill slower and more expensive every turn.
  • The growth is quadratic over the conversation.
  • The arithmetic: each turn adds about 500 tokens of question and answer, so turn k carries about 500 × k tokens.
    • 40 turns send 500 × (1 + 2 + … + 40) = 500 × 820 = 410,000 input tokens.
    • That delivers only about 20,000 tokens of new text.
  • A bounded prompt of about 2,000 tokens caps the same conversation at about 80,000.

Two ways to bound history

Approach Keeps Costs
Sliding window of the last few turns A small prompt Loses anything that scrolls out
Summarisation once the buffer crosses a threshold A condensed record One extra model call per compression
  • The memory guide's worked answer folds the buffer at about 15 turns.
    • Caveat: an illustrative threshold to tune, not a rule. 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".
Memory type Holds Update rule
Semantic Stable facts, such as a preferred language Stable key that overwrites in place
Episodic One record per completed task Appends, and is pruned
  • Different update rules → don't share one write path.

The 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: a user who can't see a remembered fact can't correct it.
  • A deletion request propagates to the conversation store, memory, uploaded files and caches.

Soundbite: "Store everything, send little."


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.

Why SSE, not WebSockets

Transport Use it for Why
SSE The chat stream After the request, traffic is one way, server to client. Runs over plain HTTP, so it passes most proxies that don't buffer responses. The browser's EventSource client reconnects on its own.
WebSockets Paths that need both directions at once, such as voice Two-way channel
  • Implementation note the source doesn't cover: EventSource issues only GET requests.
    • A chat API that sends the message as a POST usually reads the SSE stream with a fetch reader.
    • It then handles reconnect and resume itself, using the message ID.

Cancel on abandon

  • A user who leaves mid-answer is still costing GPU time.
  • The source's cost notes name it directly: "cancel the stream + any in-flight tool calls on abandon — otherwise you pay for tokens nobody read."
  1. The gateway detects the closed connection.
  2. It sends a cancel to the inference request.
  3. That frees the batch slot and its KV cache.
  4. It stops any tool call in flight.
  5. The Stop button uses the same path.

KV cache = the attention state the model keeps for the sequence so far.

  • Test it end to end: middleware can swallow a disconnect.
    • The source's reference list cites a vLLM issue where abort-on-disconnect broke behind middleware.

Measure abandonment

  • 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.

Soundbite: "Cancel on abandon. Tokens nobody reads still cost money."


7. Admit fairly, moderate both ways and recover regionally

  • Three controls sit around the serving path. Each has a deep dive.
Control What it does Key rules
Admission and fairness A token bucket per user, sized by tier, decides whether a request proceeds. 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. Keep your own quota 429 separate from a provider or pool capacity event.
Moderation and untrusted content Input moderation blocks severe requests before 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, never instructions. Retrieval over uploads filtered by user_id. Tools step-capped. Code sandbox has no network or credentials.
Regional recovery Each region has independent gateway and inference capacity; 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 eligible regions. Use circuit breakers and reserved capacity instead of assuming new GPUs start instantly.

HTTP 429 = "too many requests".


8. Prove the product before expanding a release

Measure first-token time, then trace per stage

  • Measure time to first token, not only total latency: it's 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 → tools.
  • Record stage timings, token counts, cache reads, abandonment and moderation outcomes.
  • Keep message text out of ordinary telemetry by default, as section 2 of that case recommends.

Tie every choice to a number

  • The question bank's second failure mode is hand-waving evaluation.
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 the metrics with care

  • A falling regenerate or thumbs-down rate supports a quality improvement.
    • Compare it by user segment and alongside completion. Neither is a perfect label.
  • Report queue wait and service time separately, so a scheduling problem isn't mistaken for a model problem.

The release gate

  • 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 doesn't pass.
  • Keep a fast rollback to the previous version.
  • Treat a system-prompt change as a release: it also changes the cache prefix and therefore the cost line. Watch the cache hit rate during the canary.

Quick Recall: Lines to Say in the Interview

  • "The model is stateless and the product is not."
  • "What questions would I ask before designing anything? Consumer or API, users, tiers, memory, files and tools, and whether we train."
  • "Time to first token under a second at p95 means 95% of turns start streaming in a second, not that they finish."
  • "35,000 a second at peak times eight seconds is about 280,000 open streams, about 2,800 replicas before prefill checks."
  • "Admit, assemble, stream, persist: admission decides GPU use, the context builder decides cost, the stream decides feel, persistence decides what survives."
  • "Store everything, send little: 410,000 tokens for 40 full turns versus about 80,000 bounded."
  • "Streaming buys perceived latency, not real latency."
  • "Cancel on abandon. Tokens nobody reads still cost money."
  • "A system-prompt change is a release, because it moves the cache prefix and the cost line."

Technical deep dives

What this part covers: the mechanisms behind the follow-ups. Prefix caching, routing, admission, moderation, regions, the Claude wording and the source's dated references.

30-Second Cheat Sheet

  • Chat is the best case for prefix caching: each turn is the previous turn plus a little. Matching is byte-exact; one changed byte invalidates everything after it.
  • Caches expire and live on one machine: stable parts first, volatile parts last, soft session affinity to a warm replica.
  • Routing has a number: moving 80% of traffic from Opus 5.5 to Haiku 4.5 cuts that slice about 4×, all traffic about 2.5×. But a cascade forfeits the cache.
  • Two questions, two mechanisms: a rate limit decides whether; a fair queue decides in what order.
  • Two kinds of 429: yours is policy; a provider's or full pool's is capacity.
  • Moderate both ways: output moderation catches what the model repeats from earlier turns. Files and pages are data, never instructions.
  • Failover is cold, not closed: shed the free tier, circuit-break the sick pool, respect residency.
  • The Claude wording: same design, more time on batching, queues and failover.

1. Prefill, decode and byte-stable prefix reuse

Why chat is the best case

  • 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 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

Vendor Matching Scope Lifetime
Claude API (from the cost notes) Byte-exact prefix, rendered in the order tools → system prompt → messages. One changed byte invalidates everything after it. Per model Default entry lives five minutes, refreshed each time it is read; a one-hour option whose cache write costs more
OpenAI prompt cache Exact prefixes Per model Automatic cache typically keeps a prefix for 5 to 10 minutes of inactivity, longer on some models
  • Provider caches expire. 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.

Build the prompt stable-first

  • 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 silent invalidators behind a sudden drop in cache hits

  1. A datetime.now() value in the system prompt.
  2. Unsorted JSON keys.
  3. A tool list whose order varies between requests.
  4. A prompt-version bump.
  5. A model swap.
  • Prove the cause with the cache-read token counter, not 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 (LRU) first.
    • 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.
  • 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: 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

  • Rewriting the summary changes the prefix after it.
  • Folding history every turn would defeat the cache.
  • Fold in large steps, where quality allows.

Soundbite: "Prefix caching is a byte-exact prefix match. Stable first, volatile last."


2. Model routing can sacrifice cache savings

Route on two axes

Axis Sets
The user's tier Which models a user may reach, and at what quota
The turn's difficulty (task) Which of those models this turn needs. A greeting doesn't need the premium model; a long proof might

Put a number on it (the source's cost notes)

  • On Claude's list prices as of September 2026, output costs five times input on every tier. Other vendors' ratios differ.
Model Input per million tokens Output per million tokens
Opus 5.5 $4 $20
Haiku 4.5 $1 $5
  • The sentence to say: 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.
  • Across all traffic (same token mix), the saving is smaller:
    • 0.2 + 0.8 × 0.25 = 0.4 of the original unit cost.
    • About 2.5 times cheaper, before cache effects.

Caveat: 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. That keeps the five-to-one output ratio but changes the routing arithmetic, so recompute with the prices on the day.

The trade-off: a cascade forfeits the cache

  • Prompt caches are scoped to a model.
  • A cheap → medium → 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.
  • Every escalation adds an attempt.

The source's rules

  • Measure one strong model at lower effort before building the cascade.
  • Route at the start of a conversation where possible.
  • 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.

Soundbite: "A cascade forfeits the cache. Measure one model at lower effort first."


3. Admission, fair queues and two kinds of 429

Two mechanisms, two questions

  • Section 7 of the Secure Multi-Tenant AI Platform case draws the line.
Mechanism Question it answers Where
Rate limit (token bucket) Whether this request may proceed at all Gateway, per user, sized by tier
Fair queue (weighted, per tier) In what order admitted requests are served under load In front of the shared inference pools

The token bucket

  • Per user at the gateway, sized by tier: messages per window and tokens per day.
  • Refills at a fixed rate; lets a request through only while tokens remain.
  • Allows short bursts but caps the average.
  • Count tokens, not only requests: one long request can cost as much as, say, fifty short ones.

Token bucket = a counter that refills at a fixed rate; each request spends from it, and an empty bucket means wait or reject.

The weighted fair queue

  • One per tier, feeding the shared inference pools.
  • Each tier gets a share of service in proportion to its weight.
    • A free-tier surge waits longer while paid users keep their latency.
    • No tier is starved outright.
  • Keep the queues bounded: reject or defer before the wait would break the latency objective.
  • Never drop an admitted stream silently.

Separate the two kinds of HTTP 429 (too many requests)

  • The cost notes: "Separate provider 429s from your own gateway limits."
429 from What it means Response
Your gateway A policy decision The user is over their quota or rate
A model provider or a full pool A capacity event Short term: retry with jitter onto a fallback model or region; shed non-interactive traffic. Long term: buy capacity and queue non-urgent work rather than retrying into the same wall.

Abuse is a rate-limit problem too

  • Per-account and per-IP limits.
  • Detect anomalous bursts.
  • Stricter quotas for new or unverified accounts.

Soundbite: "A rate limit decides whether; a fair queue decides in what order."


4. Moderation, files and tools as untrusted input

Moderate both ways

  • Input before it reaches a GPU, output before it reaches a screen.
  • Why both (the production guide): the model can repeat something sensitive the user said two turns ago, and an input-only check never sees that response.
Option Cost Catches
Input-only Cheaper: classifies only the user's message Misses the multi-turn case
Input plus output Two checks The multi-turn case. A consumer chat product is multi-turn by definition

How each side runs

  • Input moderation: a fast classifier at the gateway, before admission, so a blocked message never spends GPU time.
    • 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 can't be withdrawn, so choose the chunk size by how much exposure the policy tolerates.

Thresholds and policy are the application's job

  • Moderation APIs score a fixed set of categories.
  • At default thresholds, milder or app-specific abuse can still pass.
  • The guide names two independent layers: the model's trained refusals and the moderation classifier. Neither substitutes for an app-specific policy.
  • Measure false positives as closely as false negatives on a labelled sample: over-blocking is the failure users notice first.

Files and tools carry indirect prompt injection

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 upload pipeline and bounded tools

upload → user-scoped object store → scan → parse (async) → chunk and embed per user

  • Retrieval over uploads is filtered by user_id at query time.
    • The same two-layer idea as section 6 of the Enterprise Knowledge Assistant case.
  • Bounded tools: web search, the code sandbox and file retrieval.
    • Tool steps are capped per turn.
    • Each tool call has a timeout.
  • The code sandbox runs with no network and no credentials, and is destroyed after the session.

5. Regional recovery has data and capacity limits

  • Serve each user from the nearest healthy region. A regional failure should 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 doesn't queue behind another's.

History: home region plus async replica

  • Each user has a home region for the conversation store, replicated 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.

Control plane: central for policy, 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.
    • 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.
  • Hold reserved capacity while new GPUs warm.
  • Circuit breaker on a sick pool, so requests stop paying to rediscover a failure.
Circuit-breaker state (the production guide) Behaviour
Closed Normal operation
Open After repeated failures: stop sending work
Half-open After a cooldown, let one probe through

Model outage

  • Degrades to another model in the same tier.
  • Never to an error page while any healthy model the user may reach remains.
  • If no permitted path is left: an explicit unavailable-and-retry state with the saved conversation still readable.

Soundbite: "Failover is cold, not closed."


6. Answer the Claude-service wording

Same design, different emphasis

  • "Design the Claude chat service" is the same prompt as "Design ChatGPT". 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: inference batching, GPU routing and a 100,000-requests-per-second token service. The source groups them with the LLM Inference Serving case.

Where to spend more of the hour

  1. The Little's Law sizing.
  2. The fair queue.
  3. Continuous batching with session affinity.
  4. Failover.

Two expected follow-ups (from the batching prompt)

Follow-up Answer
"How do you determine which GPU has capacity?" The scheduler tracks per-replica queue depth and free KV memory and prefers the replica already holding the conversation
"How do you handle failover?" The degradation ladder below

The Tier 2 safety probe carries extra weight here

  • Circuit breakers, rate limiting and graceful degradation when the model is unavailable.

The degradation ladder, said as a list:

  1. Shed free-tier and non-interactive traffic before paid traffic.
  2. Open the circuit breaker on the sick pool and stop sending it work.
  3. Fall back to another healthy model in the same tier.
  4. Fail over to another eligible region, accepting a cold first turn.
  5. Only when no permitted model remains, show an explicit unavailable state with the saved conversation.

7. Source references and limits

Caveat: the source fact-checked its serving, cancellation, pricing, cache and moderation claims on 27 September 2026. Treat the prices as dated arithmetic, and verify cancellation, transport and cache behaviour for your actual runtime and middleware before launch.

Reference Claim it supports
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; self-hosted KV reuse saves compute, not 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:


Quick Recall: Lines to Say in the Interview

  • "Prefix caching is a byte-exact prefix match. Stable first, volatile last."
  • "A datetime.now() in the system prompt silently kills the cache; prove it with the cache-read counter."
  • "Soft affinity keeps a conversation on a warm replica, and it yields to capacity and health."
  • "Eighty percent from Opus 5.5 to Haiku 4.5 is about four times cheaper on the slice, 2.5 times overall, before cache effects."
  • "A cascade forfeits the cache. Measure one model at lower effort first."
  • "A rate limit decides whether; a fair queue decides in what order."
  • "Our 429 is policy; a provider's 429 is capacity."
  • "Moderate output too: the model can repeat what the user said two turns ago."
  • "Failover is cold, not closed."

Quick review

One sentence: admit safely, assemble bounded user-scoped context, stream from continuously batched pools, persist partial answers and cancel abandoned work.

30-Second Cheat Sheet

  • Ask first: consumer or API, DAU and turns, tiers, history and memory, files and tools, serve or train.
  • The model is stateless; the product is not. Store every turn, send only summary, recent turns and relevant memory.
  • Assumed sizing: 100M DAU → ≈ 35K/s peak → ≈ 280K open streams → ≈ 2,800 replicas before token and KV checks.
  • A rate limit decides whether; a fair queue decides when.
  • Byte-exact stable prefix + warm replica save input prefill; a model cascade may lose that cache.
  • Streaming improves perceived latency; cancellation saves actual GPU cost.
  • User scope comes from authentication at every store and retrieval boundary.
  • Measure first-token latency, fairness, isolation and cost per user, and gate every prompt change.

1. Recall the turn and its limits

Ask first

  1. Consumer or API?
  2. Daily active users and turns?
  3. Tiers?
  4. History and memory?
  5. Files and tools?
  6. Serve or train models?

The whiteboard path

client → regional gateway (auth, quota, 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)

Item Value
Daily turns 100M DAU × ten turns = 1B a day
Average rate ≈ 11.6K/s
Peak (3×) ≈ 35K/s
Input tokens at peak 70M/s
Output tokens at peak 14M/s
Open streams Eight-second answers → about 280K
Replicas 100 streams per replica → about 2,800, before token-throughput and KV checks

Five lines to remember

  1. The model is stateless; the product is not. Store every turn, send only the summary, recent turns and relevant memory.
  2. A rate limit decides whether a request runs; a fair queue decides when.
  3. A stable byte-exact prefix and a warm replica save input prefill; a model cascade may lose that cache.
  4. Streaming improves perceived latency; cancellation saves actual GPU cost.
  5. 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."

2. Decisions and failure responses

Area Decision or failure response
Clarify Clarify the product and state assumptions before drawing; the prompt gives nothing else
Requirements Testable: first token under a stated p95, zero cross-user reads, measured moderation error rates
Sizing The walk from daily users → open streams → replicas shows why admission, streaming and caching are mandatory
Diagram One diagram shows admit, assemble, stream, persist, with boundaries at the gateway, the stores and the context builder
State Store every message durably; send the model only a summary, recent turns and user-scoped memory. Summaries can drop a detail.
Streaming Stream with SSE, persist partial answers, and cancel generation and tools when the client leaves
Routing Route by tier and task, and count the prompt cache a cascade forfeits
Admission A per-user token bucket decides admission; a weighted fair queue per tier decides order. Keep your 429s separate from provider 429s.
Moderation Moderate input and output, and treat every file and fetched page as untrusted data
Caching Keep the prefix byte-stable and each conversation on a warm replica, so history is a cache read
Regions Serve per region with a home region for history. Failover is cold, not closed; residency still holds.
Release Measure time to first token, regenerate and abandon rates and cost per daily active user, and gate every prompt change
Claude wording The same design, with more time on batching, queuing and failover
Cost pivot Stable prefix, stepped summaries, short answers, route down, cancel on abandon

The short spoken answer to close on

Spoken answer: "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."


Flashcard Drill


Quick Recall: Lines to Say in the Interview

  • "The model is stateless; the product is not."
  • "Store every turn; send only the summary, recent turns and relevant memory."
  • "1B turns a day, 35K a second at peak, about 280K open streams, about 2,800 replicas before KV checks."
  • "A rate limit decides whether; a fair queue decides when."
  • "A byte-exact prefix and a warm replica save prefill; a cascade may lose that cache."
  • "Streaming improves perceived latency; cancellation saves actual GPU cost."
  • "Keep my 429s separate from provider 429s."
  • "Failover is cold, not closed; residency still holds."
  • "Stable prefix, stepped summaries, short answers, route down, cancel on abandon."

Where next