GOAT EngineerPreparing your learning space…

AI Engineering · Interview breakdown · Free article

Design ChatGPT

Designing ChatGPT is mostly an inference-serving problem: the GPUs, not the web tier, set the latency and the bill. Walk the round as a strong candidate does, from requirements and token math to the KV cache, continuous batching and the staff-level trade-offs.

This is the AI system design question you are most likely to get, and it looks familiar — a chat box, a database, a stream of text — which is exactly the trap. Almost everything you know about scaling web apps points the wrong way here. The bottleneck isn't the database, it's the GPU. The latency number that matters isn't total response time, it's time to the first token. And cost is a design constraint, not an afterthought — because every token the model reads or writes is money leaving the building. Get those three inversions and you're already ahead of most candidates. This breakdown walks the whole round: scope it down, size it, draw it, then go deep where the interview is actually won — serving the model, and the price of a token.

A user types a question and hits Enter. Somewhere in a data center, a GPU has about half a second to start saying something back — not to finish the answer, just to begin — or the person starts to feel that the thing is broken. As it writes, each word it emits costs a fraction of a cent, and there are a hundred million other people typing today.

That single moment is the whole interview. "Design ChatGPT" looks like a chat app — a text box, some history, a database — and that resemblance is the trap. A chat app is I/O-bound and cheap; this is compute-bound and expensive. If you design it like a normal web service, you will scale the wrong tier, optimise the wrong latency, and never mention the cost — and a good interviewer will notice all three.

Name those three in the first few minutes and the interviewer relaxes — they now know you have actually thought about LLMs in production, not just drawn boxes. The rest of the hour is you backing them up.

Scope it down before you build anything

The fastest way to lose this round is to try to build all of ChatGPT. The product has file uploads, voice, image generation, custom personas, memory across chats, browsing, a plugin store. If you design for all of it you will design none of it well. A strong candidate narrows to the irreducible core in one breath, then explicitly parks the rest — which shows range without drowning.

The core is smaller than people expect:

The two requirements everything hangs on

  1. Send a message and get a streamed reply. The user posts a prompt in an ongoing conversation and the assistant's answer appears token by token, live — not all at once when it's done. Multi-turn: each reply is conditioned on everything said so far in that chat.
  2. Conversations persist and resume. History is saved, listed in a sidebar, and can be reopened later with full prior context intact. Lose this and you have a stateless demo, not a product.

Then name the things you are deliberately deferring, with a one-line reason each — this is where you signal seniority, because you are showing you know they exist and why they are separable:

Deferred on purpose — say the reason, not just the name
FeatureWhy it is a separate problem
Edit / regenerate / branchA UX + versioning layer on top of the core send loop; does not change the serving story.
System prompt / custom personasJust a fixed prefix prepended to the context — cheap to add once the loop exists.
File upload, images, voiceMultimodal input is its own ingestion + model-routing problem; bolt on after text works.
Long-term memory across chatsA retrieval problem (embed + store + fetch past facts) — increasingly its own interview question.
Web browsing / tools / RAGTool-calling and grounding are a whole agent design; mention as an extension point.

What has to be true of it

Non-functional requirements are where this problem stops resembling a web app. State each as a number or a target, because each one drives a specific later decision.

The NFRs that actually move the design

  • Time-to-first-token under ~500 ms. This is the responsiveness bar for a chat product. Total completion can take several seconds — that's fine while it streams — but the gap before the first word must feel instant. Everyone who has used a good assistant has felt this; make it explicit.
  • Throughput measured in tokens per second, not requests per second. A "request" here isn't a fixed unit of work — a two-word reply and a two-page essay are wildly different loads. You capacity-plan in tokens.
  • Availability ~99.9%, degrading gracefully. When GPUs are saturated or a model provider is down, the system should queue, fall back, or shed load with an honest "high demand" message — never hang or 500.
  • A cost ceiling. Unusual for system design, essential here. The unit economics — cost per conversation — decide whether the product survives. Treat $/token as a first-class budget.
  • Scale envelope: on the order of 100M+ daily users and billions of messages a day. Read-heavy on history (~90% reads), but the write that matters is the expensive one — the generation.

