14B.7 Interview Prep II: LLM System Design
The LLM system-design round is not a disguised distributed-systems exam. It is a structured conversation in which you have to show that you can turn a fuzzy product request into a measurable, buildable, operable system. A strong answer starts before architecture: clarify the users and constraints, decide what "good" means, estimate whether the workload is even feasible, then choose the simplest design that can hit the quality, cost, latency and safety bars. This lesson gives you a repeatable 45-minute framework, the estimation maths behind it, ten worked LLM designs, two production diagnoses, a mock-interview practice system and the trade-off vocabulary interviewers listen for.
What you'll learn
- What LLM system-design interviews assess, and how they differ from classic system-design interviews
- A 45-minute framework you can run on a whiteboard, with a diagram, checklist and time allocation
- Back-of-envelope estimation for tokens, requests, concurrency, cost, latency, cache effects, storage and vector-index memory
- Ten complete worked designs: support RAG with actions, permission-aware enterprise document Q&A, a coding assistant, document extraction, a realtime voice agent, a citation-heavy answer engine, moderation at scale, a multi-agent research assistant, a text-to-SQL analytics assistant and an internal LLM gateway
- How to diagnose degraded production systems from traces, and how to design an evaluation system
- Decision tables for the recurring trade-offs: RAG vs fine-tuning, workflow vs agent, sync vs async, managed vs self-hosted, build vs buy, precision vs recall and autonomy vs risk
- A
career_kit/design_calc.pycalculator and a fill-incareer_kit/design_template.md - Mock-interview scripts, a scoring rubric, common pitfalls and staff-level considerations
What you don't need
- API keys or provider accounts. The calculator and templates are pure Python and markdown; every model-dependent example is labelled illustrative.
- Deep model internals. This lesson assumes you know what tokens, context, embeddings, tool calling, streaming, structured output, RAG, agents, evals and observability are. Those lessons own the depth; this lesson teaches how to present and defend the design.
- A finished portfolio. You can practise the framework on fictional products, then reuse it on your own projects.
Setup
The only code in this lesson is a standard-library Python calculator, so it needs no packages and no API keys. Create a small project and save the file as career_kit/design_calc.py:
uv init career-kit --bare --python 3.13
cd career-kit
mkdir -p career_kitIf uv is new, lesson 03.1, Part 4 explains project setup. You can also use python3 career_kit/design_calc.py directly; there is nothing to install. The design_template.md file is a markdown template you copy into notes or a whiteboard document.
What you must be able to do after this lesson#
- Explain what an LLM system-design round assesses
- Run the 45-minute framework with a diagram, checklist and time allocation
- Estimate tokens, requests, concurrency, cost and latency with back-of-envelope math
- Justify a trade-off such as RAG versus fine-tuning using the reusable template
- Diagnose a degraded system from traces and design an eval system for it
Why this matters for an AI engineer#
LLM system-design interviews reward a different kind of clarity from classic web-system design. Both test requirements, scale and trade-offs, but LLM systems add a second quality problem: the output can be fluent and still be wrong, unsafe, stale, expensive or impossible to reproduce. You have to design for measurement as well as uptime.
| You'll hear... | You'll understand it after... |
|---|---|
| "Design a support assistant." | Part 5: Worked designs I and Part 6: Worked designs II |
| "How much will this cost per month?" | Part 3: The back-of-envelope toolkit and design_calc.py |
| "How do we know it's good enough?" | Part 2: The 45-minute framework and the eval-design section |
| "Should we use RAG or fine-tune?" | RAG vs fine-tuning vs prompting vs workflow and 13A.8 |
| "Why not just make it an agent?" | Workflow vs agent and 08A.9 |
| "How do you stop prompt injection?" | Step 6: quality, safety and security and 12.2 |
| "What changes at 100x scale?" | 2.8 Follow-ups and scale questions |
| "This system got worse after a model update." | Part 7: Diagnosing degraded systems and 11C.4 |
Part 1: What the round actually assesses#
1.1 The shape of the round#
An LLM system-design interview usually gives you a product prompt such as "design a customer-support copilot" or "design a document Q&A system for a bank". You then have roughly 45 minutes to clarify, sketch, estimate, deep-dive and close. The interviewer is watching for five things at once:
| Signal | What it looks like |
|---|---|
| Structured thinking | You separate requirements, architecture, quality, cost, safety and rollout instead of drawing boxes immediately |
| Requirements gathering | You ask who uses it, what a wrong answer costs, what data exists, what latency is acceptable and what is out of scope |
| Trade-off judgement | You choose among real alternatives and explain what you give up |
| LLM-specific awareness | You discuss non-determinism, evals, grounding, prompt injection, model churn, context limits and cost per request |
| Communication | You narrate your reasoning, check assumptions, recover from uncertainty and invite correction |
1.2 Shared with classic system design#
Classic system-design interviews still matter. You should be comfortable with:
- Scale: users, requests per second, storage growth and concurrency
- APIs and service boundaries: what is synchronous, what is queued, what is a worker
- Data stores: Postgres for transactional state, object storage for files, vector indexes for retrieval, caches for repeated work
- Reliability: timeouts, retries, idempotency, graceful degradation and observability
- Security: authentication, authorisation, tenant isolation and secrets
The difference is that an LLM call is not a normal API call. It is expensive, non-deterministic, sensitive to prompt and context, capable of producing fluent wrong answers, and sometimes the slowest stage by an order of magnitude. You cannot hide it behind a generic "service" box.
1.3 New in LLM system design#
The new questions are the ones that make the round distinctive:
| New concern | Why it matters |
|---|---|
| Quality measurement | "It works" is meaningless until you define an eval set, metrics and regression gates |
| Grounding and citations | Retrieval can reduce hallucination, but only if answers are tied to evidence and verified |
| Prompt and context engineering | The prompt is code: versioned, tested, budgeted and reviewed |
| Model selection and churn | Model IDs, prices, limits, behaviour and deprecations change; design for portability and pinning |
| Cost per request | Token usage, retries, long contexts and reasoning tokens can dominate unit economics |
| Safety and prompt injection | Retrieved documents, tool outputs and user text can carry instructions; tools need least privilege |
| Latency composition | Retrieval, reranking, generation, streaming and tool calls add up; users feel time-to-first-token, not just total latency |
| Abstention and human handoff | Knowing when not to answer is a product feature |
1.4 The mistake candidates make first#
The weakest answers jump straight to "use RAG and an agent". The strongest answers start by asking what decision the system supports, what a wrong answer costs, what evidence exists, how success will be measured and whether a non-LLM component should handle part of the job. LLM system design is as much product judgement as architecture.
Part 2: The 45-minute framework#
2.1 The eight moves#
Use the same sequence every time. The order matters: you cannot choose retrieval, tools, model tier or guardrails until you know the users, risk, scale and definition of success.
flowchart TD
A["1. Clarify<br/>users, task, constraints, risk"] --> B["2. Define success<br/>evals and online metrics"]
B --> C["3. Estimate<br/>load, tokens, latency, cost"]
C --> D["4. High-level architecture<br/>request path and data stores"]
D --> E["5. Deep dives<br/>retrieval, orchestration, model, cache, tools"]
E --> F["6. Quality, safety, security<br/>evals, injection, permissions, PII"]
F --> G["7. Reliability and rollout<br/>observability, fallbacks, canary, kill switch"]
G --> H["8. Trade-offs and evolution<br/>what you would cut, change at 100x"]A practical time split for a 45-minute round is:
| Time | Move | What you should produce |
|---|---|---|
| 0–5 min | Clarify | Users, task, constraints, non-goals, risk tier |
| 5–10 min | Success | Quality bar, eval plan, online metrics, abstention rule |
| 10–15 min | Estimate | Requests/day, tokens/request, QPS, concurrency, monthly cost, storage |
| 15–22 min | Architecture | Request path, offline ingestion, data stores, trust boundaries |
| 22–32 min | Deep dives | Two or three chosen areas, driven by the prompt and your estimates |
| 32–38 min | Quality and safety | Eval gates, citations, injection defences, permissions, PII, human review |
| 38–43 min | Reliability and rollout | Tracing, SLOs, fallbacks, cost caps, canary, rollback, kill switch |
| 43–45 min | Trade-offs | What you would simplify, what changes at 10x or 100x, open questions |
2.2 Step 1: clarify before you design#
Ask the smallest set of questions that changes the architecture. Do not ask twenty questions; ask the ones with architectural consequences.
| Question | Why it changes the design |
|---|---|
| Who uses it, and are they authenticated? | Determines identity, tenancy, permissions and audit requirements |
| Is the user internal staff or the public? | Public systems need stronger abuse controls, rate limits and moderation |
| What is the task: answer, draft, extract, classify, act or decide? | Determines output contract, autonomy level and human review |
| What does a wrong answer cost? | Low-cost drafting can stream freely; refunds, medical, legal or security answers need verification and escalation |
| What data can the system see? | Determines RAG corpus, permissions, PII handling and provider data policy |
| What latency matters? | Chat may need streaming; batch extraction can be async |
| What volume and growth should we plan for? | Determines concurrency, caching, queues, index size and cost |
| What is explicitly out of scope? | Prevents gold-plating and shows product judgement |
The "autonomy level" in the table above is the same axis 13A.1, Part 5 calls the assist / draft / act / decide tier: it decides what the system may do unsupervised versus what it must draft, confirm or escalate. State the tier explicitly in your answer — "this is a draft-tier feature, so a human sends every message" — because it determines your tool permissions, your eval metrics and your rollout gates.
2.3 Step 2: define success before architecture#
"The LLM gives good answers" is not a success metric. Convert the product goal into measurable claims:
| Product goal | Offline eval | Online signal | Guardrail |
|---|---|---|---|
| Answer support questions correctly | Faithfulness, answer correctness, citation precision on a labelled ticket set | Thumbs up/down, escalation rate, repeat contact rate | Unanswerable questions must abstain or hand off |
| Extract invoice fields | Field-level accuracy, schema validity, semantic checks | Human correction rate, downstream exception rate | Low-confidence fields go to review |
| Draft replies for agents | Tone rubric, policy compliance, factual support | Edit distance, acceptance rate, handle time | No sending without review for regulated actions |
| Classify content | Precision/recall per class on a stratified set | Appeal rate, overturn rate, queue volume | High-severity categories get conservative thresholds |
Link the depth to Module 10A: 10A.1 for turning goals into metrics, 10A.2 for datasets and labelling, and 10A.9 for A/B tests, shadow mode and canaries. For how experiments are designed and read on LLM features specifically — what to randomise, minimum detectable effects and the AI-specific traps — see 13A.6, Part 4.
2.4 Step 3: estimate before drawing details#
Do rough arithmetic early because it changes the design. A system with 100 requests/day can use a synchronous simple pipeline; the same system at 100 requests/second needs queues, caching, concurrency limits and probably a routing strategy.
The minimum estimates are:
- Requests per day and peak QPS
- Input and output tokens per request, including retrieved context and retries
- Model calls per user request (one, two, or an agent loop of many)
- Concurrency from arrival rate and latency
- Monthly model cost from token prices
- Data growth for documents, vectors, logs and traces
- Latency budget for retrieval, generation, tools and UX
Part 3 gives the formulas and a calculator. In the interview, say the assumptions behind every number: "I am assuming 20,000 support conversations per day, 1.2 model calls per conversation, 6,000 input tokens including retrieved docs and 700 output tokens. At peak I use 4x average." Order-of-magnitude honesty beats false precision.
2.5 Step 4: draw the high-level architecture#
Draw the request path first, then the offline path. A typical LLM application has two halves:
flowchart LR
subgraph online ["Online request path"]
U["User or client"] --> API["API / auth / rate limit"]
API --> ORCH["Orchestrator<br/>prompt, retrieval, tools, model call"]
ORCH --> LLM["Model provider or gateway"]
ORCH --> STORE[("Transactional store<br/>conversations, jobs, audit")]
LLM --> OUT["Validated response<br/>streamed or structured"]
end
subgraph offline ["Offline ingestion path"]
DOCS["Documents / tickets / data"] --> PARSE["Parse, clean, chunk, metadata"]
PARSE --> EMB["Embed and index"]
EMB --> VDB[("Vector index / search")]
DOCS --> EVAL["Eval sets and golden data"]
end
VDB -.-> ORCH
EVAL -.-> ORCH13A.5 owns the layered product architecture; 07.1 owns the RAG pipeline; 08A.9 owns the workflow/agent distinction.
When you draw, use consistent shapes:
- Rectangles for services and components
- Cylinders or database symbols for stores and indexes
- Arrows labelled with data or control flow, not every dependency
- A dashed trust boundary around untrusted inputs: user text, uploaded files, web pages, retrieved chunks and tool outputs
- Small numbered stages if you need to explain order
2.6 Step 5: choose the deep dives#
Do not try to cover everything equally. Pick the two or three areas where the prompt and your estimates create real risk.
| If the system has... | Deep-dive here |
|---|---|
| Private documents or citations | Retrieval, permissions, grounding, citation verification |
| Tools that change state | Tool design, least privilege, approvals, idempotency, audit |
| Long-running or ambiguous tasks | Workflow vs agent, budgets, checkpoints, trajectory evals |
| Realtime interaction | Audio architecture, turn-taking, latency budget, interruption handling |
| Multimodal input (images, PDFs, audio) | Modality choice, context-cost multiplier, provider coverage and fallback |
| Personalisation, memory or long-running context | Memory stores, summarisation strategy, privacy and consent, staleness |
| High volume or cost pressure | Model routing, caching, batching, context size, self-hosting |
| Regulated or high-stakes decisions | Human review, policy-as-code, data governance, incident response |
2.7 Step 6: quality, safety and security#
Every design needs a short but explicit safety pass:
- Input: authentication, rate limits, prompt-injection assumptions, PII detection and minimisation
- Retrieval: ACL filters inside the query, tenant isolation, document scanning and freshness
- Model: structured outputs where possible, bounded autonomy, no secrets in prompts, model/provider data policy
- Output: schema validation, citation checks, output PII/secret scanning, safe rendering and logging redaction
- Actions: least privilege, approvals for irreversible or high-impact tools, audit logs and rollback where possible
The depth lives in Module 12: 12.1 for threat modelling, 12.2 for architectural defences, 12.4 for leak paths, 12.5 for output validation, and 12.9 for high-risk domains.
2.8 Follow-ups and scale questions#
Interviewers often ask what changes at 10x or 100x. Have a repeatable answer:
- What breaks first? Usually cost, latency, rate limits, index freshness or eval coverage.
- What do you cache or precompute? Exact responses, retrieval results, embeddings, document summaries or classifier verdicts.
- What moves async? Ingestion, evals, reports, non-urgent notifications and long-running agent tasks.
- What gets routed? Easy queries to a cheaper model, hard queries to a stronger model, sensitive queries to a compliant route.
- What gets sharded or partitioned? Vector index by tenant or collection, queues by feature, model gateways by region.
- What must not be compromised? Permissions, auditability, safety gates and eval regression coverage.
If you do not know a vendor feature, say so and reason from first principles: "I would check whether the provider supports the needed modality, data-retention terms, structured output and rate limits before choosing it. I would not design around an unverified capability." That is a stronger answer than inventing an API.
Part 3: The back-of-envelope toolkit#
3.1 The numbers you need first#
Estimation is not about being exact. It is about discovering which constraint dominates. A support chatbot might be latency-bound; a document extractor might be cost-bound; a voice agent might be concurrency-bound; a RAG system might be retrieval-quality-bound.
Start with product numbers, not architecture:
| Input | Example assumption | What it drives |
|---|---|---|
| Users or requests per day | 20,000 conversations/day | QPS, queues, cost, index freshness |
| Requests per user session | 4 turns | Token growth, memory, session store |
| Peak-to-average ratio | 3x for B2B, 5x for consumer launches | Concurrency, rate limits, autoscaling |
| Context per request | 2,000 tokens instructions + 8,000 retrieved/history | Input cost, TTFT, context limit |
| Output per request | 500 tokens answer, or 2,000 for reasoning/extraction | Output cost, latency, truncation risk |
| Model calls per request | 1 for simple answer, 3-8 for agent | Cost multiplication and error compounding |
| Corpus size | 50,000 documents, 2M chunks | Index memory, ingestion time, freshness |
3.2 Load and concurrency#
Convert daily volume to average and peak request rates:
requests_per_second = requests_per_day / 86,400
peak_qps = average_qps * peak_factorThen use Little's law: the average number of requests in flight is arrival rate multiplied by average time in system. If a service sees 10 requests/second and each request takes 4 seconds, about 40 requests are concurrently in progress. For capacity planning, use a conservative latency estimate and add headroom.
01B.4 owns bounded concurrency, worker pools, queues and rate limiting; this lesson only uses the arithmetic.
3.3 Token and cost estimation#
For a first estimate, use the provider's tokenizer when precision matters. For a whiteboard estimate, English prose is often roughly 3.5–4.5 characters per token, but the ratio varies by language, code, JSON and model tokenizer. 02.2 owns tokenisation and 03.7 owns token counting, price tables and caching mechanics.
The cost shape is:
cost_per_model_call =
(uncached_input_tokens / 1,000,000) * input_price
+ (cached_input_tokens / 1,000,000) * cached_input_price
+ (output_tokens / 1,000,000) * output_price
cost_per_user_request = model_calls_per_request * cost_per_model_call
+ retrieval/embedding/tool/guardrail cost per request
monthly_cost = requests_per_month * cost_per_user_requestRemember that output tokens are usually the expensive side, reasoning tokens count as output, retries multiply cost, and schema descriptions are input tokens sent on every call. The exact provider mechanics are in 03.7 and 02.9.
3.4 Latency budget#
Split latency into stages before choosing streaming or async:
| Stage | Typical planning question |
|---|---|
| Auth, validation, rate limit | Can this be under 50 ms? |
| Retrieval | Hybrid search + rerank: tens to hundreds of ms, plus index size |
| Prompt assembly | How many tokens are added, and is the prefix cache-friendly? |
| Model time to first token | Is the model fast enough for chat, or should output stream? |
| Generation time | Output tokens × decode speed; reasoning can dominate |
| Tool calls | Each tool adds a round trip; long tools may need async status |
| Validation and guardrails | Cheap schema checks vs classifier calls |
A chat UI should optimise time to first useful token, not just total completion time. Batch extraction should optimise throughput and cost, not first-token latency. 13A.2 owns perceived-latency UX.
3.5 Retrieval and index sizing#
For a vector index, start with:
raw_vector_bytes = vectors * dimensions * bytes_per_value
index_memory ≈ raw_vector_bytes * overhead_factorThe overhead factor covers graph links, IVF lists, metadata, quantisation tables and allocator overhead. A good interview answer gives a range, not a fake exact number. 06.4 owns index types and quantisation; 06.4 Part 8 owns scale regimes.
Also estimate:
- Chunks per document and tokens per chunk
- Embedding calls during ingestion and re-embedding after model changes
- Index freshness lag: how long until a new or corrected document is searchable
- Filter cardinality: tenant, permission, language, document type and date filters affect index choice
3.6 Caching and freshness#
Caching can reduce cost and latency, but the cache key must include everything that changes the answer: user permissions, tenant, document versions, prompt version, model ID, retrieval corpus version and feature flags. A wrong cache hit can leak data or serve stale policy.
11B.3 owns the cache layers; 03.7 and its provider sections own prompt caching. In an interview, mention at least three cache levels: exact response, retrieval result, and provider prompt-prefix cache.
Hit rate is what turns caching from a diagram box into a number. Effective input cost per call is roughly hit_rate × cached_price + (1 − hit_rate) × full_price, so a 70% hit rate on input cached at a tenth of the full price cuts that input line by roughly 60% (0.7 × 0.1 + 0.3 × 1.0 = 0.37 of the full price). Estimate the hit rate honestly: it depends on how repetitive the workload is, how stable the prompt prefix is and the cache TTL — not on the cache existing. Long stable prefixes (system instructions, tool definitions, a fixed corpus preamble) are where provider prompt-prefix caching earns its keep; 02.7, Part 7 owns the mechanics. Give a range in the interview — "30–70%, depending on the share of repeat questions" — rather than one invented figure, and say which cache level produces it. In design_calc.py, cached_input_tokens_per_call is the per-call token count you expect to hit; multiply it by your assumed hit rate before passing it in.
3.7 Storage growth#
Do not forget non-model storage:
- Conversation and job records
- Uploaded documents and generated files
- Vector index and metadata
- Traces, eval results, logs and feedback
- Audit records for actions and approvals
A useful rule is to estimate growth per month and per tenant, then state retention. "We keep raw traces for 30 days, aggregated metrics for 13 months and audit events for seven years" is the kind of answer that sounds like production experience — but verify your employer's actual policy before quoting it as fact.
3.8 career_kit/design_calc.py#
Save this as career_kit/design_calc.py. It is deliberately small: the point is to make assumptions explicit and reusable in an interview or design doc.
"""Back-of-envelope calculator for LLM system-design interviews.
Pure standard library. Prices are USD per 1M tokens and are illustrative
parameters, not current provider prices: check the official pricing pages
before relying on a real budget.
"""
from __future__ import annotations
from dataclasses import dataclass
SECONDS_PER_DAY = 86_400
DAYS_PER_MONTH = 30.0
@dataclass(frozen=True)
class Scenario:
"""One workload estimate.
input_tokens_per_call and output_tokens_per_call are per MODEL call.
model_calls_per_request lets an agent or multi-stage pipeline charge
several calls for one user-visible request.
"""
name: str
requests_per_day: float
peak_factor: float = 3.0
model_calls_per_request: float = 1.0
input_tokens_per_call: int = 6_000
output_tokens_per_call: int = 700
input_price_per_mtok: float = 0.10
output_price_per_mtok: float = 0.50
cached_input_tokens_per_call: int = 0
cached_input_price_per_mtok: float | None = None
other_cost_per_request: float = 0.0
avg_latency_seconds: float = 4.0
vectors: int = 0
dimensions: int = 0
bytes_per_value: float = 4.0
index_overhead: float = 1.5
def requests_per_second(requests_per_day: float, peak_factor: float = 1.0) -> float:
"""Convert daily volume to average or peak request rate."""
return requests_per_day / SECONDS_PER_DAY * peak_factor
def monthly_requests(requests_per_day: float) -> float:
return requests_per_day * DAYS_PER_MONTH
def token_cost_usd(
input_tokens: int,
output_tokens: int,
input_price_per_mtok: float,
output_price_per_mtok: float,
cached_input_tokens: int = 0,
cached_input_price_per_mtok: float | None = None,
) -> float:
"""Cost of one model call, with cached input priced separately."""
cached = min(max(cached_input_tokens, 0), input_tokens)
uncached = input_tokens - cached
cached_price = input_price_per_mtok if cached_input_price_per_mtok is None else cached_input_price_per_mtok
return (
uncached / 1_000_000 * input_price_per_mtok
+ cached / 1_000_000 * cached_price
+ output_tokens / 1_000_000 * output_price_per_mtok
)
def monthly_cost_usd(scenario: Scenario) -> float:
"""Monthly model plus non-model cost for a scenario."""
per_request = (
scenario.model_calls_per_request
* token_cost_usd(
scenario.input_tokens_per_call,
scenario.output_tokens_per_call,
scenario.input_price_per_mtok,
scenario.output_price_per_mtok,
scenario.cached_input_tokens_per_call,
scenario.cached_input_price_per_mtok,
)
+ scenario.other_cost_per_request
)
return monthly_requests(scenario.requests_per_day) * per_request
def concurrent_requests(arrival_rate_per_second: float, avg_latency_seconds: float) -> float:
"""Little's law: average number of requests in flight."""
return arrival_rate_per_second * avg_latency_seconds
def index_memory_mb(
vectors: int,
dimensions: int,
bytes_per_value: float = 4.0,
overhead: float = 1.5,
) -> float:
"""Rough vector-index memory, including graph/list/metadata overhead."""
raw_bytes = vectors * dimensions * bytes_per_value
return raw_bytes * overhead / 1_000_000
def summarize(scenario: Scenario) -> None:
avg_qps = requests_per_second(scenario.requests_per_day)
peak_qps = requests_per_second(scenario.requests_per_day, scenario.peak_factor)
in_flight = concurrent_requests(peak_qps, scenario.avg_latency_seconds)
cost = monthly_cost_usd(scenario)
index_mb = index_memory_mb(
scenario.vectors,
scenario.dimensions,
scenario.bytes_per_value,
scenario.index_overhead,
)
print(f"{scenario.name}")
print(f" volume: {scenario.requests_per_day:,.0f}/day "
f"({monthly_requests(scenario.requests_per_day):,.0f}/month)")
print(f" rate: avg {avg_qps:.3f} QPS, peak {peak_qps:.3f} QPS "
f"({scenario.peak_factor:g}x)")
print(f" concurrency: ~{in_flight:.1f} requests in flight at "
f"{scenario.avg_latency_seconds:g}s average latency")
print(f" model cost: ~${cost:,.2f}/month "
f"({scenario.model_calls_per_request:g} calls/request, "
f"{scenario.input_tokens_per_call:,}+{scenario.output_tokens_per_call:,} tokens/call)")
if scenario.vectors and scenario.dimensions:
print(f" vector index: ~{index_mb:,.0f} MB for {scenario.vectors:,} x "
f"{scenario.dimensions}-dim vectors at {scenario.bytes_per_value:g} bytes/value")
else:
print(" vector index: not estimated")
print()
def main() -> None:
scenarios = [
Scenario(
name="Support assistant",
requests_per_day=20_000,
peak_factor=4.0,
model_calls_per_request=1.2,
input_tokens_per_call=6_000,
output_tokens_per_call=700,
input_price_per_mtok=0.10,
output_price_per_mtok=0.50,
cached_input_tokens_per_call=2_000,
cached_input_price_per_mtok=0.01,
other_cost_per_request=0.002,
avg_latency_seconds=5.0,
vectors=500_000,
dimensions=1_536,
),
Scenario(
name="Enterprise document Q&A",
requests_per_day=2_000,
peak_factor=3.0,
model_calls_per_request=1.5,
input_tokens_per_call=14_000,
output_tokens_per_call=900,
input_price_per_mtok=0.30,
output_price_per_mtok=1.50,
cached_input_tokens_per_call=5_000,
cached_input_price_per_mtok=0.03,
other_cost_per_request=0.01,
avg_latency_seconds=9.0,
vectors=2_000_000,
dimensions=3_072,
bytes_per_value=2.0,
index_overhead=1.8,
),
Scenario(
name="Invoice extraction pipeline",
requests_per_day=100_000,
peak_factor=2.5,
model_calls_per_request=1.8,
input_tokens_per_call=5_500,
output_tokens_per_call=1_400,
input_price_per_mtok=0.15,
output_price_per_mtok=0.60,
cached_input_tokens_per_call=0,
other_cost_per_request=0.001,
avg_latency_seconds=12.0,
vectors=0,
dimensions=0,
),
]
for scenario in scenarios:
summarize(scenario)
if __name__ == "__main__":
main()Support assistant
volume: 20,000/day (600,000/month)
rate: avg 0.231 QPS, peak 0.926 QPS (4x)
concurrency: ~4.6 requests in flight at 5s average latency
model cost: ~$1,754.40/month (1.2 calls/request, 6,000+700 tokens/call)
vector index: ~4,608 MB for 500,000 x 1536-dim vectors at 4 bytes/value
Enterprise document Q&A
volume: 2,000/day (60,000/month)
rate: avg 0.023 QPS, peak 0.069 QPS (3x)
concurrency: ~0.6 requests in flight at 9s average latency
model cost: ~$978.00/month (1.5 calls/request, 14,000+900 tokens/call)
vector index: ~22,118 MB for 2,000,000 x 3072-dim vectors at 2 bytes/value
Invoice extraction pipeline
volume: 100,000/day (3,000,000/month)
rate: avg 1.157 QPS, peak 2.894 QPS (2.5x)
concurrency: ~34.7 requests in flight at 12s average latency
model cost: ~$11,991.00/month (1.8 calls/request, 5,500+1,400 tokens/call)
vector index: not estimatedThe prices above are illustrative parameters chosen to make the arithmetic easy to inspect; they are not a quote. Replace them with values from the providers' current pricing pages, then add non-model costs before treating the result as a budget.
3.9 What the calculator deliberately omits#
The calculator gives a planning range, not a finance forecast. It does not model provider rate limits, prompt-cache hit rates over time, batch discounts, regional uplifts, retries, guardrail calls, embedding costs, vector-database hosting, human review labour or engineering time. In a real design doc, list those separately and link the measurement plan to 11A.2 and 11B.1.
Part 4: Trade-off vocabulary and the reusable template#
4.1 The decision tables interviewers expect#
The best answers do not list technologies; they choose among alternatives and name the cost of the choice. Keep these tables in your head and adapt them to the prompt.
Model size vs latency vs cost
| Choice | Use when | Cost of choosing it |
|---|---|---|
| Small/fast model | High volume, simple classification, extraction, routing, short answers | May miss nuance, tool reliability or long-context reasoning |
| Mid-tier model | Default product workhorse for chat, drafting and grounded Q&A | Still needs evals; may be too slow for realtime voice |
| Large/reasoning model | Hard multi-step problems, high-stakes drafting, complex extraction | Higher latency and output-token cost; may overthink simple asks |
| Routed cascade | Mixed workload where a cheap model handles easy cases and a strong model handles hard ones | More moving parts, routing evals and per-model prompt variants |
02.9 owns model choice and 11B.5 owns routing patterns. Current model IDs and prices are volatile: verify on the official pages and say "as of November 2026" if you quote them.
RAG vs fine-tuning vs prompting vs workflow
| Symptom | First choice | Why |
|---|---|---|
| Model lacks current/private facts | RAG or tools | Facts change; retrieval is fresher and auditable |
| Style, format or narrow task is consistently wrong | Prompt/template first, then fine-tune only if evals prove it | Prompting is cheap and reversible; fine-tuning is slower and needs data |
| Output must follow a strict shape | Structured output plus validation | Constrained decoding improves format, not truth |
| Process has fixed steps | Workflow | Deterministic steps are cheaper and easier to test than an agent loop |
| Steps depend on intermediate results | Agent or hybrid | The model chooses tools, but still needs budgets and verification |
13A.8 owns this decision in depth; 07.1 gives the RAG-specific version.
Workflow vs agent
| Use a workflow when | Use an agent when |
|---|---|
| Steps are known and testable | The next step depends on model judgement |
| Reliability and auditability dominate | Open-ended exploration is the product |
| You can verify each stage | You can bound cost, tools and termination |
| Latency budget is tight | Users accept longer, supervised runs |
08A.9 owns the full framework and 08A.10 owns agent patterns.
Sync vs async
| Work | Shape | Reason |
|---|---|---|
| Chat answer, extraction preview, interactive draft | Sync/streaming | User is waiting and latency is visible |
| Bulk ingestion, nightly evals, report generation | Async queue/worker | Throughput matters more than immediate response |
| Long-running agent with tools | Async job plus status events | Work may take minutes and must survive retries |
| Payment, refund, deletion or other irreversible action | Sync confirmation plus durable audit | Human approval and idempotency matter more than speed |
Managed vs self-hosted vs gateway
| Route | Use when | Watch out for |
|---|---|---|
| Direct provider API | Fastest path, managed features, simple deployment | Provider-specific behaviour and data terms |
| Gateway/router | Multi-provider resilience, cost controls, central policy | Another service to operate and secure |
| Managed open-model host | Open weights with less GPU work | Less control over versions, hardware and privacy |
| Self-hosted open weights | Data residency, high volume, custom hardware, licence fit | You own capacity, upgrades, monitoring and evals |
11C.6 owns the serving decision; 11C.3 owns gateways and fallbacks.
Build vs buy
| Build when | Buy/use managed when |
|---|---|
| The capability is the differentiator | The capability is commodity infrastructure |
| You need unusual data controls or latency | The vendor's evals, compliance and uptime beat your team |
| You have engineering capacity to maintain it | Time-to-market and operational risk dominate |
| You can measure and improve it | The vendor can absorb model churn for you |
Precision vs recall, freshness vs cost
| Trade-off | Lean precision when | Lean recall when |
|---|---|---|
| Retrieval/classification | False positives are costly or noisy | Missing a relevant document is worse |
| Caching | Stale answers are dangerous | Repeated identical questions dominate volume |
| Guardrails | Over-blocking destroys UX | Harmful or irreversible outputs are unacceptable |
| Abstention | A wrong confident answer damages trust | Coverage matters more than perfect precision |
Autonomy vs risk
"How much can the system do without a human?" is one of the most common follow-ups, and the answer is a ladder, not a yes/no. Pick the lowest tier that meets the product need and justify every step up.
| Autonomy level | What the system may do | Required control | What to say in the interview |
|---|---|---|---|
| Read-only answer | Stream a grounded answer with citations | Schema validation, citation checks, abstention | "The blast radius is a wrong sentence, so I optimise for grounding and a graceful 'I don't know'." |
| Draft for a human | Produce text a person edits, sends or approves | Edit-distance/acceptance metrics, policy checks, full logging | "The human is the approval step; I measure acceptance rate and edit distance, not just fluency." |
| Reversible action | Look up data, create a draft ticket, update a non-critical field | Idempotency keys, audit log, rollback or compensating action | "These actions are reversible, so I require idempotency and an audit trail but not per-action approval." |
| Irreversible or high-impact action | Issue refunds, delete data, send external communications, change permissions | Deterministic policy checks, explicit human approval, reason codes | "This is the decide tier: the model may recommend, but only a human or a rules engine can execute." |
The tiers map to the assist / draft / act / decide ladder in 13A.1, Part 5; the controls column is where Module 12 and the autonomy-dial and human-in-the-loop patterns of 13A.3, Part 4 plug in.
4.2 career_kit/design_template.md#
Save this as career_kit/design_template.md and fill it in for every mock design. It mirrors the 45-minute framework so your answer has a spine even when the prompt changes.
# LLM system design: <product name>
## 1. Problem and users
- Users:
- Task:
- Wrong-answer cost:
- Constraints:
- Non-goals:
- Risk tier / autonomy:
## 2. Success and measurement
- Offline eval set:
- Metrics:
- Online signals:
- Guardrails / abstention:
- Launch gate:
## 3. Estimates
- Requests/day, peak QPS:
- Tokens per call / calls per request:
- Concurrency:
- Monthly model and non-model cost:
- Storage and index growth:
- Latency budget:
## 4. Architecture
- Online path:
- Offline path:
- Data stores:
- Trust boundaries:
- Mermaid diagram:
## 5. Deep dives
- Retrieval / orchestration / model routing / caching / tools / multimodal:
## 6. Quality, safety and security
- Input controls:
- Retrieval permissions:
- Output validation:
- Prompt-injection assumptions:
- PII/secrets:
- Human review:
## 7. Reliability and rollout
- Tracing/SLOs:
- Fallbacks and degraded mode:
- Cost caps:
- Canary / rollback / kill switch:
## 8. Trade-offs and evolution
- What I would cut first:
- What changes at 10x:
- What changes at 100x:
- Open questions:Part 5: Worked designs I: support RAG, enterprise Q&A, code and extraction#
Deep-dive
These are model answers, not product commitments. The names, volumes and prices are illustrative. In an interview, replace them with the interviewer's constraints and keep the reasoning shape.
5.1 Customer-support assistant with RAG and actions#
Requirements. Authenticated customers ask about orders, refunds, subscriptions and policies. The assistant can answer, draft a reply for an agent, look up order status through a tool, and request a refund only after policy checks and human approval. Wrong refund promises are high-cost; wrong policy summaries are medium-cost.
Estimates. Assume 20,000 conversations/day, 4x peak, 1.2 model calls per conversation, 6,000 input and 700 output tokens per call. The calculator gives about 0.23 average QPS, 0.93 peak QPS, ~5 requests in flight at 5 seconds and ~$1,754/month model cost before guardrails and tools. Retrieval adds embedding, vector-store and reranker costs.
flowchart LR
U["Customer"] --> WEB["Support UI"]
WEB --> API["API: auth, quota, session"]
API --> INTENT["Intent and risk router"]
INTENT --> RET["ACL-filtered retrieval"]
RET --> VDB[("Policy/docs index")]
INTENT --> CTX["Context assembly"]
VDB --> CTX
CTX --> LLM["Answer model"]
LLM --> VAL["Schema + citation + policy checks"]
VAL --> ACTION{Action needed?}
ACTION -->|"lookup"| TOOL["Order/status tool"]
ACTION -->|"refund"| APPROVAL["Human approval queue"]
ACTION -->|"answer only"| STREAM["Stream answer + sources"]
TOOL --> LLM
APPROVAL --> OUT["Audited outcome"]
STREAM --> OUTTrade-offs. Use a workflow for known intents and reserve agentic behaviour for ambiguous cases. Retrieval improves grounding but adds latency and permission complexity. Streaming improves perceived latency but complicates citation rendering and action confirmation. Human approval reduces autonomy but is mandatory for refunds.
Evaluation plan. Build a labelled set from historical tickets: answerable, unanswerable, policy-change, refund-request, injection-in-document and multi-turn cases. Measure answer correctness, faithfulness to retrieved policy, citation precision, abstention accuracy, action-policy violations and approval latency. Online, track escalation rate, repeat contact, refund reversal rate and cost per resolved ticket.
Failure modes. Stale policy chunks, tenant leakage through cache or retrieval filters, indirect prompt injection in help articles, model inventing order status, refund tool called without approval, citation that does not support the claim.
Model answer outline. "I would start with authenticated support conversations and a policy corpus. I would route simple FAQs to retrieval plus a fast model, order lookups to a read-only tool, and refund requests to a deterministic policy check plus human approval. Answers stream with citations, but actions never execute from model text alone. I would evaluate faithfulness, citation precision, abstention and action safety offline, then watch escalation and cost online."
Follow-ups. "At 10x, I would shard indexes by tenant and cache stable policy prefixes. At 100x, I would consider a model cascade and async eval batches. If citations are wrong, I would check retrieval recall before blaming the generator. If costs spike, I would inspect retry rate, context size and agent-loop length first."
Depth links. 07.1, 07.2, 07.4, 07.5, 07.9, 07.11, 08A.14.
5.2 Enterprise document Q&A with permissions#
Requirements. Employees ask questions over HR, legal, finance and product documentation. Every user has groups and document ACLs. Answers need citations and an audit trail. The corpus may contain sensitive policy and personnel documents; PII must be minimised in logs.
Estimates. Assume 2,000 questions/day, 3x peak, 1.5 model calls per question because a query rewrite or sufficiency check may run first. With 14,000 input and 900 output tokens per call, the illustrative monthly model cost is ~$978 before embeddings and index hosting. A 2M-vector, 3,072-dimensional index at 2 bytes/value with 1.8 overhead is roughly 22 GB, so index memory is a real design input.
flowchart LR
U["Employee"] --> SSO["SSO / groups"]
SSO --> API["Q&A API"]
API --> ACL["Principal -> permission scope"]
API --> QW["Query rewrite / expansion"]
QW --> RET["Hybrid retrieval + ACL filter"]
RET --> VDB[("Document chunks + ACL metadata")]
RET --> RR["Rerank top candidates"]
RR --> GEN["Grounded answer + citations"]
GEN --> CHECK["Citation and policy validation"]
CHECK --> AUDIT[("Audit log")]
CHECK --> UI["Answer UI"]Trade-offs. Filter permissions inside retrieval, never after generation. Hybrid search helps exact policy phrases and semantic questions, but adds operational complexity. A managed vector service is faster to launch; self-hosting may be required for data residency. Cache keys must include user scope, document versions and prompt/model versions.
Evaluation plan. Include permission-leakage tests where a user asks for documents they cannot see, superseded-policy questions, cross-language queries, citation-support checks and abstention cases. Measure recall@k before generation, citation precision, answer correctness and ACL violation count. The ACL violation count should be zero before launch.
Failure modes. Metadata missing or wrong on chunks, cache key omits tenant/group, reranker promotes an unauthorised chunk, model answers from parametric memory instead of evidence, citations point to the wrong section.
Model answer outline. "I would treat document permissions as part of retrieval, not as a post-filter. The principal's groups become a mandatory metadata filter in every vector and keyword query. I would use hybrid retrieval, rerank a small candidate set, generate with strict citation requirements, and log the document versions used. Evals would include adversarial ACL cases because one leak is worse than many wrong answers."
Follow-ups. "Freshness comes from document versioning and incremental indexing. If a user sees stale policy, I check ingestion lag and supersession metadata first. At 100x, I would partition indexes by tenant or collection and move evals to a scheduled offline pipeline."
Depth links. 07.2, 07.11, 06.6, 12.4.
5.3 Code-review or coding assistant#
Requirements. Developers ask questions about a repository, request explanations, propose patches and run tests. The system must not execute arbitrary commands without sandboxing. Secrets and customer data may exist in repos, so context selection and logging need care.
Estimates. Assume 30,000 developer requests/day, 2x peak, two model calls per request on average because a planner or verifier may run, 12,000 input tokens and 1,500 output tokens per call. This is roughly 0.35 average QPS and 0.69 at peak; at ~16 seconds per request — two sequential ~8-second model calls plus overhead — Little's law gives ~6 requests in flight on average and ~11 at peak. (Counting model calls rather than requests gives the same figure: twice the call rate at half the per-call latency.) Model cost is highly sensitive to context size, so token packing matters more than model price.
flowchart LR
DEV["Developer"] --> IDE["IDE / CLI / PR comment"]
IDE --> API["Assistant API"]
API --> REPO["Repo map, search, file reader"]
REPO --> PACK["Context packer<br/>symbols, diffs, tests"]
PACK --> LLM["Coding model"]
LLM --> PATCH["Patch / explanation / test plan"]
PATCH --> VALID["Schema + policy checks"]
VALID --> SANDBOX["Sandboxed test runner"]
SANDBOX --> PR["PR draft or answer"]
PR --> DEVTrade-offs. Use a workflow for explain-and-patch tasks; add an agent only when exploration is open-ended. Repository maps and search reduce context cost but can miss semantic relationships. A coding-agent CLI may be useful internally, but production review features need deterministic policy checks and sandboxing. Never give the model unrestricted shell access.
Evaluation plan. Use real or sanitised repo tasks: bug localisation, patch correctness, test pass rate, explanation grounded in files, secret leakage in context/logs and unsafe command attempts. Measure pass@k for patch tasks and trajectory cost. Regression-test on known vulnerable or misleading repository comments.
Failure modes. Context packer omits the relevant file, model edits the wrong module, generated patch breaks tests, repository comments contain prompt injection, logs contain secrets, agent loops until budget exhaustion.
Model answer outline. "I would start with read-only repository tools: search, file read, symbol outline and test runner. The model proposes patches; deterministic checks and tests decide whether they are acceptable. For open-ended exploration I might use an agent loop, but with a strict step and token budget. Sandboxing and secret scanning are part of the architecture, not an afterthought."
Follow-ups. "At scale I would cache repository embeddings and invalidate on commit. If latency is high, I would reduce context before upgrading the model. If quality drops after a model update, I would replay the eval suite and compare patch pass rate and cost per solved task."
Depth links. 08A.15, 08A.15, 08A.10, 12.2.
5.4 Document-processing and extraction pipeline#
Requirements. Customers upload invoices, contracts or forms. The system classifies the document, extracts fields into a strict schema, validates business rules and routes low-confidence results to human review. It is asynchronous and must handle malformed files, scanned pages and partially legible text.
Estimates. Use the calculator's extraction scenario: 100,000 documents/day, 1.8 model calls per document, 5,500 input and 1,400 output tokens per call gives ~2.9 peak QPS, ~35 requests in flight at 12 seconds and ~$11,991/month illustrative model cost. Add OCR, storage and review labour.
flowchart LR
UP["Upload / email / API"] --> SCAN["Malware + type + PII scan"]
SCAN --> PARSE["Parse / OCR / layout"]
PARSE --> CLASSIFY["Document classifier"]
CLASSIFY --> EXTRACT["Schema-constrained extraction"]
EXTRACT --> VALIDATE["Schema + semantic + business checks"]
VALIDATE -->|"confident"| POST["Post to ledger / CRM"]
VALIDATE -->|"uncertain"| REVIEW["Human review queue"]
REVIEW --> POST
VALIDATE --> AUDIT[("Audit + trace store")]Trade-offs. Async batch is better than synchronous chat because users can wait minutes but not hours. A strict schema improves format reliability but not correctness; semantic validators and grounding checks catch plausible-but-wrong values. A deterministic parser should handle clean structured PDFs before an LLM is used. Human review is a feature, not a failure, for high-cost fields.
Evaluation plan. Build a labelled set per document type with field-level expected values, ambiguous scans, missing fields, adversarial text and table-heavy layouts. Measure field accuracy, schema validity, review rate, correction effort and downstream exception rate. Track cost per successfully posted document, not cost per model call.
Failure modes. OCR loses table structure, model hallucinates a total, schema-valid but semantically inconsistent line items, PII leaks into traces, retry loop burns budget on an unreadable file, human reviewers receive too many low-value cases.
Model answer outline. "I would treat extraction as an async pipeline: scan and parse first, classify the layout, extract into a strict schema, then validate with field rules and source grounding. Low-confidence or business-rule failures go to review. I would evaluate field-level accuracy and review burden, and I would cap retries and token budgets per document."
Follow-ups. "At 10x I would shard queues by document type and add batch APIs where latency allows. At 100x I would consider specialised OCR/layout models for the hardest classes while keeping the LLM for ambiguous fields. If cost spikes, I would check retry rate, page count and whether scans are being sent as images unnecessarily."
Depth links. 03.4, 03.4, 05, 10A.1.
Part 6: Worked designs II: voice, search, moderation and agents#
Deep-dive
6.1 Realtime voice support agent#
Requirements. Customers speak to a support agent that can answer FAQs, look up order status and transfer to a human. It must handle interruptions, noisy audio, accents and tool latency without making the caller wait in silence.
Estimates. Assume 5,000 voice sessions/day, average 3 minutes each. This is not QPS-bound in the usual sense; it is concurrent-session-bound. Little's law gives the average: 5,000 sessions/day is ~0.058 sessions/second, and at 180 seconds each that is ~10 sessions in flight on average, or ~42 at a 4x peak. (A figure like 200 simultaneous sessions would need roughly 20x the volume or much longer calls, so check that a stated peak and the daily volume agree.) With 1.5 model calls per turn, cost depends heavily on audio minutes, input transcription tokens and output speech tokens. Use a per-minute cost model before promising unit economics.
flowchart LR
Caller["Caller audio"] --> Edge["WebRTC / telephony edge"]
Edge --> VAD["VAD / turn detection"]
VAD --> STT["Speech-to-text"]
STT --> Brain["Voice orchestrator + tools"]
Brain --> LLM["Reasoning/answer model"]
LLM --> TTS["Text-to-speech"]
TTS --> Caller
Brain --> Human["Human handoff"]Trade-offs. A speech-to-speech realtime model reduces pipeline complexity but may limit provider choice and tool control. A cascaded STT → LLM → TTS pipeline is easier to evaluate and swap, but has more latency seams. Full-duplex models handle interruption naturally; cascaded systems need explicit barge-in handling. Tools must be fast or asynchronous with filler speech.
Evaluation plan. Measure task success, interruption recovery, entity capture accuracy, tool-call correctness, latency per turn, cost per minute and escalation rate. Use scripted audio fixtures plus real consenting callers in shadow mode. Do not optimise only for transcript quality.
Failure modes. Misheard order IDs, model talks over caller, tool lookup exceeds turn budget, sensitive data spoken aloud, hallucinated policy, failure to hand off angry callers.
Model answer outline. "I would choose the voice architecture by latency and control requirements. If the provider's realtime API meets tool and data requirements, I would use it; otherwise I would cascade STT, a text reasoning layer and TTS. Every turn has a latency budget, tools have timeouts, and high-risk requests hand off to a human."
Follow-ups. "At 10x I would shard sessions by region and add fallback providers. At 100x I would separate realtime media from the reasoning backend so model upgrades do not rewrite the audio path. If latency regresses, I check VAD, STT finalisation, model TTFT and TTS first."
Depth links. 09.7, 09.7, 09.10, 09.10.
6.2 Search or answer engine with citations#
Requirements. Users search a public or licensed corpus and receive direct answers with citations. Answers must distinguish evidence from model knowledge, handle conflicting sources and abstain when the corpus does not support a claim.
Estimates. Assume 50,000 searches/day, 3x peak, one query rewrite plus one answer call on average. With 8,000 input and 600 output tokens per model call, model cost is meaningful but retrieval freshness and citation quality matter more. Index size depends on corpus chunks; estimate vectors × dimensions × bytes plus overhead.
flowchart LR
Q["Search query"] --> RW["Query rewrite / filters"]
RW --> RET["Hybrid retrieval"]
RET --> RR["Rerank + diversity"]
RR --> GEN["Answer with citations"]
GEN --> VER["Citation verification"]
VER --> UI["Results + source panel"]
RET --> IDX[("Document index")]Trade-offs. Hybrid retrieval beats vector-only for exact names, codes and rare phrases. Reranking improves precision but adds latency and cost. Post-hoc citations are easier but less faithful; provider-native citations may help but still need verification. Public search needs abuse controls and content licensing clarity.
Evaluation plan. Measure retrieval recall@k, citation precision/recall, answer correctness, unsupported-claim rate and abstention accuracy. Include adversarial queries, conflicting documents, near-duplicate pages and freshness cases. Track zero-result rate and reformulation rate.
Failure modes. Retrieval returns popular but irrelevant pages, model cites a source that does not support the claim, conflicting documents are silently averaged, stale index serves superseded information, answer leaks prompt or corpus metadata.
Model answer outline. "I would build retrieval first: hybrid search, metadata filters, reranking and citation verification. The answer model sees only the selected passages plus strict instructions to cite and abstain. I would evaluate retrieval separately from generation so I know whether failures come from recall, ranking or the model."
Follow-ups. "At 10x I would cache popular query results with short TTLs and partition indexes by domain or freshness. At 100x I would add query intent routing and possibly multiple indexes by content type. If citations degrade, I inspect whether the evidence reached the prompt before changing the prompt."
Depth links. 07.5, 07.9, 06.8, 06.9.
6.3 Content-moderation or classification pipeline at scale#
Requirements. User-generated text, images or reports are classified for policy violations, spam, fraud signals or escalation. The system must be high-throughput, low-latency enough for upload flows, and auditable for appeals.
Estimates. Assume 1M items/day, 2 model calls per item only for uncertain cases; most items should be handled by deterministic rules or a small classifier. Peak QPS is ~12 average and ~30 at 2.5x. Cost depends on what fraction reaches the LLM; design for a small expensive tail, not every item.
flowchart LR
IN["Content upload"] --> RULES["Deterministic rules / hashes"]
RULES -->|"clear"| PASS["Publish / allow"]
RULES -->|"uncertain"| CLS["Classifier / guard model"]
CLS --> LLM["LLM judge for edge cases"]
LLM --> DECIDE{Decision}
DECIDE -->|"allow"| PASS
DECIDE -->|"review"| QUEUE["Human review"]
DECIDE -->|"block"| BLOCK["Block + reason code"]
QUEUE --> AUDIT[("Audit log")]
BLOCK --> AUDITTrade-offs. Precision and recall are policy choices, not universal truths. High-recall screening with human review is safer but expensive; high-precision auto-blocking is cheaper but can harm users. LLM judges are flexible but costly and need calibration; deterministic rules should handle obvious cases first.
Evaluation plan. Build a stratified labelled set by category, language, source and adversarial evasion. Measure precision/recall per class, false-positive appeal rate, latency percentiles and cost per moderated item. Run red-team evasion cases and monitor distribution drift.
Failure modes. Adversarial text bypasses filters, model over-blocks dialect or minority language, reviewer queue floods, decision reasons are inconsistent, appeal overturn rate is high, PII in moderation logs.
Model answer outline. "I would use a cascade: deterministic rules first, a fast classifier second, and an LLM judge only for uncertain or high-severity cases. Decisions carry reason codes and enter an appeal-aware audit log. I would tune thresholds by harm and cost, not by a single accuracy number."
Follow-ups. "At 10x I would batch uncertain items and shard queues by category. At 100x I would consider specialised moderation models or regional policy engines. If false positives rise, I inspect class balance, prompt changes and reviewer disagreement before loosening thresholds."
Depth links. 12.5, 12.5, 10A.1, 09.10.
6.4 Multi-agent research assistant or proactive recommendation feature#
Requirements. A research assistant plans a query, fans out searches, reads sources, synthesises a cited report and may suggest follow-up tasks. Alternatively, a recommendation-style feature proactively drafts actions from user context. Multi-agent adds coordination cost; use it only when the task truly benefits.
Estimates. Assume 10,000 research runs/day, average 6 model calls per run because planner, workers, verifier and writer each call a model. This is ~60,000 model calls/day before retries — about 0.12 runs/second on average and ~0.5 at a 4x peak. If a run takes 60 seconds, Little's law (arrival_rate × time_in_system) gives ~7 runs in flight on average and ~28 at peak: tens, not hundreds. Reaching hundreds of concurrent runs needs either far higher volume (100,000+ runs/day) or much longer runs (10+ minutes); size the worker pool and budgets for the stated assumption, not the headline.
flowchart LR
U["User request"] --> PLAN["Planner agent"]
PLAN --> ORCH["Orchestrator"]
ORCH --> W1["Search worker"]
ORCH --> W2["Read/summarise worker"]
ORCH --> W3["Data/tool worker"]
W1 --> SYN["Synthesiser"]
W2 --> SYN
W3 --> SYN
SYN --> VERIFY["Citation + claim verifier"]
VERIFY --> REPORT["Report / recommendation"]Trade-offs. Multi-agent systems can parallelise research but multiply cost, latency variance and debugging surface. A workflow with fixed stages is easier to evaluate. If you use agents, isolate contexts, bound budgets, log trajectories and verify claims. Proactive features need stricter consent, relevance and suppression controls.
Evaluation plan. Measure task completion, citation support, factual errors, cost per completed run, step count, timeout rate and user acceptance. For recommendations, measure precision of suggestions, dismissal rate, opt-out rate and downstream harm. Evaluate trajectories, not only final text.
Failure modes. Agents loop or duplicate work, one worker poisons shared state, synthesiser cites a source never retrieved, cost runaway, stale memory produces irrelevant proactive suggestions, user did not consent to background processing.
Model answer outline. "I would start with the simplest orchestration that meets the task: probably a planner plus parallel search workers and a verifier. I would only add peer agents if evals show a benefit. Every run has a step budget, token budget and deadline; the final report must cite retrieved evidence and distinguish sources from inference."
Follow-ups. "At 10x I would cache source retrieval and use cheaper models for extraction. At 100x I would shard research jobs and add domain-specific workers. If quality drops, I inspect whether the planner over-decomposed the task or the verifier became a bottleneck."
Depth links. 08D.3, 08D.3, 08A.14, 13A.1.
6.5 Text-to-SQL analytics assistant#
Requirements. Business users ask questions in plain language ("what was refund volume by region last quarter?") over a warehouse they cannot query themselves. The assistant writes a query, runs it, and explains the result with the query and its assumptions visible. The data contains revenue and customer information, so access follows each user's existing data permissions. A wrong number in a board deck is high-cost; a clarifying question is cheap.
Estimates. Assume 3,000 questions/day, 3x peak, 2.5 model calls per question (pick tables and columns, write SQL, then explain the rows, with some repair retries), 5,000 input tokens per call because schema descriptions and sample values dominate, and 600 output tokens. With the illustrative prices of the calculator's enterprise scenario and 0.3 cents of non-model query cost per question, design_calc.py gives ~0.035 average QPS, ~0.10 at peak, ~1.2 requests in flight at 12 seconds and ~$810/month. The bill is small; the constraints that dominate are correctness, warehouse load and data access.
flowchart LR
U["Analyst or manager"] --> API["Assistant API<br/>auth, user scope"]
API --> CLAR["Clarify ambiguous terms<br/>or ask the user"]
CLAR --> SCHEMA["Schema retrieval<br/>tables, columns, metric definitions"]
SCHEMA --> GEN["Model writes SQL"]
GEN --> CHECK["Parse + policy check<br/>SELECT only, allow-listed tables,<br/>row and cost limits"]
CHECK -->|"rejected"| REPAIR["Error back to model<br/>bounded retries"]
REPAIR --> GEN
CHECK -->|"approved"| RUN["Read-only replica or warehouse role<br/>statement timeout"]
RUN --> ROWS[("Result rows")]
ROWS --> EXPL["Model explains rows<br/>with the SQL and assumptions shown"]
EXPL --> UI["Answer + query + chart"]
RUN --> AUDIT[("Audit log: user, SQL, rows read")]Trade-offs. A semantic layer (curated metric definitions such as "refund volume" and approved join paths) usually beats asking the model to infer business meaning from raw column names, but someone has to maintain it. Giving the model the whole schema is simple and costs tokens; retrieving the relevant tables first is cheaper and scales to large warehouses but can miss a needed table. Letting the model run any query is flexible and dangerous; a validated, read-only, allow-listed path is safer and rejects some legitimate questions. Showing the SQL builds trust for technical users and is noise for others, so make it expandable. The model proposes the query; your code decides whether it may run (07.8, Part 7 works the safe pattern).
Evaluation plan. Build a labelled set of question, reference SQL and reference result, covering ambiguous terms, joins, time windows, fiscal calendars, NULL handling, empty results and questions the data cannot answer. Compare execution results, not SQL text, because many different queries are correct. Add slices for permission boundaries (a user asking about tables they cannot see), for expensive queries, and for questions that should trigger a clarification instead of a guess. Online, track query error rate, repair rate, user corrections, "show me the SQL" rate and disagreement with certified dashboards.
Failure modes. A plausible query that answers a slightly different question (wrong fiscal year, wrong join grain, double-counted rows), silently dropping rows through an inner join, stale or undocumented columns, runaway scans that hurt the warehouse, a prompt-injected string in a data value steering the model, result rows with PII in logs, and a confident explanation of an empty result.
Model answer outline. "I would not let the model touch the database. It writes SQL; my code parses it, checks it against a read-only allow-list, adds limits and a timeout, and runs it under the user's own permissions. I would put metric definitions in a semantic layer, show the SQL and assumptions, and ask a clarifying question when a term is ambiguous. I would evaluate on execution results with permission and ambiguity slices, and track cost per correct answer."
Follow-ups. "At 10x I would cache schema retrieval and identical query results with a short TTL keyed on user scope and data freshness. At 100x I would add per-team query budgets and queue heavy questions. If answers disagree with a certified dashboard, I compare the query's grain and filters before touching the prompt."
Depth links. 07.8, Part 7, 07.2, 4.2, 12.6, 10A.3.
6.6 Internal LLM gateway for a platform team#
Requirements. A platform team serves about 40 internal applications that all call model providers. Today each app holds its own keys, retries differently and has no shared view of cost. The platform must give every app one stable API, central keys, per-team budgets and rate limits, fallbacks across providers, logging with redaction, and policy such as which data classes may go to which provider. It must not become the outage that takes every app down.
Estimates. Assume 5,000,000 model calls/day across all apps, 4x peak, 3,000 input and 400 output tokens per call and 6 seconds average latency. The calculator gives ~58 calls/second on average, ~231 at peak and ~1,390 calls in flight at peak by Little's law. Illustrative model spend is ~$103,500/month at $0.15 input and $0.60 output per million tokens (the invoice scenario's example prices). The gateway adds no model cost of its own; its design problem is holding thousands of open streaming connections, adding as little latency as possible, and protecting the shared provider rate limits.
flowchart LR
subgraph apps ["Internal applications"]
A1["App A"] & A2["App B"] & A3["Agent workers"]
end
apps --> GW["Gateway<br/>auth, quota, policy,<br/>routing, retries, cache"]
GW --> POL["Policy engine<br/>data class to allowed route"]
GW --> P1["Provider 1"]
GW --> P2["Provider 2"]
GW --> OSS["Self-hosted open models"]
GW --> LOG[("Logs and usage<br/>redacted, per team")]
LOG --> DASH["Cost and quality dashboards"]
GW --> KILL["Kill switch and<br/>per-team circuit breakers"]Trade-offs. One hop for everyone centralises keys, budgets and policy but adds latency and a shared dependency, so the gateway must be stateless, horizontally scaled and have a documented bypass for emergencies. A shared fallback chain improves availability but can silently route sensitive data to a provider it should not reach, so fallbacks follow the data-class policy, not just price. Gateway-level caching saves money for exact repeats but needs a cache key that includes the tenant, prompt version and model. A hosted or open-source gateway product gets you to production faster than building, but you take on its risks and release cadence; the thin self-built option suits two to four providers (11C.3, Part 9 compares them, as of November 2026).
Evaluation plan. The gateway is infrastructure, so the plan mixes reliability and quality. Measure added latency (p50 and p99 against calling the provider directly), availability by provider, fallback rate and whether fallback answers stay within quality bounds on a shared eval set per route. Test failure injection (provider 429s, slow responses, partial streams), budget enforcement under burst, policy tests (a restricted data class must never reach a disallowed route) and log-redaction tests.
Failure modes. The gateway becomes a single point of failure; retries from many apps amplify a provider outage into a retry storm; one team exhausts a shared provider quota; a model alias is moved and quality shifts for every app at once; logs capture prompts with PII; a fallback silently changes behaviour for structured-output or tool-calling apps because the second provider handles schemas differently.
Model answer outline. "I would start with the policy and failure model: who may call what, what happens when a provider is down, and what must never leave a boundary. The gateway is a stateless, autoscaled proxy with per-team keys, budgets and rate limits, health-checked routing with bounded retries and jittered back-off, circuit breakers per provider, and redacted logs. Model upgrades go through a pinned version and a canary per app with a shared eval set. I would also keep a documented bypass and a kill switch."
Follow-ups. "At 10x I would shard by region or team and move heavy logging off the request path. At 100x I would separate the control plane (config, keys, budgets) from the data plane (the proxy), and add provider-side quota planning. If one app's quality drops after a gateway change, I check route changes, alias resolution and fallback rate for that app first."
Depth links. 11C.3, Part 9, 11B.5, 11C.4, 12.4.
Part 7: Diagnosing degraded systems and designing evals#
Deep-dive
7.1 The diagnosis method#
When an interviewer gives you a degraded system, do not start by "switching to a better model". Treat it like an incident:
- Reproduce one failing trace. Ask for the request ID, prompt version, model ID, retrieved document IDs, tool calls and final output.
- Attribute the stage. Was the input parsed correctly? Did retrieval return the right evidence? Did the prompt contain it? Did the model ignore it? Did validation reject a good answer? Did a tool return bad data?
- Compare with a baseline. Use the last known-good prompt, model, index and config on the same input.
- Check what changed. Model alias, prompt version, retrieval corpus, permissions, cache, schema, rate limits and traffic mix can all change silently.
- Measure before fixing. A fix without an eval is a guess; a fix with a regression set is engineering.
07.10 owns RAG debugging, and 11A.1 owns trace-based debugging. In an interview, narrate this sequence explicitly.
7.2 Worked diagnosis: citations became wrong after a deployment#
Symptoms. A support RAG assistant started citing the wrong policy sections after a prompt and retrieval deploy. User complaints rose; automated citation checks flagged unsupported claims; latency and cost were unchanged.
Likely causes, in order.
| Suspect | Evidence to check | Why it fits |
|---|---|---|
| Retrieval regression | Recall@k and top-k document IDs before/after | Deploy changed chunking, metadata, embedding model or ACL filter |
| Context assembly regression | Passage order and token budget in traces | New prompt placed retrieved text after a long instruction block or truncated it |
| Prompt regression | Prompt version diff and citation instruction | Instruction now permits paraphrase without quote support |
| Citation verifier regression | Verification rules and threshold | Stricter/looser verifier changed what counts as supported |
| Model/provider change | Model ID and alias resolution | Alias moved to a different snapshot with different citation behaviour |
Strong answer. "I would freeze the failing trace and replay it against the previous retrieval index, prompt and model. If the old stack cites correctly and the new stack does not, I bisect the deploy: first retrieval output, then context assembly, then prompt, then model. I would not patch the prompt until I know whether the evidence ever reached the model. Once fixed, I would add the failing case to the eval set and a CI regression gate."
7.3 Worked diagnosis: extraction cost and latency doubled#
Symptoms. An invoice pipeline's p95 latency rose from seconds to minutes and monthly model spend doubled. Error rate stayed low because retries eventually succeeded.
Likely causes.
- A model update made structured output stricter, so more calls end
invalidand retry. - A schema change added fields or descriptions, increasing input tokens on every call.
- Reasoning effort or output budget increased, so each call generates more tokens.
- A fallback cascade now tries a stronger model after the cheap model fails validation.
- OCR or document parsing started sending page images instead of text, increasing multimodal input cost.
Strong answer. "I would segment traces by document type and failure outcome. If invalid_after_retries rose, I would compare schema versions and provider finish reasons. If token usage rose without more retries, I would inspect input size, image payloads and reasoning tokens. I would then A/B the previous model/config on the eval set and roll back the smallest component that restores quality within budget. Cost per successfully extracted document is the metric, not cost per call."
7.4 Design-the-eval-system question#
A common follow-up is "how would you evaluate this system?" A strong answer covers four layers:
| Layer | What it answers | Example artefacts |
|---|---|---|
| Offline eval | Does the current version meet the quality bar before release? | Labelled cases, golden answers, field-level metrics, judge calibration |
| Regression CI | Did this change make anything worse? | Fixed eval subset, score thresholds, cost/latency budgets |
| Online eval | Is production quality drifting? | Sampled judge scores, user feedback, assertion monitors, canaries |
| Incident feedback | Did a real failure become a permanent test? | Production failure -> sanitised eval case -> regression test |
Link to 10A.1, 10A.2 and 10A.9. The interview answer should mention dataset ownership, labelling, judge calibration, slices, confidence intervals and the rule that evals are versioned with prompts and models.
Part 8: Pitfalls, mock practice and staff-level depth#
Reference
8.1 Mistakes gallery#
| Weak answer | Strong answer |
|---|---|
| "We will use RAG and an agent." | "I would first decide whether retrieval is needed, whether the process is fixed enough for a workflow, and what a wrong answer costs." |
| "The LLM will be accurate because it is a frontier model." | "I would define an eval set, measure faithfulness and correctness, and set an abstention threshold before launch." |
| "We will add guardrails later." | "I would put least-privilege tools, ACL filters, output validation and audit logging into the first architecture." |
| "Cost is just the API price." | "I would estimate tokens per call, calls per request, retries, cache hit rate, guardrails, embeddings and human review." |
| "We will use a vector database." | "I would choose retrieval based on corpus size, filter needs, freshness and whether hybrid search beats vector-only on evals." |
| "The model can handle permissions in the prompt." | "Permissions are enforced in code and retrieval filters; the prompt is not a security boundary." |
| "We will fine-tune for better answers." | "I would try prompting, retrieval and structured output first; fine-tuning only if evals show a durable gap." |
| "Agents are more advanced, so we should use them." | "I would use the simplest reliable pattern; agents only where the next step genuinely depends on model judgement." |
| "We will stream everything." | "I would stream user-facing chat, but use async jobs for long-running or batch work and validate final outputs." |
| "We will monitor errors." | "I would monitor quality metrics, cost per task, latency percentiles, eval drift and safety signals, not only HTTP errors." |
8.2 The pitfalls to name explicitly#
- Jumping to architecture before requirements
- Ignoring evals or saying "we will test it manually"
- Vague answers like "we will use a better model" or "we will add guardrails"
- Forgetting abstention, human handoff or escalation
- Ignoring indirect prompt injection through documents, tools and web pages
- No cost estimate, or counting only the user's message
- Gold-plating with agents, vector databases or microservices the prompt did not need
- Not discussing failure modes, degraded modes or rollback
- Over-claiming accuracy without a dataset and metric
- Framework name-dropping without explaining why it fits
- Treating model output as trusted input to tools, SQL, shell or rendering
- Forgetting data retention, provider data policy, PII in logs and tenant isolation
8.3 Mock-interview practice#
Use a peer or a timer and run the same prompt twice: once aloud for 45 minutes, once written in the template. After each run, score independently:
| Area | 0 | 1 | 2 |
|---|---|---|---|
| Requirements | Did not clarify | Asked generic questions | Asked questions that changed architecture |
| Structure | Jumped to boxes | Followed a loose sequence | Used the eight-step framework and time allocation |
| Estimates | No numbers | One or two guesses | Explicit assumptions, QPS, tokens, cost, concurrency |
| Depth | Surface-level | One deep dive | Two or three relevant deep dives with trade-offs |
| Evaluation | No eval plan | Mentioned tests | Dataset, metrics, online signals and CI gate |
| Safety | Ignored | Generic guardrails | Permissions, injection, PII, output validation, human review |
| Communication | Silent or rambling | Some narration | Clear reasoning, assumptions, recovery and follow-up answers |
Peer script. "I will give you 45 minutes. Interrupt me only if I am silent for more than 90 seconds or clearly off-track. Score me on requirements, estimates, architecture, evals, safety and communication. At the end, tell me the three weakest moments and one thing you would have asked."
Self-recording review. Watch for long silences, unanswered clarifying questions, diagrams with no data flow, numbers without assumptions, and missing "what breaks at 10x". Keep a log of recurring weaknesses; practise those first.
8.4 Staff-level extras#
When the role is senior, add one paragraph on operational maturity:
- Rollout: shadow mode, canary cohort, eval gates, feature flags and rollback plan
- Governance: model inventory, prompt versions, data classification and approval for high-risk uses
- Multi-tenancy: tenant isolation in retrieval, caches, logs and model routing
- Vendor risk: provider deprecation, regional outage, pricing change and export/exit plan
- Platform vs product: whether this capability belongs in a shared LLM platform or a product-specific service
11C.4 owns operating concerns; 12.9 owns governance.
8.5 Fresher and switcher tracks#
| Track | What to emphasise |
|---|---|
| Fresher | Show learning velocity: run the calculator, fill the template, explain trade-offs simply, link portfolio projects to evals and failure analysis |
| Switcher | Translate prior experience: distributed systems -> queues and concurrency; data engineering -> ingestion and metadata; QA -> evals and regression; security -> threat modelling and guardrails |
8.6 What to do this week#
- Run
career_kit/design_calc.pyon one fictional scenario and change three assumptions. - Fill
career_kit/design_template.mdfor a support assistant in 30 minutes. - Do one timed 45-minute mock design and score it with the rubric.
- Pick one worked design and rewrite its architecture without looking.
- Write a one-page "eval plan" for the same design: dataset, metrics, CI gate and online signals.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "LLM system design is just classic system design with a model API." | LLM calls add non-determinism, quality measurement, grounding, cost per token, prompt injection and model churn. |
| "A bigger model solves quality problems." | Better prompts, retrieval, schemas, evals and routing often matter more; bigger models can cost more and still fail. |
| "RAG eliminates hallucination." | RAG grounds answers in evidence, but retrieval can miss, cite badly or leak permissions; verification is still required. |
| "Agents are the advanced choice." | Workflows are often more reliable, cheaper and easier to evaluate; agents are for genuinely open-ended steps. |
| "Streaming solves latency." | Streaming improves perceived latency but does not make retrieval, tools or validation faster; budget each stage. |
| "Cost is an afterthought." | Token usage, retries, context size, reasoning tokens and review labour can dominate unit economics. |
| "Guardrails are just output filters." | Strong guardrails include permissions, least-privilege tools, ACL-aware retrieval, audit logs and human approval. |
| "You can say you don't know in an interview." | You can, if you convert it into assumptions, sources to check and a continued design. |
Key takeaways#
- Clarify users, task, wrong-answer cost, data, latency and scale before drawing architecture.
- Define success with offline evals, online metrics and guardrails before choosing components.
- Estimate requests, tokens, concurrency, cost, latency, storage and index size with explicit assumptions.
- Use the eight-step framework: clarify, measure, estimate, architect, deep-dive, safety, reliability, trade-offs.
- Choose the simplest reliable pattern: prompt before fine-tune, workflow before agent, deterministic checks before model judgement.
- Treat permissions, citations, prompt injection, PII and human review as architecture, not polish.
- Practise diagnosing degraded systems by stage: reproduce, attribute, compare, measure, then fix.
- Communicate assumptions and uncertainty; that is what the round assesses.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| LLM system design | Designing an application around probabilistic model calls, including retrieval, tools, evals, safety and operations |
| Risk tier | The autonomy level a feature may have based on the cost of a wrong answer |
| Eval set | A fixed collection of labelled examples used to measure quality |
| Offline eval | Evaluation run before release on a controlled dataset |
| Online eval | Evaluation from production signals such as feedback, judges, monitors and experiments |
| Regression gate | A CI or release check that blocks changes that reduce quality or exceed budgets |
| Back-of-envelope estimate | A rough calculation used to expose dominant constraints, not a precise forecast |
| Little's law | Average number in a system equals arrival rate multiplied by average time in system |
| Peak factor | Assumed ratio between peak and average traffic |
| Token budget | The planned number of input/output tokens per request or run |
| Cost per resolved task | Total model and non-model cost divided by successfully completed user tasks |
| Vector-index overhead | Extra memory beyond raw vectors for graphs, lists, metadata and quantisation |
| Retrieval-augmented generation (RAG) | Generating answers from retrieved evidence rather than model memory alone |
| ACL-aware retrieval | Filtering documents by user permissions inside the retrieval query |
| Citation verification | Checking that cited evidence actually supports the claim |
| Structured output | Model output constrained to a known schema |
| Semantic validation | Checks on meaning and business rules that a schema cannot express |
| Workflow | A fixed sequence of model and deterministic steps |
| Agent | A system where the model chooses steps/tools within a bounded loop |
| Trajectory eval | Evaluation of the steps an agent took, not only the final answer |
| Human-in-the-loop | A design where consequential actions require human approval |
| Shadow mode | Running a new system on real traffic without letting it affect users |
| Canary rollout | Releasing a change to a small cohort before broader rollout |
| Kill switch | A control that disables a feature or model path quickly |
| Model cascade | Routing easy requests to cheaper models and hard requests to stronger models |
| Prompt-injection boundary | The architectural assumption that retrieved or user text may contain hostile instructions |
| Degraded mode | A safer, simpler fallback behaviour when the full system is unavailable or too risky |
| Semantic layer | Curated business-metric definitions and approved join paths that a text-to-SQL system uses instead of guessing from raw column names |
| Execution-result evaluation | Judging generated SQL by comparing the rows it returns with a reference result, not by comparing query text |
| LLM gateway | A shared proxy between applications and model providers that centralises keys, routing, retries, budgets, logging and policy |
Exercises#
- Calculator: change the support-assistant scenario to 100,000 conversations/day and 8,000 input tokens per call. Which constraint changes first: cost, concurrency or latency? (Hint: the other inputs stay as in the lesson. You should get about 4.6 peak QPS, ~23 requests in flight and ~$9,492/month, up from ~1,754. Latency per call does not change with volume; concurrency and cost do, and the cost grows slightly more than 5x because the longer prompt adds uncached tokens.)
- Template: fill
career_kit/design_template.mdfor a permission-aware HR document assistant in 30 minutes. Include at least one Mermaid diagram and one ACL test. - Mock design: pick "design a code-review assistant" and run the 45-minute framework aloud. Score it with the rubric in Part 8.
- Critique: rewrite the weak answer "We will use RAG and an agent" into a strong answer for a customer-support bot. Include requirements, estimates, evals and safety.
- Diagnosis: given a support bot whose answers became stale after a policy update, list the five checks you would run before changing the prompt.
- Eval plan: design an eval system for an invoice extractor. Include dataset slices, field metrics, CI gates, online signals and human review.
- Fresh prompts: run the framework on 6.5 and 6.6 without reading the worked answers first, then compare. Change the gateway's peak factor to 8 and say what in the design changes. (Hint: peak load becomes ~463 calls/second and ~2,800 calls in flight at 6 seconds, double the 4x case, so the connection budget, autoscaling headroom and provider quota planning change; monthly cost does not, because it depends on the daily average.)
Check yourself#
- What are the five signals an LLM system-design interviewer is evaluating?Structured thinking, requirements gathering, trade-off judgement, LLM-specific awareness and communication.
- Why should requirements come before architecture?Because users, wrong-answer cost, data, latency and scale determine which components are appropriate; architecture without requirements is guesswork.
- What four things should you estimate before drawing detailed components?Requests/QPS, tokens and model calls per request, latency/concurrency, and monthly cost plus storage/index growth.
- How does Little's law help estimate concurrency?Average in-flight requests equal arrival rate times average time in system, so higher latency or traffic increases concurrency.
- Why is output-token cost often more important than input-token cost?Output tokens are usually priced several times higher than input tokens, they include reasoning tokens, and long outputs also increase latency because tokens are generated one after another.
- When should you choose a workflow instead of an agent?When steps are known, testable, latency-sensitive or require deterministic control; agents are for open-ended decisions.
- Why must ACL filters be inside retrieval rather than after generation?Because a post-filter can still leak evidence into context, logs or model reasoning; permissions must constrain what is retrieved.
- What is the difference between offline and online evaluation?Offline evals measure controlled quality before release; online evals measure production drift, feedback and business impact.
- Name three failure modes specific to RAG systems.Retrieval misses, stale chunks, bad citations, permission leakage and generation from model memory instead of evidence.
- Why is prompt injection an architectural concern rather than only a prompt problem?Because retrieved documents, tool outputs and user text can contain instructions; defences include least privilege, output validation, sanitisation and monitoring.
- What should you do when you do not know a provider feature during the interview?State the assumption, name the source you would verify, and continue designing the parts you do know.
- What changes should you discuss for a system at 10x and 100x scale?At 10x: caching, routing, sharding, queues and eval automation. At 100x: platform boundaries, multi-region/vendor risk, cost governance and organisational rollout.
- What decides whether the system may act without human approval?The risk tier / autonomy level: read-only answers need grounding and abstention, drafts need acceptance metrics, reversible actions need idempotency and audit, and irreversible or high-impact actions need deterministic checks plus human approval.
- Why should a text-to-SQL system be evaluated on execution results rather than on the SQL text, and where does the model's access to the database stop?Many different queries return the same correct rows, so text comparison marks correct answers wrong and misses queries that look similar but differ in grain or filters. The model never holds a database connection: it proposes SQL, and your code parses it, checks it against a read-only allow-list, applies row limits and a timeout, and runs it under the user's permissions (6.5).
Further resources#
- Module 10A: Evaluation Foundations for datasets, metrics, judges and regression testing
- Modules 11A to 11C: Production & LLMOps for tracing, cost, routing, reliability and operations
- Module 12: Safety & Security for threat modelling, injection, privacy and guardrails
- 07.10: RAG Failure Modes and Debugging for stage-by-stage diagnosis
- 08D.3: Multi-Agent Systems for when multi-agent designs are justified
- OpenAI API documentation, Anthropic documentation, Google Gemini API documentation and OpenRouter documentation for current provider capabilities — verify volatile features before relying on them
← 14B.6 — Interview Prep I: Coding and Fundamentals | Module 14B overview | 14B.8 — Interview Prep III: Take-Homes, Behavioural Rounds and Offers →