Contents
Key concepts
A repeatable structure
Spend the first five to eight minutes on requirements: users, core flows, scale, latency and availability targets, data sensitivity and residency, budget. Then do estimates, sketch the API and data model, draw the architecture, and go deep on the two or three hardest parts (often the model, the data pipeline and serving). Close with trade-offs, failure modes and how you would evaluate and roll out. State assumptions aloud and check them with the interviewer.
Back-of-envelope numbers to know
1M requests a day ≈ 12 per second on average; plan for peaks of 3–10×. Main memory reference ≈ 100 ns; SSD random read ≈ 100 µs; round trip within a data centre ≈ 0.5 ms; London to US East ≈ 70–80 ms. An H100 SXM offers about 989 TFLOP/s dense bf16, 3.35 TB/s HBM and 80 GB; NVLink about 900 GB/s per GPU; inter-node networks commonly 400 Gb/s per GPU. A float32 1,024-dimensional embedding is 4 KB. For LLM bills: cached prompt prefixes are typically charged at about a tenth of the normal input price or less (cache writes cost a little more, for example 1.25× for a short-lived cache), batch APIs halve the price for work that can wait up to 24 hours, and Anthropic measured agents using about 4× and multi-agent systems about 15× the tokens of a chat interaction.
Compute-bound versus memory-bound
Arithmetic intensity is FLOPs per byte moved. If it is below the hardware ridge point (peak FLOP/s ÷ bandwidth, about 295 for an H100 in bf16) the kernel is limited by memory bandwidth, otherwise by compute. Elementwise operations and small-batch decode are memory-bound, so fuse kernels, batch more or quantise; large matrix multiplications and prefill are compute-bound, so use lower-precision tensor cores. Overhead (Python, kernel launches) dominates tiny workloads.
Evaluation-first ML design
Define the decision the model supports and its cost of errors, then the offline metric that tracks it (for moderation: recall at fixed precision per policy area, measured on a stratified, regularly refreshed set), then the online metric and guardrail metrics for the A/B test. Plan for delayed or biased labels: chargebacks arrive weeks later, implicit feedback has position and selection bias, and a model’s own decisions censor the labels you will see (you never learn whether a blocked transaction was fraud).
Batch, online and streaming inference
Batch scoring is cheapest and simplest when predictions can be stale for hours (nightly churn scores). Online inference is needed when inputs arrive with the request (fraud, search ranking). Hybrids precompute heavy features or candidate sets in batch, compute fresh velocity features in a stream processor, and run a light model online. Training-serving skew, where features are computed differently offline and online, is a classic failure; a shared feature store or shared feature code mitigates it.
LLM application architecture
Choose the least autonomous design that works: a single prompt, then a fixed workflow (chain, router, parallel calls, evaluator-optimiser), and only then an agent loop when steps cannot be predicted in advance; orchestrator-worker multi-agent designs pay off only for valuable, parallel, breadth-first tasks. Common building blocks: retrieval with reranking, a gateway or router for provider failover and model tiers (including routing between a fast and a reasoning model, as GPT-5 does), prompt-prefix caching with static content first, guardrails, structured outputs and tracing. Tools are increasingly exposed through MCP, a vendor-neutral standard under the Linux Foundation since December 2025, behind a gateway that enforces authentication, per-user permissions and audit. Use retrieval for changing knowledge, fine-tuning for behaviour, format or latency, and long context when the corpus is small and fits, remembering that recall degrades as context fills, so curate what goes in rather than stuffing it.
Flow · 4 stepsChoosing the least autonomous LLM design
- Start simple Begin with a single prompt when the task is simple.
- Use a fixed workflow Move to a fixed workflow (chain, router, parallel calls, evaluator-optimiser) when the steps are fixed.
- Use an agent loop Use an agent loop only when steps cannot be predicted in advance.
- Reserve multi-agent Orchestrator-worker multi-agent designs pay off only for valuable, parallel, breadth-first tasks.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Start simple | Begin with a single prompt when the task is simple. |
| 2 | Use a fixed workflow | Move to a fixed workflow (chain, router, parallel calls, evaluator-optimiser) when the steps are fixed. |
| 3 | Use an agent loop | Use an agent loop only when steps cannot be predicted in advance. |
| 4 | Reserve multi-agent | Orchestrator-worker multi-agent designs pay off only for valuable, parallel, breadth-first tasks. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Task | Input | |
| Single prompt | Design | |
| Fixed workflow | Design | chain, router, parallel calls |
| Agent loop | Design | |
| Multi-agent | Design | orchestrator-worker |
Source: This page's text
Multi-tenancy and isolation
Isolate data by tenant at the storage and index level (separate namespaces or indexes, row-level security, per-tenant encryption keys), never only in application logic or prompts. Protect against noisy neighbours with per-tenant quotas, fair scheduling and separate queues for large batch jobs. For customisation, per-tenant LoRA adapters served on a shared base model are far cheaper than separate deployments.
Trade-offs interviewers want named
Latency versus quality (smaller model plus reranker, a larger model, or a reasoning model whose thinking tokens add seconds and cost), cost versus freshness (re-embedding frequency), synchronous versus batch (half price if results can wait), consistency versus availability, fail-open versus fail-closed when a dependency times out (fraud scoring usually falls back to rules), single provider versus multi- provider with evaluation parity, and build versus buy. Say which way you lean for this prompt and why.
Worked examples
Back-of-envelope for real-time card-fraud scoring
Design estimates for a service that scores card transactions in real time: 1,500 transactions/s on average, 5,000/s at peak, a 50 ms p99 budget for scoring inside the authorisation flow, 60 million cards and 2 million merchants.
1. Latency budget (p99, 50 ms).
- Network and authentication into the service: 5 ms.
- Feature fetch: card, merchant and device profiles in parallel from an in-memory store: 10 ms.
- Streaming velocity features (spend in the last 1 h and 24 h, distinct merchants) precomputed by a stream processor and read in the same lookup: included above.
- Model: gradient-boosted trees with about 1,000 trees of depth 8 visit about 8,000 nodes, well under 1 ms on CPU; allow 3 ms at p99.
- Rules engine and decision: 2 ms. Logging is asynchronous.
- Total ≈ 20 ms, leaving headroom for tail latency and retries within one attempt.
2. Feature store size. Cards: 60M × 150 features × 4 B = 36 GB. Merchants: 2M × 100 × 4 B = 0.8 GB. About 37 GB, roughly 74 GB with one replica, so a small in-memory cluster.
3. Read load. 5,000 TPS × 3 lookups = 15,000 reads/s, comfortable for a few in-memory nodes.
4. Scoring compute. About 1 ms of CPU per transaction → 5,000 TPS needs 5 cores; at a 50% utilisation target, 10 cores, spread over three or more pods across availability zones.
5. Event log. 1,500 TPS × 2 KB = 3 MB/s ≈ 260 GB a day for training and audit.
6. Design consequences. Fail open to rules if the model times out; chargeback labels arrive 30–90 days later, so monitor proxy signals (decline rate, manual-review outcomes, score drift) in the meantime; blocked transactions never get labels, so keep a small randomised holdout or use review outcomes to reduce selection bias.
Stack · 5 layersLatency budget for real-time card-fraud scoring
5 ms into the service.
Card, merchant and device profiles in parallel from an in-memory store, with streaming velocity features read in the same lookup.
Gradient-boosted trees, about 1,000 trees of depth 8, about 8,000 nodes, well under 1 ms on CPU; allow 3 ms at p99.
2 ms; logging is asynchronous.
About 20 ms, leaving headroom for tail latency and retries within one attempt of the 50 ms p99 budget.
Choose a vector index for 100 million chunks
You must search 100M chunks embedded at 1,024 dimensions. Compare flat search, HNSW and IVF-PQ on memory and latency, and say when Postgres or an existing search engine is enough.
1. Raw vectors. float32: 100M × 4,096 B = 410 GB. int8 scalar quantisation: 102 GB.
2. Flat (exact) search. Each query touches every vector: 100M × 1,024 × 2 ≈ 2e11 FLOPs and reads all 410 GB. On a CPU node with about 100 GB/s memory bandwidth that is about 4 s per query. On 8 GPUs holding fp16 vectors (205 GB) each GPU reads about 26 GB at 3.35 TB/s ≈ 8 ms, and batching queries makes it efficient. Flat is right for under about 1M vectors, or as ground truth for measuring recall.
3. HNSW. Memory = vectors + graph. With M = 32, the base layer stores about 64 neighbour IDs × 4 B = 256 B per vector, about 26 GB in total. In float32 that is about 436 GB of RAM, so shard across nodes; with int8 vectors about 128 GB. Recall is high (often 95–99%) at single-digit millisecond latency, but builds take hours and deletes and updates are awkward.
4. IVF-PQ. Product quantisation with 64 sub-quantisers × 8 bits stores 64 B per vector: 6.4 GB, plus about 0.8 GB of IDs, so it fits on one machine or GPU. The number of lists grows with N: the Faiss guidelines suggest 4√N to 16√N for small sets and about 2^18 (262,144) to 2^20 (about 1M) lists around the 100M scale. Recall is lower, so rerank the top few hundred candidates with full-precision vectors fetched from SSD (300 × 4 KB = 1.2 MB per query).
5. Postgres or an existing search engine. At tens of millions of vectors with heavy metadata filtering, transactional updates and a team that already runs Postgres or OpenSearch, pgvector or the engine’s ANN support is often good enough and much simpler to operate. At 100M with tight latency, a dedicated index (or a sharded HNSW or IVF-PQ deployment) is usually justified.
6. Decision. For 100M chunks with a 100 ms retrieval budget: IVF-PQ or int8 HNSW sharded across two or three nodes, hybrid with BM25, and a cross-encoder reranker on the top 50–100. Measure recall at k against flat search on a sample.
Is this matmul compute-bound or memory-bound on an H100?
A layer multiplies activations X (B × 4,096) by weights W (4,096 × 4,096) in bf16. For which batch sizes B (tokens) is it compute-bound on an H100 (989 TFLOP/s, 3.35 TB/s)? What does that mean for decode and for elementwise operations?
1. Ridge point. 989e12 / 3.35e12 ≈ 295 FLOPs per byte.
2. FLOPs and bytes. FLOPs = 2 × B × d² with d = 4,096. Bytes (bf16) = 2 × (d² + B·d + B·d) for W, X and the output = 2d² + 4Bd.
3. Intensity. I = 2Bd² / (2d² + 4Bd) = Bd / (d + 2B).
- B = 1: I ≈ 1 FLOP/byte, about 300× below the ridge: badly memory-bound.
- B = 256: I = 256 × 4,096 / (4,096 + 512) = 228: still memory-bound.
- B = 512: I = 512 × 4,096 / (4,096 + 1,024) = 410: compute-bound.
4. Crossover. Bd / (d + 2B) = 295 → 4,096B = 295 × 4,096 + 590B → 3,506B = 1,208,320 → B ≈ 345 tokens.
5. Consequences.
- Prefill of a 2,000-token prompt is compute-bound: use FP8 or bf16 tensor cores efficiently.
- Decode with 32 sequences means B = 32: memory-bound. Batch more, quantise weights or use speculative decoding to use the idle compute.
- Elementwise operations (activation functions, residual adds, normalisation) do about one FLOP per several bytes, always memory-bound, which is why kernel fusion (for example with torch.compile) matters.
What changed recently
MCP becomes stateless (2026-07-28 specification)
The July 2026 revision of the Model Context Protocol removes protocol-level sessions and the initialise handshake: every request carries its protocol version and client capabilities, list results carry cache lifetimes, long-running work moves to a tasks extension, and servers should list tools in a deterministic order so prompt caches keep hitting. MCP servers can therefore sit behind ordinary load balancers and scale like any stateless HTTP service, with cross-call state passed as explicit handles; expect questions on putting a tool gateway in front of many MCP servers.
Code execution with MCP
Anthropic argued that loading every tool definition up front and piping intermediate results through the model wastes context, and proposed exposing MCP servers as code APIs that the agent discovers on demand and calls from a sandbox, filtering data before the model sees it; in one example token use fell from about 150,000 to 2,000. The cost is a secure sandbox with resource limits and monitoring, so interviewers ask when direct tool calls remain the better design.
Context engineering for long-running agents
Anthropic framed context as a finite attention budget whose recall degrades as it fills, and set out patterns for long-horizon agents: just-in-time retrieval through tools instead of pre-loading, compaction of old history, structured notes kept outside the window, and sub-agents that return short summaries. Agent designs are now expected to state what enters the context at each step, not just which model is used.
GPT-5 ships as a routed system
OpenAI launched GPT-5 as a fast model, a deeper reasoning model and a real-time router that picks between them from conversation type, complexity, tool needs and explicit intent, trained on signals such as model switches, preference rates and measured correctness, with mini models absorbing traffic at usage limits. Routing between cheap-fast and slow-reasoning paths is now a component candidates are expected to design and evaluate.
The economics of a production multi-agent system
Anthropic described its Research feature: a lead agent plans and spawns parallel sub-agents with their own context windows, beating a single agent by 90.2% on an internal evaluation while using about 15× the tokens of chat, with token usage explaining about 80% of performance variance on BrowseComp. Its lessons (only worth it for high-value parallel tasks, resume from checkpoints, rainbow deployments, start evaluation with about 20 queries) are now standard material for agent design rounds.
Pitfalls
- Jumping to architecture boxes before agreeing requirements, scale and the success metric.
- Estimates with no units or no peak factor, or sizing GPUs by parameter count alone and forgetting KV cache, activations and redundancy.
- Designing the model before the evaluation, and ignoring delayed, biased or censored labels.
- Choosing an autonomous agent where a fixed workflow would be cheaper, faster and easier to test, or proposing a multi-agent design without budgeting for its several-fold token cost.
- Enforcing tenant isolation or permissions in prompts instead of storage, retrieval and the tool layer (an MCP server or gateway should act with the calling user’s own permissions, not a shared super-user credential).
- Listing technologies without stating the trade-off you are making and why it suits this prompt.
How interviewers probe it
Flow · 5 stepsThe repeatable structure of an ML system design round
- Requirements Spend the first five to eight minutes on requirements: users, core flows, scale, latency and availability targets, data sensitivity and residency, budget.
- Estimates Do back-of-envelope estimates.
- API and architecture Sketch the API and data model, then draw the architecture.
- Deep dives Go deep on the two or three hardest parts, often the model, the data pipeline and serving.
- Close Close with trade-offs, failure modes and how you would evaluate and roll out.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Requirements | Spend the first five to eight minutes on requirements: users, core flows, scale, latency and availability targets, data sensitivity and residency, budget. |
| 2 | Estimates | Do back-of-envelope estimates. |
| 3 | API and architecture | Sketch the API and data model, then draw the architecture. |
| 4 | Deep dives | Go deep on the two or three hardest parts, often the model, the data pipeline and serving. |
| 5 | Close | Close with trade-offs, failure modes and how you would evaluate and roll out. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Requirements | Open | users, flows, scale, latency, budget |
| Estimates | Design | back-of-envelope |
| API and data model | Design | sketch |
| Architecture | Design | draw |
| Deep dives | Design | model, data pipeline, serving |
| Trade-offs and rollout | Close | failure modes, evaluation |
Source: This page's text
- Design a real-time fraud-scoring service; you are judged on reasoning and collaboration rather than product trivia.
- Design a model to detect policy-violating images and videos at scale, starting with evaluation.
- HNSW, IVF-PQ or flat for 100M chunks, and when is Postgres or an existing search engine enough?
- When would you build a fixed workflow rather than an agent, and when prompting, retrieval, fine-tuning or long context? When is a multi-agent design worth its token bill, and how would you manage context for a long-running agent?
- Why are GPUs fast, and how do you tell whether a kernel or model is compute-bound or memory-bound?
- Batch or online inference for this use case, and what hybrid patterns exist?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Design a service that scores card transactions for fraud in real time. You’ll be judged on reasoning and collaboration rather than product trivia.
Model answer, written in a candidate's voice
- Clarify requirements first: latency budget, throughput, availability, consistency, and what the decision is allowed to do
- Architecture: ingestion stream -> feature lookup -> scoring -> decisioning -> feedback loop
- Failure modes and fallbacks: degrade gracefully when features, model, or store are unavailable
- Bottlenecks at scale: feature lookup, inference, hot keys, and the feedback path
- ML issues: feature freshness, training/serving skew, delayed labels
- Collaborate: ask the interviewer what matters most, invite pushback, and iterate
Design a model to detect policy-violating images and videos at scale. Begin with how you would evaluate it.
Model answer, written in a candidate's voice
- Define policy classes and asymmetric error costs before choosing metrics.
- Sample eval set from real traffic, stratified, with expert labels and adjudication.
- Choose operating point by expected loss; report precision there and recall on severe classes.
- Use expert labelling with consensus, disagreement tracking, and active learning.
- Use a multimodal encoder in a cost cascade with per-stage latency budgets.
- Monitor drift and adversarial adaptation; red-team; human-review loop feeds back into labels and thresholds.
Compare HNSW, IVF-PQ and flat search for 100 million chunks. When would you use Postgres or a search engine you already run instead of a dedicated vector database?
Model answer, written in a candidate's voice
- Flat: exact linear scan, fine up to ~1M vectors, too slow/expensive at 100M
- HNSW: graph-based, high recall at low latency, memory-hungry, awkward deletes
- IVF-PQ: search nprobe clusters; PQ compresses vectors with recall loss, mitigated by rescoring
- Memory maths: 100M x 1,024 dims x 4B ~ 400GB raw, so quantise, use PQ or shard
- Filtered search: pre- vs post-filtering matters for ACLs
- Postgres/existing search engine when scale is moderate and joins, transactions and existing ops matter
- Tune efSearch/nprobe against measured recall and latency, not defaults
You have finished this topic.
Reading
- The System Design PrimerGeneral distributed-systems building blocks, back-of-envelope method and latency numbers.
- Building effective agents (Anthropic)When to use workflows versus agents, with the common workflow patterns named.
- Building A Generative AI Platform (Chip Huyen)A step-by-step reference architecture: context, guardrails, router and gateway, caches, actions, observability.
- Effective context engineering for AI agents (Anthropic)What goes into an agent’s context at each step: just-in-time retrieval, compaction, notes outside the window and sub-agents.
- How we built our multi-agent research system (Anthropic)A production orchestrator-worker agent with its token economics, evaluation approach and reliability lessons.
- How we built it: Stripe RadarA real fraud-scoring system with its latency budget, features and model evolution.
- All About Rooflines (How To Scale Your Model, part 1)Rigorous roofline analysis for accelerators, the basis of GPU capacity estimates.
- Guidelines to choose an index (Faiss wiki)A decision tree for vector indexes by dataset size, memory and exactness.
Practise this topic
- Design a service that scores card transactions for fraud in real time. You’ll be judged on reasoning and collaboration rather than product trivia.
- Design a model to detect policy-violating images and videos at scale. Begin with how you would evaluate it.
- Compare HNSW, IVF-PQ and flat search for 100 million chunks. When would you use Postgres or a search engine you already run instead of a dedicated vector database?
- When would you build a fixed LLM workflow (chain, router) rather than an autonomous agent loop? Give one example of each for a product you could build here.
- A product team wants the assistant to “know” 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and fine-tuning — and when would you not use retrieval at all?
- When do you use prompting, retrieval, fine-tuning or an agentic design? Give examples.
- Design, and partly code, a single-GPU inference service that batches incoming requests up to a maximum batch size while each caller waits synchronously for its own result. How do you trade latency against throughput?
- When would you serve predictions in batch vs online? What hybrid patterns exist?
- Explain why GPUs accelerate deep learning, and how you decide whether a kernel or model is compute-bound or memory-bound.
- How would you use implicit user feedback (clicks, edits, thumbs) to improve a recommendation or assistant model, and what biases does that feedback carry?
- For a phone-based voice agent, break down end-to-end response latency and explain how you’d get the median under a second while keeping interruptions rare.
- Sketch the ML and systems pipeline for generating a talking-avatar video from a script, and where LLMs fit.
- For a UK bank’s phone line, compare a cascaded ASR–LLM–TTS voice agent, a single speech-to-speech model, and a full-duplex voice front end that delegates reasoning and tools to a backend model (as in OpenAI’s GPT-Live, 2026). Which would you ship, and where do turn-taking, tool calls, grounding and audit live in each?
- Your company wants to let internal agents use third-party MCP servers through a central gateway. The 2026-07-28 MCP specification made the protocol stateless and deprecated dynamic client registration. Design the gateway’s security controls and say which threats each addresses.
- Design a tool gateway that lets internal agents use about 200 MCP servers (CRM, ticketing, code search, data warehouse) on behalf of 5,000 employees. Cover authentication and permissions, scaling, prompt-injection containment and the context cost of so many tools.
- A product team wants an orchestrator–worker multi-agent ‘deep research’ feature. Given published figures that multi-agent systems use around 15 times the tokens of a chat turn, how would you decide whether it is worth building, and which levers would you use to control cost and latency?
- GPT-5 shipped as a fast model, a deeper reasoning model and a real-time router between them. Design and evaluate a similar router for your own assistant, which today sends every request to an expensive reasoning model.
- Your team retrieves candidates for a 50-million-item video catalogue with a two-tower model and ANN search. A research group proposes replacing it with generative retrieval over semantic IDs, as YouTube (PLUM) and Spotify (GLIDE) have deployed. How would you build the semantic IDs, serve the model within the retrieval latency budget, and decide whether to ship it?
- Meta trains one LLM-scale ads foundation model (GEM) but serves hundreds of smaller vertical models under tight latency budgets. Design the knowledge-transfer path from a large recommendation foundation model to a production ranker, and explain how you would know the transfer is actually working.