Size it before you draw it

The estimation for a normal system ends at QPS and storage. Here it ends at how many GPUs and how many dollars a month — and getting there is the most impressive thing you can do in this round, because almost nobody does it and it forces every assumption into the open. The chain is: users → messages → peak arrival rate → concurrent generations → aggregate tokens per second → GPU count → cost.

Work it as a formula first, then plug in one set of numbers. The point is the method; the interviewer can swap any input.

The estimation chain (state each assumption as you go)

  1. Messages per day. Say 100M daily users × ~8 messages each = ~800M messages/day.
  2. Peak arrival rate. Spread over a day that's ~9,000 messages/sec average; traffic is spiky, so assume peak ≈ 3× average ≈ ~30,000 messages/sec.
  3. Concurrent generations. Each answer takes time to write — say ~15 s at a live-feeling pace. Concurrent streams at peak ≈ arrival rate × generation time = 30,000 × 15 ≈ ~450,000 conversations generating at once.
  4. Aggregate decode load. Each live stream emits maybe ~30 tokens/sec (fast enough to feel fluid). Total = 450,000 × 30 ≈ ~13.5M tokens/sec the fleet must produce at peak.
  5. GPU count. A well-batched 8×H100 node serving a 70B-class model does on the order of ~2,800 tokens/sec (more on why that number is a choice, not a constant, in the serving section). So 13.5M ÷ 2,800 ≈ ~4,800 nodes ≈ ~38,000 H100 GPUs — before any caching or smaller-model routing.
  6. Cost. ~38,000 GPUs × ~$2.90/GPU-hour × 730 hours/month ≈ ~$80M/month, at full precision, before optimisation.

The interactive version of this example is available when JavaScript loads.

The design in one picture

Now the architecture. Walk it as the path of a single message, from keystroke to streamed reply, naming what each stage is for. The shape is a normal request pipeline wrapped around one abnormal, expensive core — the model-serving fleet.

The request path — every message flows through these stages
StageWhat it does
ClientWeb or mobile; opens a streaming connection and renders tokens as they arrive.
API gatewayTLS, routing, authentication, request logging. The front door.
Rate limiterPer-user and per-tenant token buckets, tier-aware — free users can’t starve paying ones out of GPU time.
Input moderationFast classifier that blocks disallowed prompts before they ever reach a GPU.
OrchestratorThe brain of a turn: loads history, assembles the context window (system prompt + memory + recent turns + reserved output budget), picks a model, calls inference.
Conversation storePostgres (primary + read replicas) for history; Redis for the hot recent-turns cache. Durable, cheap, boring — as it should be.
Inference gatewayQueues the request and schedules it onto a GPU worker with free capacity in its batch.
GPU serving fleetThe scarce, costly core: runs the model, streams tokens back. Everything else exists to keep this busy and no busier.
Output moderationScreens the reply as it streams — incrementally, not just at the end.
Async writerPersists the completed exchange off the hot path once streaming finishes.

A subtle but important point to make while drawing: the orchestrator is code, not a prompt. Control flow — which model, how much history to include, whether to retrieve, when to fall back — lives in a real service you can test and reason about. Candidates who try to push that logic "into the prompt" get pressed hard, because prompts are not a control plane.

With the skeleton on the board, the interviewer will pick a box and say "go deeper." It will almost always be the GPU fleet or the cost of feeding it. That's where the round is won.

Serving the model: where the milliseconds and the money go

This is the deep dive that separates people who have deployed LLMs from people who have only called them. You do not need to be able to train a model. You do need to know why serving one is strange, because that strangeness is the entire cost and latency story.

Generating an answer happens in two phases, and they have opposite performance characteristics.

Prefill vs decode — the two halves of one generation

  • Prefill: the model reads your whole prompt at once and builds up its internal state. This is a big parallel matrix crunch — compute-heavy, but it happens in one shot. Prefill time is what your time-to-first-token mostly depends on: the longer the prompt, the longer before the first word appears.
  • Decode: the model then writes the answer one token at a time, each new token depending on all the ones before it. This part is inherently sequential and, crucially, memory-bandwidth-bound — the GPU spends more time shuttling the model's weights and remembered state around than doing math. It's the slow, expensive part, and it sets your inter-token latency.

Two mechanisms make decode survivable at scale, and naming them is what makes this answer land.

The interactive version of this example is available when JavaScript loads.

There's a memory twist that pairs with batching: the KV caches of all those batched conversations have to fit in GPU memory, and they're different lengths and constantly changing. PagedAttention manages KV-cache memory in small fixed pages like an operating system manages RAM, so you can pack far more concurrent conversations onto a GPU with almost no wasted memory (under ~4% overhead). This is what serving engines like vLLM are built around — you can name it as "the paged-memory trick that makes big batches actually fit."

Two more serving levers to mention

  • Model routing by difficulty and tier. Not every prompt needs the frontier model. Route easy or free-tier requests to a smaller, cheaper model and reserve the big one for hard or paid traffic. This is the biggest single cut to the fleet estimate, and it's a routing decision in the orchestrator.
  • Quantization. Serving the model in lower precision (FP8, INT4) shrinks it and roughly doubles to triples throughput per GPU, at a small, measurable quality cost. It's a throughput-vs-quality dial you tune against your evals — which is exactly why the evaluation section later isn't optional.

The cost model: a token is a unit of money

Most people never open this box, which is exactly why opening it well is a differentiator. The whole product's viability is a cost-per-conversation question, and the levers are concrete. Start with the one table that reframes everything: the same model on the same hardware costs radically different amounts per token depending on how hard you batch it.

Cost per million output tokens vs batch size (a 70B-class model on an 8×H100 node; illustrative, from published 2026 benchmarks)
Batch sizeThroughput (tok/s)Cost per 1M tokens
1~25~$258
8~200~$32
32~720~$9
128~2,100~$3
256~2,800~$2.30

The interactive version of this example is available when JavaScript loads.

The other cost levers, in rough order of impact

  • Buy vs build. Renting a frontier model by the API token can run anywhere from ~$0.14 to ~$5 per million input tokens depending on the model; self-hosting an open-weights model at good batch efficiency can undercut that by 10–50× on raw tokens — at the price of owning GPU ops, capacity planning, and reliability. Below a certain volume, buy; above it, the math flips hard toward build. Naming the crossover is a staff answer.
  • Precision. Quantizing that 70B from full precision to FP8 roughly halves the per-token cost (~$2.30 → ~$1.15); INT4 cuts it further (~$0.77) — for a small quality hit you verify with evals.
  • Model tiering. A small model can be an order of magnitude cheaper per token than a frontier one. Routing the easy majority of traffic to it is often the single biggest line-item cut.
  • Caching (below) is a cost lever, not just a latency one — every cache hit is a generation you didn't pay for.

Streaming the answer back

Everyone gets the surface of this one: the answer streams token by token so it feels alive, and you use Server-Sent Events rather than WebSockets because the data flows one way (server → client), it rides plain HTTP, and the browser reconnects for free. Correct — say it, justify the SSE-over-WebSocket choice in a sentence (WebSockets are for two-way traffic like live voice; text streaming doesn't need the extra machinery), and then go past it, because the basics are commoditised and the depth is where you separate.

The parts that show you have run this in production

  • Stateful connections at scale. Those ~450k concurrent streams from the estimate are long-lived connections, each pinned to the server generating that answer. You need routing that keeps a stream on its server (sticky) and a plan for what happens when that server dies mid-answer — you can't just re-balance a half-written generation to another box.
  • Backpressure. A phone on a slow network can't drain tokens as fast as the GPU produces them. You buffer, and past some bound you have to decide: slow the generation, or drop the client. Unbounded buffering of hundreds of thousands of streams is its own memory outage waiting to happen.
  • Cancellation as a cost lever. This is the one that impresses. When a user hits stop — or just closes the tab — that generation should be killed immediately so the GPU slot is reclaimed for someone else. On a fleet where every slot is precious, promptly freeing abandoned generations is real money, not politeness. This is why "stop generation" earned its place in scope back at the start.

Remembering the conversation

The model has no memory of its own. Every turn, the orchestrator hands it the entire relevant conversation as input — and that input is capped by the model's context window, a fixed budget measured in tokens. So each turn is a packing problem: fit the system prompt, any long-term memory or retrieved facts, and as much recent conversation as helps, while reserving room for the answer — all inside the budget.

Strategies, cheapest to smartest

  • Truncation / sliding window. Keep the most recent turns, drop the oldest. Free and simple; the cost is that the assistant "forgets" the start of a long chat. Fine for most conversations.
  • Running summarization. When the history approaches the budget, replace old turns with a compact summary the model writes. Keeps the gist at the price of an extra model call (latency + cost) and some lossy compression — a subtle fact can vanish into the summary.
  • Memory tiering / retrieval. Keep a working set in the window, store the rest, and pull back only the pieces relevant to the current turn (by embedding + similarity search). This is how "remember me across sessions" works, and it's really the RAG problem in disguise — worth naming as the bridge to that question.

The interactive version of this example is available when JavaScript loads.

Keeping it safe

Safety is a layer, and the tell of a weak answer is bolting it on at the very end. Design it into the path in both directions.

Where the guards go

  • Input moderation, before the GPU. A fast classifier rejects disallowed prompts up front — cheaper and safer than generating first and screening after.
  • Output moderation, on the stream. You're streaming, so you can't wait for the whole answer to screen it — you moderate incrementally and can cut the stream mid-sentence if it turns. Designing moderation to be stream-aware is a detail that shows you've actually built this.
  • Prompt injection and jailbreaks. Untrusted text in the context window can try to override your instructions; jailbreak prompts even transfer between models (a jailbreak found on one frequently works on another). Defenses are layered — instruction hierarchy, input filtering, red-teaming — and you should frame it as an ongoing arms race, not a solved checkbox.
  • PII and audit. Redact sensitive data, log for audit, isolate tenants. Table-stakes, stated briefly.

How do you even know it is good?

Here is the question that quietly separates the strongest candidates: you change a prompt or swap in a cheaper model — how do you know you didn't make the product worse? For a normal service you have correctness tests. For a generative one there's no single right answer, so "it seems fine" is the default, and that's how quality silently rots. The senior answer treats evaluation as infrastructure, with two loops.

The two evaluation loops

  • Offline evals. A curated set of representative prompts with graded expectations, run automatically on every prompt or model change — often using a strong model as a judge against a rubric. This is your regression suite: it catches the change that made things worse before it ships. The course's whole spine is "build the eval harness before you're allowed to trust the system" — this is where that pays off.
  • Online signals. Real usage is the richest evaluator. Explicit thumbs up/down, and implicit tells — a user who regenerates, rephrases, or abandons is voting no. Sample live traffic, judge it periodically, and feed what you learn back into the offline set. That loop, from production signal back to test case, is the flywheel that keeps quality improving instead of decaying.

When it breaks

The failures worth designing for

  • A model provider or GPU pool goes down. Have fallbacks: a secondary provider, a smaller self-hosted model, or a degraded mode. Never a hard dependency on one source of tokens.
  • Demand spikes past capacity. GPUs can't autoscale on a dime — there's a supply limit and a hardware lead time. So you queue, and you make the wait honest ("high demand, hang on") rather than hanging. Graceful degradation beats a white screen.
  • Noisy neighbours. Without tier-aware rate limiting, a burst of free-tier or abusive traffic starves paying users of GPU time. Per-user and per-tenant token buckets keep one user's spike from becoming everyone's outage.
  • Context overflow and cost blowups. A runaway conversation or a pathological prompt can balloon tokens. Budget caps and max-output limits are guardrails, not just tuning.
  • A half-written answer whose server dies. Streaming state is fragile; decide whether you can resume, restart, or must fail that one generation cleanly — you can't silently reassign it.

What each level is expected to reach

The same question is graded very differently by level. Use this to calibrate how deep to go — and to hear what the interviewer is waiting for if they keep probing.

The same answer, five bars
LevelWhat a strong answer reaches
Intern / SDE-1Client → server → “LLM API” → database, with streaming as a typing effect and saved history. Treats the model as a black box. Misses that the GPU, not the DB, is the constraint.
SDE-2Clean component decomposition (gateway, orchestrator, store, moderation). Chooses SSE over WebSockets and justifies it. Handles context truncation. Does rough estimation. Knows caching exists but hand-waves cost.
Senior / SDE-3Names the real bottleneck and why decode is memory-bound. Designs continuous batching + KV cache into serving. Does the tokens/sec → GPU-count math. Tier-aware rate limiting, model routing, cancellation → GPU reclaim, stream-aware moderation.
Staff / PrincipalOwns the end-to-end cost model with real per-token numbers and the buy-vs-build crossover. Articulates batch size as a cost-vs-tail-latency dial and picks the operating point per tier. Treats evaluation as infrastructure. Plans capacity for spikes GPUs can’t absorb. Reasons about quality/cost/latency as one three-way frontier.

The follow-ups they will actually ask

Why is time-to-first-token more important than total response time?
Because the answer streams. A user watching words appear feels engaged even over several seconds; a blank pause before anything appears feels broken. First-token latency governs perceived responsiveness, so it's the SLO you protect — mostly by keeping prompts short (prefill is what you wait on) and by not letting oversized batches delay a new request's first slot.
Why can't you just autoscale GPUs like web servers when traffic spikes?
GPUs are scarce and expensive, with a real supply limit and hardware lead time — you can't conjure ten thousand H100s in five minutes the way you spin up stateless containers. So capacity is planned, not summoned. The design response is queueing, graceful degradation, model fallbacks, and tier-aware rate limiting, rather than pretending you can scale out instantly.
Where would you cut cost first if the model bill doubled overnight?
Check batch utilisation first — running at batch 8 instead of 256 can be ~100× more expensive per token on the same GPU, so that's the fastest, safest win. Then route the easy majority of traffic to a smaller model, quantize the big model to FP8/INT4 (verifying quality with evals), and turn up caching — exact, semantic, and prompt-prefix. Each is a measured trade-off, which is why the eval harness has to exist first.
How do you know a prompt change didn't quietly make answers worse?
You don't, unless evaluation is built in. Run a curated offline eval set (often LLM-as-judge against a rubric) on every change as a regression gate, and watch online signals — thumbs, regenerate/abandon rates — feeding sampled production traffic back into the offline set. “It seems fine” is how quality rots; the eval flywheel is how it improves.

Common pitfalls

What sinks otherwise-competent answers

  • Scaling it like a stateless web app and never naming the GPU as the bottleneck. The single most common miss.
  • Optimising total completion time instead of time-to-first-token, or not distinguishing first-token from inter-token latency.
  • Choosing WebSockets for one-way token streaming without a reason (SSE is the fit).
  • Never mentioning cost — no token economics, no batching, no routing. Half the interesting decisions live here.
  • Happy path only — no provider outage, no overload, no context overflow, no cancellation.
  • Safety bolted on at the end, or output moderation that ignores that you're streaming.
  • Name-dropping tools (“just use vLLM / LangChain”) instead of reasoning about the architecture underneath them.
  • No answer to “how do you know it's good?” — zero evaluation story.

Takeaway

Design ChatGPT rewards one shift in perspective above all: stop thinking in requests and start thinking in tokens — as the unit of latency, the unit of cost, and the unit of load. Once a token is your currency, the rest falls out. The GPU is the bottleneck because tokens are made there. First-token latency matters because that's when tokens start flowing. Batching, caching, routing, and quantization are all just ways to make each token cheaper or faster. And evaluation is what lets you push those levers without flying blind.

Walk the arc — scope down, size in tokens and dollars, draw the pipeline around the serving core, then go deep on serving and cost — and close on the three-way frontier of quality, cost, and latency that a staff engineer trades deliberately. Do that and you haven't just designed a chatbot; you've shown you can build an AI product that survives contact with a hundred million users and a finance review.

By GOAT Engineer. Back to Interview breakdown. Privacy Policy · Contact.