System Design, Interviews & Your Portfolio — Landing the Role
"Knowing how to build components is table stakes. Knowing how to architect systems — and price them — is what gets you the offer."
01 · The hookThe Interview That Changes Everything
The interview round where you design an AI system on a whiteboard, plus the portfolio and the framing that get you into that room.
"I've run thirty loops this quarter for two Senior GenAI Engineer seats. Nearly every candidate can build a chatbot — that stopped being interesting in 2024. They fail in the same three places.
They answer my GenAI design prompt with a framework list instead of a system. They can't defend their chunking strategy past the second follow-up. And in the AI-assisted coding round they either refuse to use the assistant or trust it blindly — both are automatic no-hires.
The offer goes to the one candidate in ten who designs the system on the board, prices it at 100K users, and tells me — unprompted — what breaks first. That candidate gets the top of the band."
Her three numbers are the seed of this whole module, so look at them before you read another word. Thirty loops, twenty-seven no-hires, three candidates at her bar, two seats. The picture below draws those thirty people, the three places the twenty-seven fell, and the one thing the three did that nobody else did.
- Thirty circles, three filled. Each circle is one candidate who sat the full loop this quarter. The three filled ones are the candidates Priya would hire; two of them accepted. One in ten is not a rejection rate you can shrug at, and it is not a talent shortage either, because the twenty-seven failed in only three ways.
- The framework list. The candidate recites a set of stages and never commits to a design. It sounds organised and decides nothing, so the interviewer has no decision to score. Section 03 gives you the skeleton that prevents this, and the clock that stops you reciting it.
- The undefended number. The candidate says 512 tokens, and cannot say why when asked twice. Every number you put on the board is a promise that you can defend it once more than you were asked. Probe 1 in section 05 is this exact exchange, written out.
- The assistant. Two opposite failures score the same. Refusing the AI assistant reads as untrainable; accepting its code without reading it reads as dangerous. Section 07 is the protocol that sits between them.
- What the three did. They designed on the board rather than naming tools, attached an arithmetic estimate to the design, and volunteered the first thing that would break. Three habits, all rehearsable, and the rest of this page rehearses them.
You've spent sixteen modules building things: RAG pipelines with eval gates, agents with human-in-the-loop checkpoints, MCP servers, fine-tuned models with cost-benefit sheets. This module converts all of it into the two artifacts that actually get you hired: a 45-minute whiteboard performance and a portfolio that survives scrutiny.
Three things changed since you last ran a job search.
First, at FAANG-tier companies there are now three distinct flavors of the system-design round: traditional distributed systems, ML system design, and the GenAI system design round — "design a RAG service", "design an agentic workflow", "design an LLM chat system", 45–55 minutes on the clock.
Second, Meta runs a dedicated AI-Enabled coding round where you solve problems with an AI assistant and are graded on direction-setting and verification, not keystrokes — and the pattern is spreading.
Third, the stakes repriced: senior GenAI roles in the US run $187K–$457K median total comp at the top tier (agentic-AI postings median $213K), and in India a 9-YOE LLM specialist at a Bengaluru product company lands ₹40–70+ LPA — while the same résumé at a services firm clears 60–150% less.
One interview loop, run well, is worth more than most annual raises compound to in five years.
A system-design interview is an architecture review — something you've run dozens of times — except you're presenting, the review board is one skeptical stranger, and the clock says 45:00.
A behavioral interview is a postmortem writeup read aloud: situation, what you did, measured outcome. And a portfolio is your staging environment — the place a hiring manager can poke your claims before buying.
You are not learning a new skill in this module; you are packaging nine years of engineering judgment plus sixteen modules of AI craft into formats interviewers can score.
"I have designed real systems for nine years. Why would I rehearse a whiteboard performance like a student?"
— a nine-year engineer, reading the bridge above
Because the round measures something the job never trains: reasoning out loud, to a stranger, in forty-five minutes, with no time to measure anything. On the job you ask for a week and a trace. Here you must estimate from stated assumptions and land within a factor of two. Experienced engineers lose this round in one specific way: they design the system they built last year instead of the one that was asked for.
There is a second, quieter failure. Nine years of judgement lives in your hands, not your mouth. You know the chunk size should follow how the retriever is graded; you have never had to say so in one sentence with a number in it. Rehearsal is not learning the material. It is moving what you already know from reflex into speech.
The honest downside: rehearsing can make you sound rehearsed. An interviewer who has watched the flagship board in Fig. 17.3 drawn from memory will steer off it on purpose, and a candidate who memorised the picture rather than the method stalls at the first probe. Rehearse the questions you ask and the numbers you estimate, not the diagram.
Read markers 3 and 5 of Fig. 17.0b together and you have the whole distinction. Marker 3 is a memorised number with nothing behind it. Marker 5 is an estimate the candidate can rebuild out loud when the interviewer changes an assumption. Rehearsal moves you from the first to the second; memorising the board moves you nowhere.
02 · The loopSix Rounds, Three Flavors of System Design
Priya's debrief is the seed of everything that follows: thirty loops, twenty-seven no-hires, two seats. You are going to be candidate thirty-one, and the rest of this module walks her loop one round at a time, from the 10:00 whiteboard prompt to the offer call. Before you practise the round that decides the offer, you need to know where it sits among the other five and what each of them is actually buying. That map is the picture directly below.
Here is the modern senior-AI interview loop, mapped. Companies shuffle the order and banks skip some rounds, but at product companies you should expect every box below at least once. The system-design round is where offers are decided at senior level — and note which flavor of it is newest.
- The round that decides the offer. At senior level the other five rounds mostly screen you out; this one is where the band is set. Forty-five to fifty-five minutes, one prompt, and a stranger probing whatever you cannot defend.
- The round that did not exist. You solve a problem with an AI assistant while being watched, and the grade is on direction and verification rather than keystrokes. Two opposite mistakes fail it: refusing the assistant, and accepting its code unread.
- The newest flavour. The same system-design slot now comes in three versions, and the GenAI one — design a retrieval service, an agent platform, a chat system — is the least practised by candidates. That is the whole reason this module exists.
What each round rewards, in one line each: the recruiter screen rewards a crisp story and a researched comp number; coding rewards LeetCode-medium fluency and SQL window functions (Module 01); the AI-Enabled round rewards the workflow you drilled in Module 15; system design rewards the frameworks below; behavioral rewards prepared STAR stories with numbers; the domain round rewards exactly the consultant skills from Module 16 — turning a vague business ask into metrics and an ML problem.
03 · The frameworkThe 7-Step Whiteboard Playbook
It is 10:00 on interview day. Priya writes one sentence on the whiteboard — design a document question-and-answer service for our enterprise customers — and starts a timer at 45:00. Nothing about the product is defined yet, and this is the exact moment the twenty-seven no-hires in Fig. 17.0b start drawing boxes. You need two things before you touch the marker: a skeleton that makes a silent hole impossible, and a budget that says how many of the forty-five minutes each part gets.
Every ML system design answer follows the same seven-step skeleton. Memorize it, announce it up front ("here's my map: problem, metrics, data, features, model, serving, monitoring — I'll go deep where you steer me"), and never skip a step. Announcing the map does two things: it proves you have a system for systems, and it invites the interviewer to tell you which step they care about — which is where your 45 minutes should go.
| Step | The question you're answering | The trap |
|---|---|---|
| 1 · Problem formulation | What business goal? What ML task does it map to — classification, ranking, anomaly detection, forecasting, generation? | Jumping to a model before agreeing what "good" means |
| 2 · Success metrics | Model metrics (AUC-PR, precision@recall, NDCG) + business metrics ($ saved, retention) + system metrics (p99 latency, availability) | Naming one metric family instead of all three |
| 3 · Data strategy | What exists, how it's collected, labeled or not, volume, freshness, privacy constraints | Assuming clean, on-time labels (they're usually late and dirty) |
| 4 · Features | Offline (batch) vs online (streaming) features; a feature store to keep training and serving consistent | Ignoring training-serving skew |
| 5 · Modeling | Baseline first, then earned complexity; selection justified by constraints, not fashion | Starting with the fanciest model you know |
| 6 · Serving | Batch vs real-time, caching, autoscaling, versioning, rollout strategy | Hand-waving "deploy it on Kubernetes" with no latency math |
| 7 · Monitoring | Drift detection, decay alerts, retraining triggers, feedback loops, A/B testing | Ending at deployment as if models don't rot |
"Here's my map: problem1, metrics2, data3, features4, model5, serving6, monitoring7.
I'll go deep where you steer me8."
- Problem. The business goal, and the machine-learning task it maps to: classification, ranking, forecasting, retrieval, generation or action. The mistake: naming a model before agreeing what "good" means, which leaves every later choice with nothing to justify it.
- Metrics. Three families, every time: a model metric (AUC-PR, faithfulness), a business metric (dollars saved, tickets contained) and a system metric (p99 latency, cost per query). The mistake: naming one family and moving on. Interviewers count to three.
- Data. What exists, how it is collected, whether it is labelled, how fresh it is and what you may not use. The mistake: assuming clean, on-time labels. Fraud labels arrive 30 to 90 days late; a document corpus changes every day.
- Features. In classic ML, offline versus online features and the store that keeps one definition for both. In GenAI, context engineering: chunking, retrieval, reranking and the token budget. The mistake: ignoring training-serving skew, or letting the context window fill by accident.
- Model. A baseline first, then complexity earned by a measured gap. In GenAI this is a routing decision: frontier API, open model or fine-tune. The mistake: starting with the fanciest model you know, or naming a favourite vendor instead of a decision rule.
- Serving. Batch or real-time, caching, autoscaling, versioning, the rollout strategy and the bill. The mistake: "deploy it on Kubernetes" with no latency or cost arithmetic. This is the step where a number is mandatory.
- Monitoring. Drift, quality decay, retraining triggers, eval gates, cost dashboards and who gets paged. The mistake: ending at deployment as if models do not rot. This step is where "what breaks first" gets said.
- Go deep where you steer me. An invitation, said out loud, that hands the interviewer the wheel for the ten-minute deep-dive. The mistake: saying it and then ignoring the steer, or never saying it and spending equal time on all seven steps.
Budget the clock: ~5 minutes each on requirements, metrics, and data; ~10 on the architecture sketch; ~10 on the deep-dive wherever the interviewer steers; ~5 on monitoring and rollout; ~5 held in reserve for follow-up probes. Interviewers rarely grade the diagram — they grade the decisions and whether each one came with a number attached.
- The first fifteen minutes buy the right to draw. Clarify, metrics and data take five minutes each, and no box goes on the board until they are done. A candidate who starts drawing at 0:30 is designing a product nobody specified.
- Ten minutes for the whole board. All seven steps get a box before any one of them gets a sentence of depth. Ten minutes is enough for boxes and arrows and nothing else, which is the point: breadth first, so the interviewer can choose the depth.
- The ten minutes that decide the offer. This is the deep-dive, and the interviewer picks the topic, not you. Marker 5 of Fig. 17.0b lives here: the estimate, the failure mode, the trade-off said out loud. Give this block away by over-running the earlier ones and there is nothing left to score.
- Five minutes you do not plan to use. Held back for the probes that arrive late, and for the follow-up you did not expect. Every design round over-runs somewhere; a candidate with no reserve finishes the monitoring step while being shown the door.
- The recital, for contrast. Seven equal five-minute blocks fill thirty-five minutes and produce a complete list of topics with no depth anywhere. It scores below a candidate who skips monitoring entirely but prices the system out loud, because coverage is not judgement.
Clarify the problem before you touch the board.
Estimate the numbers before you draw.
Draw the whole board, then go deep where they steer.
Say every choice as a trade-off.
End with what breaks first.
Clarify: the first block of Fig. 17.1b, minutes 0 to 5, before a single box exists. Estimate: the next ten minutes, the six-rung ladder you will work by hand in section 05 and that ends at $12,000 a day. Draw the whole board: marker 2, ten minutes for all seven boxes and no depth anywhere. Trade-off: every box leaves the round with a reason and a number attached to it. Breaks first: marker 5 of Fig. 17.0b, the failure mode you volunteer before anyone asks.
"Isn't system design just naming the right boxes? Gateway, cache, vector store, model, queue. I could draw that board in my sleep."
— the same engineer, looking at the seven-step table
The boxes are the cheap half, and every candidate in the loop can name them. If the round were graded on boxes, nobody would fail it, and the debrief in the hook says one candidate in ten passes. What is graded is the decision behind each box and the number attached to it: why this chunk size, what it costs at 100K users, what happens when a document changes.
Try it on yourself. Draw the board, then ask "why?" at each box and write the answer in one sentence with a number in it. The boxes where you cannot are the ones the interviewer finds in under a minute, because those are the probes they ask every candidate.
That minute has a home on the clock. The ten minutes at marker 3 of Fig. 17.1b are the deep-dive, and the interviewer spends them on whichever box you cannot defend. Naming the boxes buys you the ten minutes at marker 2; surviving marker 3 is what the offer is made of.
The honest downside of the seven-step framework: it can become a box-naming exercise of its own. A candidate who recites all seven steps at equal depth, with no numbers, scores below one who skips monitoring but prices the system out loud. The framework guarantees coverage. It cannot supply judgement.
Here is how the round is usually lost, verbatim from real debriefs. Interviewer: "Design a document Q&A service for our enterprise customers." Candidate: "I'd use LangChain with Pinecone and an OpenAI model. We chunk at 512 tokens because that's standard, embed, and do similarity search." Interviewer: "Why 512?" Silence. "What does it cost at 100K users?" Silence. "What happens when a document is updated?" Silence. Three signatures of the no-hire: tool names instead of mechanisms, no numbers, and no failure modes.
The seven steps exist to make those silences structurally impossible — steps 2 and 6 force numbers, step 7 forces failure modes, and naming the mechanism at each step forces you past the framework list.
Before the two of them argue, look at what each one is actually holding. The left panel is everything the candidate knows. The middle panel is everything the interviewer can score. The right panel is the thirty seconds of arithmetic that moves a fact from the left panel to the middle one. Every line of the chat below points at a number in this picture.
- The candidate's panel. All of it is true, and none of it is scoreable. Nine years of judgement, a product at 200 users, and the correct instinct that a real cost answer needs a week of traces. The round does not have a week.
- The interviewer's panel. This is the entire record of the morning: three tool names, one unexplained number, and a silence where the reason should be. The timer reads 45:00 because that is all the evidence there will ever be.
- The arithmetic that crosses the gap. Five assumptions, four multiplications: 100,000 users times five questions gives 500,000 questions a day; 6,000 input tokens at $3 per million is $0.018 and 400 output tokens at $15 per million is $0.006, so one question costs $0.024; times 500,000 is $12,000 a day. You will work every rung of this by hand in section 05.
- The rule under the whole argument. The round measures what is said, not what is known, and it prefers a stated assumption with clean arithmetic to an honest refusal. That is unfair to the way engineering actually works, and it is also the only thing the interviewer is allowed to write down.
Tonight's talk: The Candidate and The Interviewer argue over the question, "Who's more important?"
Let's start with what I bring — panel 1 of Fig. 17.1c, all of it true. Nine years of shipped systems. I have designed the thing you are about to ask me to design, on a real budget, with real users, and it is still running. You have a whiteboard and a timer reading 45:00. If one of us knows what a good answer looks like, it is me.
the candidate's case is that experience is the qualification. Everything in the left panel of the picture is real, and none of it has left his head yet.
I do not doubt it. I also cannot see it. Look at panel 2. That whiteboard is my entire record of this morning: LangChain, Pinecone, 512 tokens because that's standard. I asked why 512 and got the line in red. A reason you did not say is a reason I cannot score. My whole job is to be a fair witness to what reached the board.
the interviewer can only grade the middle panel. Three tool names and one unexplained number are the whole of the evidence, however much sits in the left panel.
A fair witness would ask a fair question. You asked what the system costs at a hundred thousand users. The real product has two hundred — it is written in my panel. A week of traces would answer you honestly, and you wanted it in ninety seconds.
the candidate objects that the question cannot be answered truthfully in the time given. On the job that objection is correct, which is what makes this the hardest habit to break.
I wanted panel 3. Six thousand tokens read per question at three dollars a million, four hundred written at fifteen, five questions per user per day: four multiplications, thirty seconds, and it lands within a factor of two of whatever your traces would have said. "I'd need to measure" is right about the world and wrong about the round. "Roughly twelve thousand dollars a day, and here is every assumption in it" gets the offer.
the accent panel is the answer the interviewer was fishing for. It is not a remembered number; it is five stated assumptions and four multiplications, done out loud.
And the candidate who fills all seven of your boxes with an equal five minutes each — the bottom bar of Fig. 17.1b, thirty-five minutes of coverage and nothing decided? You reward that. I have watched people recite problem, metrics, data, features, model, serving, monitoring like a prayer and design nothing at all.
the recital is a real failure and the candidate is right to name it. Seven steps at five minutes each fills the clock and leaves no depth anywhere.
That candidate scores below you. The seven steps are scaffolding so nobody leaves a silent hole like the one in panel 2. I do not grade the scaffolding; I grade the decisions inside it and whether each came with a number of the kind in panel 3. Announce the map, then go deep where I steer. If I steer toward tenancy and you spend the time on chunk size, that is on you, not the framework.
the framework exists to prevent silence, not to earn points. The points are in the decisions and their numbers, and in following the interviewer's steer.
Then admit your side of it. Your probes punish the exact habits that make me good at the job. In the building, I measure before I estimate. I ask for the week in my panel. I do not draw a system I cannot test.
the round rewards fast estimation and the job rewards careful measurement. Both are true at once, and the candidate is naming a genuine cost of the format.
Admitted. The round is an unnatural act, and the debrief knows it. It is also the only forty-five minutes on my timer in which I can watch you reason under pressure with a stranger pushing back. What I am really testing is marker 4: whether you update on new information without dropping your reasoning. Fold and you read as junior. Fight and you read as difficult. Trade off out loud and you read as senior.
the hidden question in every probe is how you handle being wrong. Changing your answer while keeping your reasoning visible is the senior signal.
So I move my panel into yours, out loud, and you keep your rubric honest.
the truce. The candidate's job is to say what he knows; the interviewer's job is to score it fairly once it is said.
Attach a number of panel 3's kind to every step, tell me what breaks first, and I will have nothing left to probe. We can revisit who matters more after the debrief.
a number on every step plus a volunteered failure mode leaves the interviewer with no opening. That is the whole of marker 5 in Fig. 17.0b.
After the offer, you mean.
nobody wins the argument. Neither chair can do the other's job, and the round happens anyway.
04 · Worked example #1Fraud Detection at 10,000 TPS
Priya's loop has two design rounds, and the first one is at 11:00 with her staff engineer. Same seven steps, no language model anywhere: TrustBank's fraud system at 10,000 transactions a second, under 50 milliseconds each. It is worth walking this one first because its numbers are impossible to hide behind, and because its hardest fact — the labels arrive 30 to 90 days late — is the kind of constraint the GenAI round expects you to find on your own. Get the skeleton right here and the 10:00 board becomes a translation exercise.
The classic ML system design prompt, worked end-to-end: "Design a real-time fraud detection system for a payments company processing 10,000 transactions per second." This is TrustBank's actual problem from Module 03, now at interview scale.
Step 1 — Problem. Block fraudulent payments before money moves. Binary classification (fraud / not fraud) plus anomaly detection for novel patterns. Hard constraints: respond in under 50 ms per transaction at 10K TPS. False positives burn customer trust; false negatives burn money — say that tradeoff out loud, because it drives every downstream choice.
Step 2 — Metrics. All three families, with targets:
| Family | Metric | Target |
|---|---|---|
| Model | Precision at recall ≥ 0.95 | ≥ 0.70 |
| Model | AUC-PR (imbalanced classes — not ROC) | ≥ 0.85 |
| Business | $ fraud prevented / month | tracked monthly |
| Business | Legitimate users blocked (FP rate) | < 0.5% |
| System | p99 latency | < 50 ms |
| System | Availability | 99.99% |
Step 3 — Data. Transaction events stream through Kafka (amount, merchant, location, device, timestamp); a user profile store supplies enrichment (account age, average ticket size, device fingerprint). The catch every strong candidate names: labels are delayed — chargebacks confirm fraud 30–90 days after the event. Bootstrap with confirmed fraud plus rule-based pseudo-labels, then fold in chargeback truth monthly.
Before reading on: what would happen if you retrained monthly using only confirmed chargeback labels — the cleanest data you have?
Reveal the answer
Your freshest confirmed labels would always describe fraud patterns from one to three months ago.
Fraud rings iterate weekly — they A/B test you — so the model would chase where the adversary used to be, and precision would decay right after every retrain.
That's why production systems blend delayed truth with rule-based pseudo-labels and a human analyst queue (which produces same-day labels for the ambiguous middle of the score distribution).
Delayed, adversarial labels are the single most common "gotcha" hiding inside fraud, abuse, and spam design prompts.
That reveal turns on a date, so draw the dates. Everything the fraud model will ever know about one payment arrives at four different times, and the gap between the first and the last is the whole design problem.
- Day 0, the decision. The score has to be produced before the money moves, inside the 50 ms budget, with no label in existence. Every feature the model uses has to be computable at this instant.
- Day 0, the analyst. Human review of the ambiguous middle of the score range produces labels the same day. They are fewer and biased toward the hard cases, and they are the only fresh truth you have.
- Day 7, the adversary. Fraud rings iterate weekly against your live system. This is why the gap matters: it is not that the labels are old, it is that the world moved while you waited for them.
- Days 30 to 90, the chargeback. Clean, confirmed, and describing a pattern that stopped working weeks ago. Production systems blend it with the day-0 analyst labels and rule-based pseudo-labels rather than waiting for it.
Questions you might be asking now
Steps 1 to 3 pack four kinds of number into a few lines: a rate, a time, a pair of accuracy targets and a percentage of uptime. The questions below take them one at a time. Every answer uses the same five TrustBank numbers.
| Number | Value | Where it comes from |
|---|---|---|
| Payments arriving | 10,000 a second | Step 1 |
| Time budget for one payment | Under 50 ms for 99 payments in 100 | Step 1 and the metrics table |
| Time inside the champion model | 15 ms, used as a flat figure | The champion box of Fig. 17.2, "under 15 ms" |
| Availability target | 99.99% | The metrics table |
| Fraud share | 1 payment in 1,000 | An assumption for these answers only |
TrustBank handles 10,000 payments a second, and each must finish in under 50 ms. Is throughput the same thing as latency?
No. Throughput is how many payments finish each second; latency is how long one payment takes. One multiplication links them: payments in flight = throughput × time each. So 10,000 a second × 0.015 s = 150 payments are inside the model at any instant.
- Throughput is a rate: payments finished per second. TrustBank's target is 10,000.
- Latency is a duration: the time from a payment arriving to its decision. The target is under 50 ms at p99.
- p99 is the latency that 99 payments in 100 beat. Sort a day's times from fastest to slowest and read the value 99% of the way along. Module 01's Fig. 1.3d draws that line-up.
Picture a toll plaza. It can pass 1,000 cars an hour with each car through in ten seconds, or the same 1,000 cars with a twenty-minute queue. The count per hour is identical. The wait depends on how close the booths are to full.
| Throughput | Latency | |
|---|---|---|
| Unit | Payments per second | Milliseconds per payment |
| The question it answers | How much work does the system get through? | How long does one customer wait at the till? |
| TrustBank's target | 10,000 a second | Under 50 ms at p99 |
| What improves it | More workers, bigger batches | Faster boxes, and spare capacity so nobody queues |
The rule that links them fits in your head. The left panel of Fig. 17.1e draws a version small enough to count.
- Draw a small version. One payment every 5 ms is 200 a second. Each one spends 15 ms in the model.
- Count what is inside at one moment. At 22 ms, the payments that started at 10, 15 and 20 ms are all still being scored. That is 3.
- Check it against the rule. 200 a second × 0.015 s = 3. Payments in flight = rate × time each.
- Scale it up. 10,000 a second × 0.015 s = 150 payments inside the model at any instant.
- Turn it into workers. One worker scoring one payment at a time finishes 1 ÷ 0.015 = 66.67 a second, and 10,000 ÷ 66.67 = 150 workers. It matches step D because each worker holds exactly one payment.
Why 150 workers is not enough
With 150 workers, every worker is busy all the time. Customers arrive in random clumps, not every 0.1 ms, so a clump landing on a full pool has to queue. Time in a queue is pure latency.
The script throughput_vs_latency.py sends 100 seconds of random arrivals into one shared queue, with a flat 15 ms per payment. Only the pool size changes between rows.
| Workers | Busy | p50 | p99 | Finished per second |
|---|---|---|---|---|
| 148 | 101% | 842.6 ms | 1,508.7 ms, and still growing | 9,867 |
| 152 | 99% | 17.0 ms | 30.7 ms | 10,009 |
| 155 | 97% | 15.3 ms | 21.7 ms | 10,009 |
| 160 | 94% | 15.0 ms | 18.0 ms | 10,009 |
| 175 | 86% | 15.0 ms | 15.5 ms | 10,009 |
| 200 | 75% | 15.0 ms | 15.0 ms | 10,009 |
Read the last column first: from 152 workers up it barely moves. Now read p99. It falls from 30.7 ms to 15.0 ms as the pool grows, with no change in throughput.
At 148 workers the pool finishes only 148 ÷ 0.015 = 9,867 a second. The other 133 a second pile up, and after 100 seconds the newest payment waits 1.5 seconds.
- Three inside at once. The dashed line at 22 ms crosses the payments that started at 10, 15 and 20 ms. The rule predicts the count: 200 a second × 0.015 s = 3.
- The same rule at full size. 10,000 a second × 0.015 s = 150 payments in the model at every instant. It is also the worker count if nobody may ever wait, and that pool cannot cope.
- 148 workers: short by 133 a second. The pool finishes 9,867 a second and the rest queue. After 100 seconds the p99 is 1,508.7 ms and climbing.
- 152 workers: 99% busy. The pool keeps up, but random clumps still queue: p99 is 30.7 ms for a 15 ms job. Little of the 50 ms is left for the other boxes.
- 160 workers: 94% busy. Eight more workers than the zero-slack count bring p99 to 18.0 ms. Latency is bought with spare capacity, not a faster model.
So "150, because 10,000 × 15 ms" uses the right rule and forgets the queue. "About 160, so the p99 stays near 18 ms" answers the question actually asked.
The honest limit: this simulation is kinder than production. Real scoring times vary, and real traffic has bursts such as lunchtime; both lengthen queues. The rule in flight = rate × time holds for averages over a steady period, but a p99 has to be measured or simulated.
Throughput is how many per second; latency is how long each; payments in flight are the two multiplied. A pool run close to full keeps its throughput and loses its latency.
Precision at least 0.70 at recall 0.95, and under 0.5% of legitimate users blocked: what do those targets mean in real payments? Aren't they the same thing?
No. Precision divides by the payments the model flagged; the false-positive rate divides by every legitimate payment. At 1 fraud in 1,000, the precision target allows 244 honest customers flagged a minute, and the 0.5% limit on its own would allow 2,997. The precision target is 12.3 times stricter, so it is the one that binds.
Three terms from the metrics table sound alike. They differ only in what goes under the line of the fraction.
- Recall. Of all the fraud that happened, the share the model caught.
- Precision. Of all the payments the model flagged, the share that really were fraud.
- False-positive rate. Of all the legitimate payments, the share the model flagged by mistake.
Work one minute of TrustBank traffic, with the model sitting exactly on its targets.
- Payments in a minute. 10,000 × 60 = 600,000.
- Split them. 600,000 × 0.001 = 600 fraudulent. 600,000 − 600 = 599,400 legitimate.
- Apply recall 0.95. 0.95 × 600 = 570 caught, so 30 missed.
- Apply precision 0.70. The 570 must be 70% of everything flagged, so flagged = 570 ÷ 0.70 = 814.3. Divide rather than multiply, because 570 is the part and the flagged total is the whole.
- Count the honest customers flagged. 814.3 − 570 = 244.3 a minute.
- Turn that into a false-positive rate. 244.3 ÷ 599,400 = 0.000408, which is 0.0408%. That is far under the 0.5% limit.
| Precision | False-positive rate | |
|---|---|---|
| Top of the fraction | Fraud caught: 570 | Legitimate payments flagged: 244.3 |
| Bottom of the fraction | Everything flagged: 814.3 | Every legitimate payment: 599,400 |
| Value on target | 0.70 | 0.0408% |
| Who feels it | Whoever works the flags: 3 in 10 are honest customers | The customers: 244 blocked payments a minute |
| If fraud becomes half as common and the model stays the same | Falls to 0.538 | Stays at 0.0408%, because it never looks at fraud |
Now hold the model only to the 0.5% limit. That allows 0.005 × 599,400 = 2,997 honest customers flagged a minute, and precision 570 ÷ (570 + 2,997) = 0.1598: about 5 flags in 6 would be honest. The two targets ask for the same thing only when fraud is 1.2132% of payments. Below that, precision does the work.
- The split. One payment in a thousand is fraud, an assumption for these answers: 600 fraudulent and 599,400 honest payments a minute. The honest side is 999 times bigger.
- The flag queue. Everything the model flags: 570 frauds and 244.3 honest customers, 814.3 a minute. Precision is measured here.
- Precision. 570 ÷ 814.3 = 0.70, so 3 flags in 10 are honest customers. It falls when fraud gets rarer, even if the model does not change.
- False-positive rate. The same 244.3 customers divided by all 599,400 honest payments: 0.0408%. It looks tiny because the bottom of the fraction is enormous.
- The weaker target. A model held only to the 0.5% limit could flag 2,997 honest customers a minute, with precision 0.16, and still pass.
This is also why the metrics table asks for AUC-PR, not ROC. A ROC curve plots the false-positive rate, which stays small whenever honest payments outnumber fraud 999 to 1. A precision-recall curve shows the flag queue filling with honest customers, which is what actually happens.
Over a full day at 10,000 a second, even a model exactly on target flags 351,771 honest payments and misses 43,200 frauds.
The honest limit: 1 in 1,000 is an assumption, since the page gives no fraud rate. The widely used Kaggle credit-card dataset has 492 frauds in 284,807 transactions, 0.17%. And none of these numbers is known on day 0: precision and recall need confirmed labels, which Fig. 17.1d shows arriving 30 to 90 days late.
Precision divides by the flags; the false-positive rate divides by every honest payment. When fraud is rare, precision is the target that bites.
The table says 99.99% availability. How much downtime is that, and what happens to a payment while the fraud path is down?
99.99% allows 4.383 minutes of downtime a month, about 4 min 23 s, and 2,629,800 payments arrive in that time. Four boxes in a row at 99.99% each give only 99.96%, which is 17.53 minutes. So each box has to beat the target, and the design must decide in advance what a payment gets while scoring is down.
Availability is the share of time a system answers. The rest is downtime. At 10,000 payments a second, downtime is counted in payments, not minutes.
- Minutes in a month. 43,830 on average, which is 365.25 days × 24 × 60 ÷ 12. It is the month Appendix A2 uses.
- The share allowed to be down. 1 − 0.9999 = 0.0001.
- Downtime in minutes. 43,830 × 0.0001 = 4.383 minutes, about 4 min 23 s.
- Payments in that time. 4.383 × 60 × 10,000 = 2,629,800.
Now the catch. A payment is scored only if every box on the real-time path of Fig. 17.2 answers: online features, the bandit router, the champion model and the decision engine. A chain is up only when all of its links are up, so the availabilities multiply.
- Four boxes at 99.99% each. 0.9999 × 0.9999 × 0.9999 × 0.9999 = 0.99960.
- Downtime of the chain. 43,830 × (1 − 0.99960) = 17.53 minutes a month, four times the target. That is 10,517,622 payments.
- What each box needs instead. The fourth root of 0.9999 is 0.999975, which allows each box only 1.096 minutes a month. The fourth root is the number that, multiplied by itself four times, gives 0.9999.
- What a second copy buys. Two copies of one box are down only when both are down: 1 − 0.0001 × 0.0001 = 0.99999999. That is about 0.026 seconds a month, if the two copies fail independently.
- One box. 99.99% of a 43,830-minute month leaves 4.383 minutes of downtime: 2,629,800 payments with no score at 10,000 a second.
- Four in a row. Multiply 0.9999 four times and you get 0.99960, or 17.53 minutes a month. Four boxes that each meet the target miss it together by four times.
- What each box must do. For a 99.99% chain, each box needs 0.999975, or 1.096 minutes a month. That is the number to write next to each box.
- A pair. Two copies of a box fail the payment only when both are down at once: 0.99999999, if their failures are independent. Copies sharing one cluster or region are not.
- The decision made in advance. Failing open lets 2,630 frauds through; failing closed declines 2,627,170 honest payments. A rule that needs no model keeps a worse service running instead of none.
Failing open suits small payments, where a declined card costs more than the fraud, and TrustBank pays the losses. Failing closed puts the cost on honest customers, so it is rarely right for all traffic. Falling back to a rule is the usual answer: a worse decision, but still a decision.
One detail makes the fallback real. Step 5's day-one rule needs "new merchant" and "new device", which come from the feature store. A fallback that reads the feature store fails with it, so it needs its own copy of those lookups, or a rule that reads only the payment.
The honest limit: multiplying availabilities assumes the boxes fail independently. Two boxes that share one Redis cluster or one region fail together, and a "pair" then buys far less than the arithmetic says. A box that answers in 300 ms is also "up" by this measure and useless to a 50 ms path, so count timeouts as downtime.
Availabilities multiply along a chain, so every box must beat the target. Four minutes a month at 10,000 a second is 2.6 million payments that need a decision chosen in advance.
Step 4 — Features. Two speeds, one definition. Offline features computed daily in batch (30-day average amount, unique merchants in 90 days, account age, historical chargeback rate); online features computed per-request from the stream (transactions in the last 5 minutes, distance from last location, "new merchant for this user?", "amount more than 3σ above this user's mean?"). A feature store (Feast/Tecton pattern) holds one definition for both paths — offline store in Parquet on S3, online store in Redis fed by Kafka Streams — because training-serving skew is the silent killer: a model trained on yesterday's feature definition serving today's slightly different one.
Step 5 — Modeling. Earn complexity, in four stages:
- Rule baseline — amount over $5,000 plus new merchant plus new device → flag. Ships day one, and becomes your pseudo-labeler.
- XGBoost on the feature set — fast, interpretable, tabular-native. Module 03's lesson: trees still beat deep nets on tabular data.
- A neural sequence model over user behaviour.
- Ensemble the two scores.
Step 6 — Serving is the diagram below.
Step 7 — Monitoring. Drift detection on transaction distributions. Weekly precision-at-recall tracking, with a retrain trigger at −5%. Shadow then canary rollout for new models. And chargebacks feeding back monthly.
- The router, not a switch. Ninety-five percent of transactions go to the proven model and five percent to the candidate, and that split moves on its own as evidence accumulates. Nobody schedules a cutover; the challenger earns the traffic.
- The labels arrive late. This is the box that is dashed for a reason: chargebacks confirm fraud 30 to 90 days after the decision, so the training data always describes a world that has moved on.
- The humans close the gap. Cases in the ambiguous middle of the score range go to an analyst, who produces a confirmed label the same day. That is the only fresh truth in the whole picture, and it is why the queue is part of the architecture rather than an operations detail.
Under the hood: the math of multi-armed bandits (UCB) — optional depth
How do you deploy a new model without betting 100% of live traffic on it? The bandit router in Fig. 17.2 scores each model i at time t as:
Sᵢ(t) = x̄ᵢ + c · √( ln t / Nᵢ(t) )
In words, term by term:
- x̄ᵢ is model i's average observed reward so far — for example, its confirmed-correct decision rate.
- Nᵢ(t) is how many requests model i has served.
- ln t grows slowly with total traffic.
- c tunes how adventurous the router is.
The square-root term is an uncertainty bonus. A model that has served few requests has a small Nᵢ, so its bonus is large — "optimism in the face of uncertainty".
Route every request to whichever model currently has the highest Sᵢ.
Why this formula and not a fixed 95/5 split? A fixed split pays a constant tax forever — 5% of traffic goes to the worse model even after you know it's worse. UCB's bonus shrinks as √(1/Nᵢ), so exploration decays exactly as confidence grows: total regret (money lost to the worse arm) grows like ln t instead of linearly. The system exploits the proven winner, keeps probing the uncertain option, and hands over traffic smoothly the moment the challenger's lower bound beats the champion's mean.
And the quick-sketch version of the second classic prompt — news-feed ranking — as a compressed table you can reproduce in five minutes flat:
| Step | Design decision |
|---|---|
| Problem | Rank 500+ candidate posts per user to maximize engagement |
| Metrics | Model: NDCG@20 · Business: time-on-feed, DAU · System: p50 < 200 ms |
| Data | Click logs, dwell time, likes/shares/hides, profile, social graph |
| Features | Author-user affinity, freshness, content embedding, user history |
| Model | Two-tower retrieval (candidates) → LightGBM ranker → diversity re-ranker |
| Serving | Pre-computed candidate embeddings offline; real-time scoring; cache hot users |
| Monitoring | Per-cohort engagement, interleaving tests for new rankers, filter-bubble checks |
05 · The 2026 centerpieceGenAI System Design
Back to 10:00 and Priya's own whiteboard. This is the round that decides the two seats, and the timer still reads 45:00. Everything you have built since Module 06 is about to be asked for in one sitting: the corpus, the retrieval, the token budget, the bill, and what breaks first. The rest of this section is that single round run minute by minute — clarify, estimate, draw, then four probes — and it ends with you sitting in Priya's chair, scoring somebody else's answer to the same prompt.
This is the round your sixteen modules were secretly rehearsing for. The skeleton is the same seven steps — same skeleton, new organs. Here is the translation table; notice that every right-hand cell is a module you've already built through:
| Step | Classic ML version | GenAI version (what they listen for) |
|---|---|---|
| 1 · Problem | Which ML task? | Is this retrieval, generation, or action? Does it even need an LLM? (Module 06) |
| 2 · Metrics | AUC, NDCG | Offline evals: faithfulness, relevancy, validated LLM-as-judge. Online: TTFT, cost/query, containment rate (Module 07) |
| 3 · Data | Labels, freshness | Corpus and ingestion: parsing, chunking, update feeds, index staleness (Module 08) |
| 4 · Features | Feature store | Context engineering: retrieval quality, reranking, the context-window token budget (Module 08) |
| 5 · Model | Baseline → complex | Model routing: frontier API vs open model vs fine-tune — a decision framework, not a favorite (Modules 11, 12) |
| 6 · Serving | Batch vs real-time | KV cache, continuous batching, semantic cache, prompt caching, streaming — and the bill (Module 12) |
| 7 · Monitoring | Drift, retraining | Eval-in-CI gates, tracing, guardrail hit rates, corpus staleness alarms, cost dashboards (Modules 07, 12) |
Interviewers also listen for a specific vocabulary — not as buzzword bingo, but because each term proves you've operated the thing it names. These seven earn instant credibility when used correctly, and instant suspicion when fumbled:
| Term | What it is | Drop it when discussing… |
|---|---|---|
| KV cache | Stored attention keys/values so each new token doesn't recompute the whole prefix | Why long contexts eat GPU memory; why serving ≠ training hardware math |
| Continuous batching | Slot-level batching that refills the GPU per token, not per request | Throughput on vLLM; why naive batching wastes half the GPU |
| Semantic cache | Cache keyed on embedding similarity, not exact string match | Cost cuts: 30–40% hit rates on FAQ-shaped traffic |
| TTFT vs TPOT | Time-to-first-token (prefill) vs time-per-output-token (decode) | Latency budgets; why streaming makes TTFT the UX metric |
| Context-window budget | Explicit token allocation: system + retrieved chunks + history + query | Chunking and rerank choices; cost-per-query arithmetic |
| Guardrails | Input injection scanning + output grounding/PII checks around the model | Security step of any enterprise design (Module 12) |
| LLM-as-judge | A model grading outputs — only trustworthy after validation against human labels | Eval strategy; always mention the validation step (Module 07) |
Worked example A — "Design an enterprise document Q&A service"
The prompt is on the board and the first five minutes belong to questions, not boxes. Priya answers them: 100,000 employees across tenant companies, about 12,000 documents each, daily updates, answers must cite their source, and p95 time-to-first-token under 1.5 seconds. That is enough to size the system, and sizing it is what minutes 5 to 15 are for. You do the arithmetic before you draw, because every box you are about to draw is justified by one of these numbers.
The single most common GenAI design prompt in 2026 loops, and it is PolicyPal's product from Module 08 at enterprise scale.
Requirements first: 100K employees across tenant companies, ~12K policy and process documents per tenant, updates daily, answers must cite sources, wrong answers have compliance cost, p95 time-to-first-token under 1.5 s.
Here is the same ladder drawn, because on the board you will climb it out loud, in this order, and each rung is one multiplication away from the rung above it.
- Rung 1, the volume. 100,000 employees asking five questions each workday is 500,000 questions a day. Nothing else can be sized until this exists, which is why a candidate who never asks for the user count cannot score on any later step.
- Rung 2, the peak. The average of 5.7870 questions per second is the number that lies to you. Traffic arrives inside an eight-hour workday and bunches, so the honest figure is 52.0833 per second at the busiest hour — nine times the average, and the number you buy capacity for.
- Rung 3, the bill. Three billion input tokens at $3 per million is $9,000; two hundred million output tokens at $15 per million is $3,000. Twelve thousand dollars a day, $360,000 a month, and three quarters of it is the reading side. That is why every lever in Probe 4 shrinks the context rather than the answer.
- Rung 4, the index. 480,000 chunks, each a list of 1,024 numbers at four bytes apiece, is 1.9661 GB per tenant before the search index is built. It fits in memory on one node, the graph index roughly doubles it, and fifty tenants is where you start sharding.
Metrics: faithfulness ≥ 0.90 and answer relevancy ≥ 0.85 on a golden set (Ragas + a judge validated against human labels — Module 07), cost per query as a first-class SLO, citation coverage 100%.
Corpus and ingest: parse with
layout awareness (LlamaParse for tables), chunk heading-aware at 400–800 tokens, embed with
BGE-M3 or text-embedding-3-large, index in pgvector with dense + BM25 hybrid and
tenant_id stamped on every chunk. Retrieval: hybrid top-50 →
cross-encoder rerank to top-8 (Module 08's exact pipeline).
Serving and cost: semantic cache in front, model routing cheap-first, streamed responses. Security: tenant filter applied at the query layer before retrieval, injection scanning on inputs, grounding checks on outputs.
One requirement has not been sized yet: p95 time-to-first-token under 1.5 seconds. A latency target is not a wish, it is a budget, and a budget has to be divided before it can be met. Here is the 1,500 milliseconds handed out to the stages that spend it.
- The reranker is the expensive piece of plumbing. A cross-encoder reads the question together with each of the 50 candidates, so it costs more than the search that produced them. It buys the biggest single jump in answer quality, and 180 ms is what that quality costs.
- The model's prefill dominates everything. Six hundred of the thousand milliseconds are the model reading 6,000 tokens before it writes anything. This is why the levers that cut the bill — a tighter context, fewer chunks — also cut latency, and why the two arguments are really one argument.
- The total is what you promise. One thousand milliseconds against a 1,500 ms target. Streaming makes this number the user's whole experience: the answer goes on arriving for twelve more seconds, and nobody is waiting for it.
- The margin is the design. Five hundred milliseconds of slack is what absorbs a cold cache, a slow tenant, a retry. A budget that sums exactly to the target has already failed, because p95 means one request in twenty is worse than this.
Here is the whole thing on one board — this is the diagram to be able to draw from memory:
The board below names tools from five earlier modules: LlamaParse, BGE-M3, pgvector, Langfuse, promptfoo. If a label does not ring a bell, that is fine. The table under the figure walks every box in plain words and says which file from Module 08 does the job.
- The tenant filter is the first thing that happens. Authentication resolves who is asking, and the tenant becomes a hard condition of the search before any ranking occurs. Draw it here, at the start of the query path, and the tenancy probe answers itself.
- The cache short-circuits a third of the traffic. Keyed on the meaning of the question rather than its exact words, it answers 30 to 40 percent of enterprise question-and-answer traffic for the price of an embedding lookup. Everything to the right of it is only paid for on a miss.
- Nothing ships except through the gate. A prompt change, a chunk-size change and an index change are all the same kind of change, and all three have to pass the eval suite in continuous integration first. This is the box that turns a demo into a service.
Now the same board a second time, concretely. The second column is the answer from the failure-mode box in section 03, which is what most candidates draw. The third column is Fig. 17.3, built from the files you wrote in Module 08 and the cost model later in this section. If a box in the figure feels abstract, find its row here.
| Stage | In the naive answer (section 03) | On the production board (Fig. 17.3) | What flows out |
|---|---|---|---|
| Ingest and parse | A plain text extractor over the PDFs; tables come out as word soup | LlamaParse or another layout-aware parser; a change feed re-parses only what changed | Clean text with document id, page, version and tenant_id |
| Chunk | 512 tokens "because that's standard" | Heading-aware, 400–800 tokens, the size chosen on the golden set (600 beat 300 and 1,200 on PolicyPal) | Chunks that each hold one complete idea |
| Embed | One embedding call per chunk, model unnamed | BGE-M3 or text-embedding-3-large, the same model.encode(...) as mini_rag.py, model name pinned in the schema | One vector of 1,024 or 3,072 numbers per chunk |
| Index | Pinecone, similarity search only | pgvector with dense plus BM25 and tenant_id on every row: the chunks table from schema.sql | An index that answers meaning queries and exact-identifier queries |
| Query and auth | The question goes straight to search | The tenant filter is a hard metadata predicate applied before retrieval, with row-level security as the second wall | A query that can only reach one tenant's rows |
| Semantic cache | None, or a cache keyed on the exact string | A cache keyed on embedding similarity; 30–40% of questions hit it | A stored answer in milliseconds, or a miss that continues |
| Hybrid retrieve | Top 5 by cosine similarity | Dense plus BM25 fused by rrf() in hybrid_rrf.py, top 50 | A ranked shortlist of candidates |
| Rerank | None | CrossEncoder in rerank.py reads question and chunk together, keeps the top 8 | The chunks that answer the question, not just resemble it |
| Assemble context | Paste the chunks into the prompt | A 3–6K token budget: system prompt, numbered chunks, then the question | A prompt the model can cite by number |
| LLM and guardrails | "Ask the model to answer with citations" | Injection scan on the way in, grounding check on the way out, streamed, routed cheap-first | An answer with checkable [n] citations, first token in under 1.5 s |
| Evals, traces, cost | "Have the model check its own answers" | Langfuse traces, Ragas plus a validated judge in eval_rag.py, a promptfoo gate in CI, doc_qa_cost_model.py for the bill | Numbers that say which stage to fix and what it costs |
Third time, and this is the version to carry into the room. Same board, boxes and arrows only, with every number you worked out on the ladder written next to the component it sizes. A box with a number beside it is a decision. A box without one is a noun.
- The index is sized by the corpus, not by the traffic. 480,000 chunks at 1,024 dimensions and four bytes is 1.9661 GB per tenant, and the graph index roughly doubles that. Write it next to the index box and the sharding question answers itself.
- The reranker is where quality is bought. Fifty candidates in, eight out, 180 milliseconds. Those eight chunks are what the model sees, so every argument about faithfulness is really an argument about this box.
- The model box carries the bill. $0.024 a question is the number that becomes $12,000 a day. Putting it on the board next to the model, unprompted, is the single strongest ninety seconds available in the round.
- The lane nobody draws. Traces, the eval gate and the cost dashboard are one wide box under everything else, because they touch every request. A board without this lane says the candidate has built a pipeline but never operated one.
Drawing the board is the easy half. The round is decided by the follow-up probes — here are the four that interviewers actually ask, with strong-answer shapes:
Probe 1 — "Defend your chunking." Weak: "512 is standard." Strong: tie chunk size to retrieval granularity and the token budget — "Heading-aware 400–800 token chunks keep each chunk a self-contained idea, so the reranker judges complete thoughts. Smaller fragments lose context and force more chunks into the window; page-sized chunks smuggle irrelevant text in and dilute faithfulness. I'd validate on our golden set: chunking is an eval-measured decision, not a constant — when we tested 300 vs 600 vs 1,200 on PolicyPal, 600 won on faithfulness by six points."
Probe 2 — "A document changed yesterday. Your index still serves the old version — what now?" Strong: incremental ingestion off a change feed (webhook or nightly diff), re-embed only changed chunks, version documents so citations pin to the version the answer used, and — the senior touch — a staleness alarm: alert when source-of-truth timestamps outrun index timestamps beyond SLA. Never "we re-index everything nightly" for a 12K-doc corpus that changes 40 documents a day.
- The nightly answer is not wrong, it is expensive and blind. It re-embeds every chunk to catch a third of one percent of changes, and between two runs an answer can cite a policy that was replaced this morning. Nothing in the system knows.
- The change feed does the small job. A webhook or a nightly diff finds the forty changed documents, and only their 1,600 chunks are re-parsed and re-embedded. The same work, three hundred times smaller, which is why it can run continuously instead of once.
- The alarm is the senior half of the answer. Compare the source system's last-modified timestamp with the index's, and page someone when the gap exceeds the service level you promised. Without it, staleness is invisible until a customer finds it in a compliance answer.
Probe 3 — "Two customers on one deployment. Prove tenant A never sees tenant B's documents." Strong: defense in depth.
Tenant filter enforced at the retrieval layer as a hard metadata predicate (never "the LLM is instructed not to"), row-level security in pgvector as the second wall, per-tenant encryption keys if compliance demands physical separation, and a red-team eval in CI that tries cross-tenant leakage on every release (Module 12's security suite).
Bonus point: note that prompt injection inside an uploaded document is the attack path — a poisoned PDF saying "ignore tenant restrictions" — which is why the filter must live below the model, where instructions can't reach.
tenant_id = A applied before the search, so the other 480,000 chunks are not candidates at all.- The leak is one row. Nothing dramatic happens: the search ranks by meaning, one of tenant B's chunks is genuinely the closest match, and it lands in the model's context. The answer is well-grounded, cited, and a breach.
- The filter is a predicate, not a prompt. Stamp
tenant_idon every chunk at ingest and make it a hard condition of the query. The rows are excluded before ranking, so there is no path by which the model could see them, whatever the question says. - Two more walls, because one is never enough. Row-level security in the database catches a query built wrong by your own code, and a red-team eval in continuous integration tries the attack on every release. The attack to test is a document that says "ignore tenant restrictions" — which is exactly why the control has to live below the model.
Probe 4 — "What does this cost at 100K users?" Before reading on: 100K employees, ~5 questions each per workday-ish (call it 5/day), 6,000-token contexts and 400-token answers on claude-sonnet-5 ($3 in / $15 out per million tokens, Aug 2026). What's the monthly bill, order of magnitude — and which three levers cut it?
Reveal the answer
Per query: 6,000 × $3/1M = $0.018 in, plus 400 × $15/1M = $0.006 out ≈ $0.024. Volume: 100K × 5 × 30 = 15M queries/month. Naive bill: ≈ $360K/month — a number that ends projects.
The three levers, exactly as built in Module 12: a semantic cache (~35% of enterprise Q&A is paraphrased FAQs), a router that sends easy lookups to claude-haiku-4-5 ($1/$5), and a tighter context (rerank to top-5, ~3K tokens).
Together: roughly $78K/month — a 78% cut with no quality loss that your eval suite can prove. Delivering this arithmetic unprompted is the strongest 90 seconds available in this round.
Three levers, three cuts, and the order matters because each one acts on what the one before it left. Drawn as bars, the argument takes ten seconds to make and it is the same arithmetic the file below runs.
- The naive bar is the one that ends projects. Fifteen million questions a month at $0.024 each is $360,000, and it is what a design with no cache, no router and no context budget actually costs. Say this number before anyone else does.
- The cache removes questions, not tokens. Enterprise question-and-answer traffic is full of paraphrased repeats, so a cache keyed on meaning rather than exact text answers about 35% of it for the price of an embedding lookup. The bill falls by the same 35%.
- The context trim is the quiet one. Reranking to five chunks instead of eight halves the tokens the model reads, and reading is three quarters of the bill. It also takes 300 milliseconds off the prefill in Fig. 17.2c, which is the same lever twice.
- The router is the last third. Most questions are lookups a small model answers correctly, so seven in ten go to the model at $1 and $5 per million instead of $3 and $15. What makes this defensible rather than reckless is the eval suite that shows the cheap answers are still faithful.
You have not been walked through the file below yet. Guess first, then check. Every line is explained in the step-by-step list between this exercise and the code, and the same arithmetic was worked by hand in the pencil exercise at the top of this worked example.
Step-by-step: what doc_qa_cost_model.py does, in plain English
- Set the four workload assumptions as named constants: 100,000 users, 5 questions each per day, 6,000 tokens of context per question (the system prompt, eight reranked chunks and the question), and 400 tokens of answer. Underscores inside a number are digit separators Python ignores.
- Define
PRICE, a dictionary from model name to a pair of prices: dollars per million input tokens, then dollars per million output tokens. Two models are listed, the frontier one and the cheap one. - Define
per_query(model, ctx, out): look up the model's two prices, charge the context tokens at the input price and the answer tokens at the output price. Dividing by1e6turns token counts into millions. The result is the cost of one uncached question, in dollars. - Define
monthly(mix, cache_hit).mixis a list of pairs: a share of traffic and the per-query cost for that share. Total questions in a month is users, times questions per day, times 30. - Multiply by
(1 - cache_hit): cache hits are served from stored answers and cost nothing here, so only misses are billed. The sum overmixis the blended cost of one miss. - Scenario 1: every question goes to the frontier model with the full 6,000-token context and there is no cache. That is the naive bill.
- Scenario 2: 35% of questions hit the cache; of the misses, 70% go to the cheap model and 30% to the frontier model, both with the context trimmed to 3,000 tokens.
- Print both monthly figures and the saving, as dollars with thousands separators and as a percentage. Run it and check the two numbers against the Brain Power reveal above.
# No installs needed — Python 3.10+ stdlib only.
# The back-of-envelope model behind Probe 4. Bring numbers like these to the
# whiteboard; date-stamp them ("Anthropic pricing as of Aug 2026").
USERS = 100_000
QUERIES_PER_DAY = 5 # per user — support/policy-lookup workload
CTX_TOKENS = 6_000 # system prompt + 8 reranked chunks + query
OUT_TOKENS = 400 # grounded answer with citations
# $ per 1M tokens (input, output)
PRICE = {
"claude-sonnet-5": (3.00, 15.00),
"claude-haiku-4-5": (1.00, 5.00),
}
def per_query(model, ctx=CTX_TOKENS, out=OUT_TOKENS):
p_in, p_out = PRICE[model]
return ctx / 1e6 * p_in + out / 1e6 * p_out
def monthly(mix, cache_hit=0.0):
"""mix = [(traffic_share, cost_per_query), ...] for cache MISSES.
Cache hits cost ~nothing (embedding lookup), so they drop out."""
queries = USERS * QUERIES_PER_DAY * 30
return queries * (1 - cache_hit) * sum(s * c for s, c in mix)
# Scenario 1 — naive: every query hits the frontier model with a fat context.
naive = monthly([(1.0, per_query("claude-sonnet-5"))])
# Scenario 2 — engineered: 35% semantic-cache hits; router sends the easy
# 70% of misses to Haiku; rerank tightened to top-5 trims context to 3K.
engineered = monthly(
[(0.70, per_query("claude-haiku-4-5", ctx=3_000)),
(0.30, per_query("claude-sonnet-5", ctx=3_000))],
cache_hit=0.35,
)
print(f"Naive: ${naive:,.0f} / month") # ≈ $360,000
print(f"Engineered: ${engineered:,.0f} / month") # ≈ $78,000
print(f"Saved: ${naive - engineered:,.0f} ({1 - engineered / naive:.0%})")
Under the hood: the latency and memory arithmetic of LLM serving — optional depth
Total latency ≈ TTFT + TPOT × output tokens. TTFT (time to first token) is the prefill phase: the model processes all N prompt tokens in parallel — compute-bound, so it grows with prompt length. TPOT (time per output token) is the decode phase: one token per step — memory-bandwidth-bound and roughly constant. With TTFT = 600 ms on a 6K prompt and TPOT = 30 ms, a 400-token answer takes 0.6 + 0.03 × 400 = 12.6 s to finish — but streaming makes perceived latency equal TTFT, which is why every chat product streams and why TTFT, not total time, is the UX SLO.
Why the KV cache exists: without it, generating token n would recompute attention over all n−1 predecessors — total work would grow with the square of sequence length. Caching each token's keys and values makes each step's new work constant.
The price is memory: KV bytes per token = 2 × layers × KV-heads × head-dim × 2 bytes (FP16).
For a Llama-3-8B-class model: 2 × 32 × 8 × 128 × 2 ≈ 0.13 MB per token, so one 6K-token request holds ≈ 0.8 GB of KV cache. Forty concurrent requests ≈ 32 GB — an entire A100's memory on cache alone.
That arithmetic is why vLLM's paged KV cache and continuous batching exist (Module 12), and quoting it is what "senior" sounds like in this round.
Both answers come from engineers who know how retrieval works. Put the two whiteboards side by side and the difference is not knowledge, it is that every line on the right carries a number or a reason, and every line on the left is a noun.
- The left board is a pipeline. Every stage is present and correctly ordered, which is why it reads as fluent and scores four. No line on it could be argued with, because no line on it claims anything.
- The right board is a set of decisions. Same six stages, each carrying either a measurement (600 tokens beat 300 and 1,200 by six points) or an amount (1,600 chunks a day, $12,000 a day). Each one invites a follow-up that you can answer.
- The gap is rehearsable. This is the good news in the whole module. The distance between the boards is the capacity ladder, four probe answers and one sentence about what breaks first — all of which you can practise in an afternoon.
One line of that rubric is the component most candidates never draw at all. They draw the query path, answer the four probes, and stop — as though the system were finished the moment it works once. Here is the lane that makes it keep working, bolted onto the board you already have.
- Traces are the raw material. Every call logged with its prompt, its retrieved chunks, its latency and its cost. Without them there is no error analysis, and error analysis is the only way to find the failures your golden set does not yet contain.
- The golden set grows. It starts as 120 questions with known answers and gains a case every time production surprises you. This is what makes the loop a loop rather than a one-off test suite.
- The gate is the whole point. A threshold that blocks a merge is the difference between having evals and being protected by them. Say the number out loud in the round: faithfulness below 0.90 does not ship.
- Alarms watch what the gate cannot. The gate sees changes you make; the alarms see the world changing under you — a stale index, a cost creeping past $0.008 a question, a cache hit rate falling off 35%. Naming both is what "monitoring" means in step 7.
Questions you might be asking now
Worked example A is now complete: the ladder, the latency budget, the board, four probes, the bill and the loop. The questions below slow down on how those pieces meet one real question. Every answer uses the same four questions from tenant A's employees at the 9 a.m. peak.
| # | The question | Nearest question already in tenant A's cache | Similarity | What the cache does |
|---|---|---|---|---|
| Q1 | How many days of annual leave can I carry over? | None: it is the first question of the morning | none | Miss. Full path, answer stored |
| Q2 | How much unused annual leave rolls over into next year? | Q1 | 0.9846 | Hit. Q1's answer, and it is right |
| Q3 | Which form do I file for an expense over $5,000? | Q1 | 0.0558 | Miss. Full path, answer stored |
| Q4 | How many days of sick leave can I carry over? | Q1 | 0.9530 | Hit. Q1's answer, and it is wrong: annual-leave rules for a sick-leave question |
Walk one question through the board, box by box: what happens to it, how long each box takes, and what it costs?
Q1 spends 400 ms in four boxes of plumbing and 600 ms while the model reads 6,000 tokens. Its first word arrives at 1,000 ms and its last at 13,000 ms. It costs $0.024. Q2, a cache hit, is finished at 50 ms and costs no model call at all.
Follow Q1 from left to right along the query path of Fig. 17.3. The milliseconds are the budget of Fig. 17.2c: times the design assumes, not measurements. The 30 ms per written token comes from the serving hood above.
| Station | What it does to Q1 | What comes out | Adds | Clock |
|---|---|---|---|---|
| Query and auth | Finds out who is asking and fixes tenant_id = A as a hard filter. Turns Q1 into a vector and checks tenant A's cache. | 480,000 reachable chunks of the 960,000 in the index. Cache empty: a miss. | 50 ms | 50 ms |
| Hybrid retrieve | Dense search matches by meaning; BM25, a keyword score, matches exact words such as "carry over". | 50 candidate chunks | 120 ms | 170 ms |
| Rerank | A cross-encoder reads Q1 beside each candidate and scores how well it answers. | The 8 best chunks | 180 ms | 350 ms |
| Assemble context | Instructions and citation rules, the 8 numbered chunks, then Q1. | 6,000 tokens: 8 × 600 of chunks, 1,200 of the rest | 50 ms | 400 ms |
| Model prefill | The model reads all 6,000 tokens before writing anything. | The first word of the answer | 600 ms | 1,000 ms |
| Decode | One token at a time, 30 ms each, streamed to the screen. | 400 tokens with [n] citations | 12,000 ms | 13,000 ms |
The 6,000 tokens are one way the budget adds up, using the 600-token chunk size that won in Probe 1. Now the bill for this one question, at the prices of the capacity ladder.
- Price the reading. 6,000 ÷ 1,000,000 × $3 = $0.018. Prices are quoted per million tokens, so divide the count by a million first.
- Price the writing. 400 ÷ 1,000,000 × $15 = $0.006.
- Add them. $0.018 + $0.006 = $0.024 for Q1.
- See which side dominates. $0.018 ÷ $0.024 = 75%. Reading is the cheaper price but the far larger count, so it is three quarters of the bill.
Q2 takes the short path. The first box finds Q1 in the cache at a similarity of 0.9846, above 0.92, and returns the stored answer whole at 50 ms. Nothing to the right of the cache runs.
- Auth and cache. The tenant filter is fixed before any search, so half the index is out of reach from the start. The same box checks the cache, which is empty at 9 a.m.
- The reranker. The costliest plumbing: 180 ms to read Q1 beside each of 50 chunks. It keeps the 8 that answer the question, and those 8 are all the model sees.
- Prefill. The model reads all 6,000 tokens before its first word: 600 of the 1,000 ms. A shorter context helps the bill and the clock at once.
- Decode. Twelve seconds of writing at 30 ms a token. The user reads as words arrive, so this is not what "slow" feels like, but the connection stays open for 13 seconds.
- The bill. Reading is $0.018 of the $0.024, which is why the levers in Fig. 17.3e cut context first.
- The hit. Q2 leaves at the first box with a stored answer, twenty times sooner and with no model call. The next question counts what that saves and risks.
One more number matters at the peak. By the rule of Fig. 17.1e, answers in flight = arrival rate × time each. With no cache, 52.0833 a second × 13.0 seconds = 677.1 answers streaming at once; with 35% hits, 52.0833 × 0.65 × 13.0 = 440.1. The gateway, its connection pool and the provider's rate limit must hold about 440 open answers at 9 a.m.
The honest limit: every stage time here is a budget. Real stages vary, and the slowest 5% of questions are not the slowest 5% of each box added up. Only the traces say which box is actually slow.
A question's first word waits for 400 ms of plumbing and 600 ms of reading. Its bill is mostly that reading. At the peak, about 440 answers are mid-stream at once.
Why put a cache in front at all? What does a 35% hit rate actually save, worked by hand, and what can go wrong?
Because employees ask the same things in different words, and the second asking should not pay for a model. At 35% hits the bill falls from $12,000 to $7,800 a day, which is $126,000 a month. The price is a new way to be wrong: a hit can hand one question the answer to another.
Picture tenant A's HR desk on the first Monday of January. By ten o'clock the carry-over question has come in five times, so the answer is on a note. The sixth person hears the note read out, with no trip to the handbook. The note is the cache; the trip is retrieval, reranking and a model call.
A semantic cache is that note, looked up by meaning. Each answered question is stored as a vector, a list of numbers standing for its meaning. If a new question's vector points almost the same way, the stored answer goes back.
The saving, by hand
- Count the hits. 500,000 questions a day × 0.35 = 175,000 answered from the cache.
- Count the misses. 500,000 − 175,000 = 325,000 go down the full path.
- Price the misses. 325,000 × $0.024 = $7,800 a day. The page's cost model counts a hit as free, because it is one embedding and one lookup.
- Subtract from the bill without a cache. $12,000 − $7,800 = $4,200 saved a day.
- Make it a month. $4,200 × 30 = $126,000 a month. This is the first cut in Fig. 17.3e.
- Take the load off the model. At the peak, 52.0833 × 0.65 = 33.85 questions a second still reach a model, instead of 52.08.
At 40% hits, the other end of the page's 30–40% range, the same steps give a $7,200 day: $144,000 a month saved, and 31.25 questions a second at the peak. Values from rerunning semantic_cache_by_hand.py.
Now the step people skip. The average wait falls by a third: 0.35 × 50 + 0.65 × 1,000 = 667.5 ms. The p95 does not follow it. p95 is the time 95 questions in 100 beat, so the slowest 5 in 100 set it.
Every hit takes 50 ms and every miss at least 1,000 ms, so those slowest 5 are all misses: the slowest 0.05 ÷ 0.65 = 7.7% of them. The 1.5-second target is still met, or missed, by the full path.
How the cache decides, by hand
Cosine similarity is the score that decides a hit. It measures how closely two vectors point the same way: 1 means the same direction, 0 means nothing in common. Real embeddings have 1,024 numbers that nobody can name. The four below are made up, so the arithmetic fits on one line.
| Question | About leave | About carrying over | About annual leave | About expense claims |
|---|---|---|---|---|
| Q1 annual leave, carry over | 0.8 | 0.5 | 0.3 | 0.0 |
| Q2 annual leave, rolls over | 0.7 | 0.6 | 0.3 | 0.1 |
| Q3 expense form | 0.0 | 0.1 | 0.0 | 0.9 |
| Q4 sick leave, carry over | 0.8 | 0.5 | 0.0 | 0.0 |
Q2 against Q1, the only question stored so far:
- Multiply matching numbers and add them. 0.8 × 0.7 + 0.5 × 0.6 + 0.3 × 0.3 + 0.0 × 0.1 = 0.56 + 0.30 + 0.09 + 0 = 0.95. This sum is called the dot product.
- Find Q1's length. √(0.64 + 0.25 + 0.09 + 0) = √0.98 = 0.9899, where √ (square root) undoes the squaring.
- Find Q2's length. √(0.49 + 0.36 + 0.09 + 0.01) = √0.95 = 0.9747.
- Divide the dot product by both lengths. 0.95 ÷ (0.9899 × 0.9747) = 0.9846. Dividing by the lengths compares direction only, so a long question and a short one can still match.
- Compare with the threshold. 0.9846 is at least 0.92, so Q2 is a hit. Q1's answer is right for it.
Q3 scores 0.0558 and misses, as it should. Q4 changes one word. Its dot product with Q1 is 0.8 × 0.8 + 0.5 × 0.5 = 0.89 and its length is √0.89 = 0.9434, so 0.89 ÷ (0.9899 × 0.9434) = 0.9530. That clears 0.92 too: an employee asking about sick leave is told the annual-leave rule.
- The bill, split. 175,000 of 500,000 daily questions come from the cache at no model cost; the other 325,000 cost $7,800. The gap to $12,000 is $4,200 a day.
- The wait. The average first word moves from 1,000 ms to 667.5 ms. The p95 stays where the misses put it, because the slowest 5 in 100 are all misses.
- The threshold. At or above 0.92 the stored answer goes back; below it the question takes the full path. Q2 and Q4 both clear it.
- The wrong hit. Q4 differs from Q1 by one word and scores 0.9530. It gets the annual-leave rule, and no later box runs to catch it.
- Raising the bar. At 0.96, Q2 still hits and Q4 misses; at 0.99 both miss and the saving shrinks. Choose the value on labelled question pairs.
What goes wrong, and what each fix costs
| Failure | In tenant A's morning | Fix | What the fix costs |
|---|---|---|---|
| Wrong hit on near-identical wording | Q4 gets Q1's answer at 0.9530 | Raise the threshold to 0.96 | Fewer hits, so a smaller saving |
| Stale hit | The carry-over policy changes at noon; Q1's stored answer cites the old version | Store the document versions each answer cited, and evict it when one changes, from the change feed of Probe 2 | Hits dip after every update |
| Cross-tenant hit | Tenant B types Q1 word for word and sees tenant A's policy | One cache per tenant, with tenant_id in the key, as in Probe 3 | Each tenant's cache fills on its own |
The honest limit: 35% is the page's assumption, and your traces set the real figure. A hit is not quite free either: the embedding and lookup sit inside the first 50 ms box. And every hit is an answer nobody checked again, which is why the alarms in Fig. 17.3h watch the hit rate.
A cache removes whole questions from the bill and from the model's load. It lowers the average wait, not the p95. Every hit is an unchecked answer, so key it by tenant and document version, and count its wrong hits.
In the interview, how do I choose between two designs out loud? Show me a side-by-side with numbers.
Put both designs in the same rows, fill every row with a number from your ladder, then name the requirement that decides and the number that would flip it. For Priya's prompt, the engineered design saves $282,000 a month at 100,000 users. At 1,000 users it saves $2,820, and the simpler design is the better call.
Interviewers often hand you the choice directly, for example by asking why every question should not go to the best model. "B is more scalable" gives them nothing to write down. Both designs in the same rows gives them the decision and its price, in five steps.
- Name each design in one line. So both sides know what is being compared.
- Choose the rows before filling them. Cost, load, latency, new ways to be wrong, what must be proven, what must be run: the same rows for both.
- Put a number in every cell. A cell holding a word is a cell you will be probed on.
- Say which stated requirement decides. One Priya gave in the first five minutes, not a preference.
- Say the number that would flip your choice. It shows judgement rather than a favourite.
| Row | Design A: the board as first drawn | Design B: cache, 5 chunks, router |
|---|---|---|
| In one line | Every question: 8 chunks, 6,000 tokens, the frontier model | 35% answered by the cache; misses get 5 chunks, 3,000 tokens, and 70% go to the cheap model |
| Monthly bill | $360,000 | $78,000 |
| Cost of a question that reaches a model | $0.024 | 0.7 × $0.005 + 0.3 × $0.015 = $0.008 |
| Cost averaged over every question | $0.024 | 0.65 × $0.008 = $0.0052 |
| Questions a second reaching a model at the peak | 52.08 | 33.85 |
| First word on a miss | 1,000 ms | 700 ms on the frontier model (prefill 600 → 300 ms); the cheap model must be timed. A hit: 50 ms. |
| New ways to be wrong | None added | Wrong cache hits; a needed chunk ranked 6th to 8th is dropped; the cheap model misreads a hard question |
| What must be proven before it ships | The golden-set gate | The gate with each lever on, faithfulness still at least 0.90, plus a wrong-hit test |
| Extra parts to run | None | A cache keyed by tenant and document version, a router, a tuned threshold |
Step 4. Two requirements from the prompt pull against each other. Cost per query is a first-class target, and wrong answers carry a compliance cost. Design B wins the first by $282,000 a month. It is allowed only if the quality bar still holds with each lever switched on.
Step 5: the number that flips it
Run the same two designs for a much smaller customer. Nothing changes except the user count.
- Questions a month at 1,000 users. 1,000 × 5 × 30 = 150,000.
- Design A's bill. 150,000 × $0.024 = $3,600.
- Design B's bill. 150,000 × 0.65 × $0.008 = $780. The 0.65 is the share that misses the cache.
- The saving. $3,600 − $780 = $2,820 a month.
- Something to weigh it against. The bottom of the US band in Fig. 17.5c is $187,000 a year, so one month of that pay is $187,000 ÷ 12 = $15,583. Then $2,820 ÷ $15,583 = 0.18 of one month's pay.
The same steps at 10,000 and 100,000 users save $28,200 and $282,000 a month, and Fig. 17.3k draws all three scales. Design B always costs 21.7% of Design A ($0.0052 ÷ $0.024). The ratio never moves; the dollar gap grows a hundredfold while the work of running a cache and a router stays about the same. That is the whole flip.
- At 1,000 users. The saving bar stops short of the dashed line: $2,820 a month, 0.18 of one month's pay. The cache and router still need building and watching, so Design A wins.
- At 10,000 users. The saving, $28,200, crosses the line at 1.81 months of pay. Between these two rows the engineering starts to pay for itself.
- The line. One month of pay at the bottom of Fig. 17.5c's US band, $15,583: a yardstick, not a price. An engineer costs an employer more than pay, which moves the crossover to more users.
- The same gap in every group. On a log axis equal distances are equal ratios, and B costs 21.7% of A at every scale. The ratio is fixed; the dollars grow a hundredfold.
Said out loud: "At 100,000 users I build B. It saves about $282,000 a month, and each lever ships only through the golden-set gate. At 1,000 users I ship A and collect traces, because the saving is under a fifth of one engineer's monthly pay. I switch when the saving beats the cost of keeping the cache and router honest."
The honest limit: Design B's column rests on three assumptions: the 35% hit rate, the 70% share a cheap model can handle, and "no quality loss". Say them as assumptions until your traces and golden set confirm them.
Same rows for both designs, a number in every cell, one requirement that decides, one number that flips it. That is how a design choice sounds in the round.
The stack, and why
Before the second example, here is the reference stack for a GenAI board: the boxes you draw when the interviewer says “design a document Q&A service”, what sits in each, and what you would pick instead if asked “why not X?”.
The stack, and why
The one question that decides each box: what is the smallest thing that meets the quality bar and the bill, and what number would make you replace it? (As of November 2026.)
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Gateway | A thin LLM gateway in front of the models, such as the LiteLLM proxy (Module 12; it is not drawn on Fig. 17.3) | Portkey, Cloudflare AI Gateway, calling the provider SDK directly | One place for keys, budgets, provider fallback and cost logging. Weakness: one more hop (a few milliseconds) and one more service to keep up. | Call the provider directly while you have one provider and under about 1,000 requests a day; add the gateway at the second provider or the first budget dispute. |
| Models | claude-sonnet-5 for hard questions, claude-haiku-4-5 for easy ones, routed cheap-first (the prices in doc_qa_cost_model.py) | OpenAI or Gemini models, an open-weight model served by vLLM | Two tiers let you pay frontier prices only where the question needs it. Weakness: a router can send a hard question to the weak model, so it needs the golden-set gate. | Self-host an open-weight model when data may not leave your network, or when steady traffic passes roughly the point where a rented GPU costs less than the API bill (work it out with the cost model). |
| Vector store | pgvector inside Postgres, dense plus BM25, tenant_id on every row | Qdrant, Pinecone, Milvus, OpenSearch | Vectors live next to the permissions and business data, so one filter and one backup cover everything. Weakness: slower than a dedicated engine at very large size. | A dedicated vector database past about 10 million chunks per index, or when p99 search must stay under 20 ms; Pinecone when nobody on the team will run a database. |
| Semantic cache | A cache keyed on embedding similarity (semantic_cache_by_hand.py) | Exact-string cache in Redis, a provider’s prompt caching, no cache | Catches reworded repeats, so 30–40% of questions skip the model on this board. Weakness: a too-loose similarity threshold returns the wrong stored answer. | Exact-string caching when most questions are canned or templated; drop the cache when the golden set shows it returns wrong answers more than 1 time in 100. |
| Queue | A durable queue between the change feed and the embedder (the board draws the box and names no product; Kafka is the log used in the fraud board, section 04) | Amazon SQS, RabbitMQ, Redis Streams, no queue | Re-embedding a large file takes minutes, so it must not block the upload and must survive a crash. Weakness: you now own retries, duplicates and a dead-letter queue. | SQS when you are on AWS and only need “process each file once”; Kafka when several consumers need to replay the same events; no queue under about 100 documents a day. |
| Observability | Langfuse traces on every call | LangSmith, Arize Phoenix, OpenTelemetry with your existing tracing backend | Open source and self-hostable, and it shows each stage’s latency and cost per request. Weakness: it is a second system next to your normal logs; ClickHouse bought it in January 2026, so check its roadmap before you commit. | OpenTelemetry into your current backend when the company already pays for one and wants a single place to look. |
| Evals | Ragas plus a judge checked against human labels, with a promptfoo gate in CI (eval_rag.py) | DeepEval, LangSmith evals, hand-graded spreadsheets | Turns “it feels better” into numbers that block a bad change. Weakness: a judge model has its own biases and needs checking against people. | Hand grading while the golden set has fewer than about 50 questions; the automated gate once more than one person changes prompts. |
On the whiteboard, name the default for each box in one breath, then say the number at which you would swap it, because “why not X?” is the follow-up you are actually graded on.
Worked example B — "Design an agent platform for internal automation"
Priya's colleague takes the 1:00 slot and changes the prompt: SaaSify wants its employees to automate internal workflows with agents that file tickets, chase approvals and draft pull requests. The seven steps still hold, but the risk moves from a wrong answer to a wrong action, and a refund the agent already issued is much harder to take back than a policy it misquoted. Sketch depth is enough in this round. What it grades is where you put the human, and what you keep a record of.
The second-most-common GenAI prompt, and it's Modules 09 and 10 on one board. The ask:
"SaaSify wants employees to automate internal workflows — file tickets, chase approvals,
draft PRs — with AI agents. Design the platform." Sketch depth is enough here; the seven
steps compress to five decisions: (1) Orchestration — a LangGraph
StateGraph with checkpointing, so runs are resumable and every step is
inspectable (say why not a free-running loop: bounded, auditable state beats vibes).
(2) Tool registry via MCP — tools live in MCP servers owned by their teams (Jira server, GitHub server, read-only SQL server), so the platform discovers capabilities instead of hard-coding integrations, and new tools ship without redeploying the agent.
(3) HITL gates — LangGraph's interrupt() pauses the graph
before any side-effecting call; a human approves the write, the graph resumes from its
checkpoint. (4) Audit — an append-only log of every tool call, argument,
and approval, because "who approved this refund?" is a question you will be asked.
(5) Evals — replay real traces against task-success criteria before any
prompt or tool change ships (Module 07's harness pointed at agent trajectories).
- The gate is the design. Reads run freely; anything that changes the world stops here and waits for a person. The graph is checkpointed, so the pause costs nothing and the run resumes exactly where it stopped once someone approves.
- The registry, not the integrations. Each team owns the tool server for its own system, and the platform discovers what is available instead of hard-coding a client for each one. A new tool ships without redeploying the agent.
- The log is the answer to the question you will be asked. Every tool call, every argument and every approval, append-only. "Who approved this refund?" has to be answerable months later, and no amount of tracing replaces a record that cannot be rewritten.
The probes here are predictable: "what stops the agent looping forever?" (step budget + checkpointed state + cost ceiling per run), "what if a tool is compromised?" (least-privilege scopes per MCP server, read-only by default, the HITL gate on writes), and "how do you know a prompt change didn't break existing automations?" (trace replay in CI — the same eval answer as always, because in 2026 every "how do you know" answer is an eval answer).
06 · Shipping modelsDeployment Strategies & A/B Testing
Minute 35 of Priya's round, and she asks the question every deep-dive ends on. Your new prompt scores better on the 120-question golden set, so how does it reach 500,000 questions a day without betting the product on it? This is where a candidate either names four rollout strategies with what each one costs, or says "we would deploy it" and loses five minutes of the clock. Four strategies, their prices and the one sentence that defends each choice are next.
Both boards above end the same way: a new model or prompt exists — how does it reach traffic without betting the company? You have four standard strategies plus the bandit refinement, and interviewers love asking you to pick one and defend it.
- Shadow: no risk, no evidence about people. The new model sees every request and answers into a log that nobody reads at the time. You learn how it behaves on real inputs and nothing at all about how users react to it, and you pay for inference twice.
- Canary: the default. Five percent of live traffic, held for a day or two, compared on the metrics that matter, then widened to twenty-five and a hundred. Small blast radius, real behavioural evidence, and a rollback that is a configuration change.
- Blue-green: rollback in one flip. Two complete environments, one live, one warm and idle, and a router between them. You buy instant reversal with twice the infrastructure, which is the right trade for payments and the wrong one for a side feature.
- Interleaving: for ranking only. Both models' results are mixed into one page and the clicks say which model's items won. It needs far less traffic than a split test to reach a conclusion, and it cannot be used on a generated answer, which has no items to interleave.
| Strategy | Choose when | Avoid when | Typical cost |
|---|---|---|---|
| Shadow | New model class, unknown failure modes; you need production-shaped evidence with zero user risk | You need behavioral evidence (clicks, conversions) — shadow can't see user reactions | 2× inference, 0 user risk |
| Canary | Default for most model and prompt rollouts; real evidence, bounded blast radius | Effects too small to detect at 5% traffic in days | Small risk on 5% of users |
| Blue-green | Rollback speed is everything (payments, healthcare); infra changes ship with the model | Budget can't carry two full environments | 2× infra during the switch |
| Interleaving | Ranking systems — mixes both models' results on one page; very sample-efficient | Non-ranking outputs (a generated answer can't be interleaved) | Complex attribution logic |
| Bandit (UCB/Thompson) | Several variants and a direct reward signal; you want minimum regret, not a report | Rewards are delayed or diffuse (fraud labels at 90 days make bandits slow) | Engineering complexity |
Feel the bandit mechanism once and you'll never fumble the follow-up — this simulation is the router from Fig. 17.2 in forty lines:
Step-by-step: what ucb_bandit_router.py does, in plain English
- Import numpy and create a random number generator with a fixed seed, so every run produces the same sequence and the output is reproducible.
- Set the true accuracy of each model: 71% for the champion, 74% for the challenger. The router never reads this dictionary. It is the hidden truth the simulation draws rewards from.
- Create two bookkeeping dictionaries keyed by model name:
pulls, how many requests each model has served, andreward, how many of those decisions were later confirmed correct. - Define
ucb_score(arm, t, c). If a model has never been chosen, return infinity, so every model is tried at least once before any statistics matter. - Otherwise compute the model's observed mean reward, then add a bonus of
ctimes the square root ofln tdivided by its pull count. The bonus is large for a model with few pulls and shrinks as evidence accumulates;csets how adventurous the router is. - Loop over 20,000 requests. On each, pick the model with the highest UCB score, count the pull, and draw a reward: 1 if a random number falls below that model's true accuracy, otherwise 0.
- After the loop, print each model's share of traffic and its observed accuracy. The challenger should hold most of the traffic and its observed accuracy should sit close to 0.74, with no human having flipped a switch.
# pip install numpy==2.1.*
# UCB1 router: the challenger EARNS traffic as evidence accumulates.
# Reward = 1 when the routed model's decision is later confirmed correct.
# (Real fraud labels arrive months late; the simulation collapses that delay.)
import numpy as np
rng = np.random.default_rng(7)
TRUE_ACCURACY = {"champion": 0.71, "challenger": 0.74} # unknown to the router
arms = list(TRUE_ACCURACY)
pulls = {a: 0 for a in arms}
reward = {a: 0.0 for a in arms}
def ucb_score(arm, t, c=1.2):
if pulls[arm] == 0:
return float("inf") # every arm gets tried before stats matter
mean = reward[arm] / pulls[arm]
bonus = c * np.sqrt(np.log(t) / pulls[arm]) # uncertainty pays a bonus
return mean + bonus
for t in range(1, 20_001):
arm = max(arms, key=lambda a: ucb_score(a, t))
pulls[arm] += 1
reward[arm] += float(rng.random() < TRUE_ACCURACY[arm])
total = sum(pulls.values())
for a in arms:
print(f"{a}: {pulls[a] / total:.1%} of traffic, "
f"observed accuracy {reward[a] / pulls[a]:.3f}")
# The 3-point-better challenger ends up with the overwhelming majority of
# traffic — no human flipped a switch, and regret grew only logarithmically.
07 · The new roundThe AI-Enabled Coding Round
The design round ends at 10:45 and the loop moves on. At 2:00 you sit the round that did not exist the last time you looked for a job: you solve a coding problem with an AI assistant in front of you, and Priya's debrief in Fig. 17.0b counts it as one of her three failure places. Candidates lose it in two opposite ways, and neither has anything to do with whether the code runs. This section is the protocol that sits between them.
Meta added a round where you solve a coding problem with an AI assistant — and other companies are copying it, because it measures the job as it's actually done (90% of professional developers use AI tools daily). The trap is misreading what's graded. You are not graded on whether the code works — the assistant can usually get there. You are graded on direction (did you decompose the problem, set constraints, and steer?) and verification (did you test, read the diff like a reviewer, and catch the model's mistakes?). Refusing the assistant reads as untrainable; accepting its output unread reads as dangerous. Both fail.
The practice protocol — the Module 15 workflow under a clock:
- Spec first: restate the problem, constraints, and edge cases to the assistant before asking for code — out loud, so the interviewer hears the decomposition.
- Small hunks: request one function or one layer at a time; never "write the whole thing."
- Read every diff like a code review — narrate what you're checking ("this handles the empty case, but I don't trust the off-by-one here…").
- Verify before trusting: write or request tests, run them, and probe the edge case you named in the spec. Evaluators deliberately note whether tests come before or after acceptance.
- Catch a model error on purpose: the strongest observed signal is the candidate who says "that's wrong, because…" and fixes course. Practice until you catch one per session.
- Own the result: be able to explain every line you ship. "The AI wrote it" is an automatic fail.
There are no dumb questions
- I've never operated at 10K TPS or 100K users. How do I answer scale questions honestly?
- Reason, don't résumé. "Here's what I'd change at 10× traffic: a Redis feature cache, horizontal autoscaling, a feature store to kill training-serving skew" is a legitimate senior answer — interviewers grade the reasoning, not your former employer's traffic. Your course labs are real systems with real measurements; scale them out loud.
- Do interviewers actually expect the seven steps by name?
- No — they expect coverage. The framework is scaffolding so you never leave a silent hole (metrics with no business family, a design with no monitoring). Announce your map in your own words; nobody is grading step numbering.
- What if I don't know a number — a price, a latency, a hit rate?
- Estimate out loud and label it: "Order of magnitude, assuming roughly $3 per million input tokens as of mid-2026…" A stated assumption plus clean arithmetic beats a confident guess and destroys a vague shrug. If you're fully off the map, say what you'd measure and how.
- My "production experience" is this course's labs plus side projects. Does that count?
- Deployed + measured + documented counts. A RAG service with a CI eval gate, traced costs, and twenty real users is more production experience than a tutorial at a big-name employer. Present it with metrics and failure modes — the vocabulary of operation, not the vocabulary of tutorials.
- The interviewer pushes back on my design. Fold or fight?
- Neither — trade off. "You're right that blue-green doubles infra; I chose it because rollback speed dominates cost for a payments path. If budget is the binding constraint, canary is the better call." Updating on new information without abandoning your reasoning is precisely the senior signal the pushback exists to test.
08 · BehavioralSTAR and the Three Stories
At 3:00 the hiring manager stops asking about systems and starts asking about people. This is the round your nine years should win outright, and it is lost by engineers who answer with architecture when the question was about an outcome. The fix is the same one that worked on Priya's whiteboard: attach a number. A story that ends at "and then we shipped it" scores like a design with no arithmetic on it.
Behavioural rounds are postmortems performed live, and STAR is the writeup format.
- Situation — "our recommendation engine had a 2% click-through rate…"
- Task — "I owned raising personalization CTR 50% in a quarter…"
- Action — "I built a two-tower retrieval model, a Feast feature store, and an interleaving test…"
- Result — "CTR hit 3.8%, a 90% lift worth $1.2M in annual revenue."
Prepare eight to ten stories. But for senior GenAI roles three of them are effectively mandatory, because screeners now probe for each explicitly:
| Story | Modules that arm it | Numbers it must contain |
|---|---|---|
| A production AI failure and the eval-driven fix — hallucination incident, injection near-miss, silent quality decay; what you built so it can't recur | 07 · 12 | Failure rate before/after; eval metric (e.g., faithfulness 0.71 → 0.94); the CI gate that now blocks regressions |
| A cost-optimization win — the bill that shocked someone, the levers you pulled, the quality you proved you kept | 12 | $ before/after (e.g., $46K → $19K/month); the levers (semantic cache, routing, prompt caching); the eval that proved no quality loss |
| A stakeholder-translation moment — an exec's vague ask ("can we use ChatGPT for this?") turned into a scoped, measured, shipped decision | 16 | The ROI frame you presented; the build-vs-buy call; adoption or business outcome after shipping |
Each of those three rows is a before-and-after with a number on both ends. Drawn, the shape of a senior story is obvious, and so is the reason a story without numbers cannot be scored — it has a beginning and no end.
- R is the only block anyone remembers. Situation, task and action set up one sentence: the measured change and what it was worth. A story that stops at "and we shipped it" gives the interviewer nothing to write in the debrief.
- Story one is about the failure, not the fix. Screeners ask for a production AI failure because they want to hear you describe being wrong. The number that matters is the pair — 0.71 before, 0.94 after — plus the gate that makes the fix permanent.
- Story two is the arithmetic story. It is the behavioural version of the round you just sat: a bill that shocked someone, the levers you pulled, and the evidence that quality survived. Bring the before and after in dollars a month.
- Story three is translation, not modelling. The skill being tested is turning a model metric into a business sentence. Same model, same score, one version lands in a boardroom and the other does not.
And keep the executive-summary discipline from Module 16 for the delivery itself. Don't say: "We achieved a ROC-AUC of 0.94 using an XGBoost ensemble with 150 estimators." Say: "Our model correctly flags 94% of customers who will churn, letting us intervene two weeks before they cancel — projected at $380K in retained annual revenue." Lead with impact; surface hyperparameters only when asked. Executives — and interviewers playing them — care about dollars, latency, and risk.
Here's the module's reframe: an interview IS a boardroom translation exercise. Every answer in every round should connect architecture to cost, risk, and user outcome — "hybrid retrieval plus a reranker" is a mid-level answer; "hybrid retrieval plus a reranker, which is where answer quality comes from, costs six points of latency, and cuts our hallucination exposure on compliance queries" is a senior one. That habit — ending every technical decision with its business consequence — is the actual line between senior and staff in a debrief, and you've been drilling it in every module's boardroom box since Module 00. The interview is just the exam you already studied for.
09 · PortfolioThree Deep Projects
Rewind two months, to the part of the story that happens before interview day. None of Priya's thirty loops began with a whiteboard; each began with a hiring manager reading a repository and deciding to spend an hour. She screens for three signals — measured metrics, named failure modes, a demo that runs — and three deep projects beat ten shallow ones every time. You have already built all four of the patterns she looks for, so this section is about making them readable in five seconds.
The market research is unambiguous: three exceptional projects demonstrating depth outperform ten shallow tutorial implementations. Hiring managers pattern-match in seconds — a repo with real metrics, named failure modes, and a live demo reads as "production scars"; twelve half-finished clones read as tutorial tourism, whatever the green squares say. Four project patterns carry the 2026 market, and you have already built all four in this course — the lab work was the portfolio all along:
| Pattern | Course lab it extends | What it proves | Headline metric |
|---|---|---|---|
| RAG service with evals in CI | Lab 08 + Lab 07's harness | Retrieval judgment and the #1 differentiator: shipped evals with measurable outcomes | Faithfulness 0.94 on a 120-question golden set |
| Multi-tool agent with observability | Lab 09 | Orchestration, HITL judgment, and trace-level debugging | Task success rate across replayed traces |
| Fine-tune with a cost-benefit sheet | Lab 11 | The rarest proof: "widely claimed, rarely proven" — a QLoRA model that beats the API option and shows the math | Quality delta + $/1K requests vs the API baseline |
| MCP server, published | Lab 10 | Fluency in the fastest-rising named skill (17–24% of agentic postings, named in Goldman's VP JD) | Installs / integrations + tool-call latency |
Round the set out with Module 12's LLMOps artifacts — the gateway with provider fallback and cost tracking, the guardrail layer logging injection attempts, the semantic cache with measured savings — folded into the projects above rather than standing alone. Then make every README carry its weight. The template below is the upgraded version of what hiring managers scan for; the difference from 2024 is that metrics, failure modes, and an architecture diagram are now mandatory, and a demo link beats a thousand words:
Step-by-step: what each section of README_template.md does, in plain English
- Title and one-line pitch: what the project does in one sentence, then the three things a hiring manager scans for in the first five seconds: a quality score, a cost per query and a demo link.
- Problem: who is hurt, what it costs them, and why a generic chat product fails at it. Two sentences, no back-story.
- Architecture: one image and two sentences naming the mechanism (hybrid retrieval, reranker, model, guardrails, cache). A design note in
docs/holds the rest. - Results table: each metric with its value and how it was measured. The third column is what separates a measured number from a claimed one.
- Failure modes: three things that broke, each with the fix. This is the section most templates leave out and the one interviewers read first.
- Evals: the command that replays the golden set, the CI threshold that blocks a regression, and the judge's agreement with human labels, so the reader knows the score can be trusted.
- Run it: one command. If it takes more than one, the reader stops here.
# PolicyPal — Document Q&A with Evals in CI
One-line pitch: grounded answers over 12K policy documents.
94% faithfulness · $0.008/query · live demo: (link) · 90-sec video: (link)
## Problem
Who hurts, what it costs them, why generic chat fails. Two sentences, no lore.
## Architecture

Hybrid retrieval (pgvector dense + BM25) → BGE reranker → claude-sonnet-5
behind guardrails, semantic cache in front. Full design note in docs/.
## Results — measured, not vibes
| Metric | Value | How measured |
|-------------------------|--------|-------------------------------------|
| Faithfulness (Ragas) | 0.94 | 120-question golden set |
| Answer relevancy | 0.91 | same set |
| p95 TTFT | 1.2 s | k6 load test at 50 rps |
| Cost per query | $0.008 | 30-day traced average (Langfuse) |
| Semantic cache hit rate | 34% | production traces |
## Three failure modes I found (and fixed)
1. Table answers hallucinated → layout-aware parsing + table-scoped chunks.
2. "Latest policy" served a 2023 doc → recency boost + stale-index alarm.
3. Prompt injection via uploaded PDF → input scanning + grounding check on output.
## Evals
`make eval` replays the golden set; CI fails any PR that drops faithfulness
below 0.90. Judge prompt validated against 40 hand-labeled answers
(agreement: 0.88 Cohen's kappa) — see eval/.
## Run it
docker compose up # then open http://localhost:8000
Two closing verdicts from the research. Public signal: write-ups beat green squares — one honest post per project ("what broke, what I measured, what I'd change") plus a contribution to the eval/agent ecosystem outweighs any contribution graph. Certifications: garnish, not substance. AWS ML Specialty is near-required in India's AWS-heavy services sector; GCP Professional ML Engineer and Azure AI-102 (AI-103 after June 2026) help at cloud-aligned shops; IAPP AIGP is genuinely differentiating for the governance track (25–35% premium). But vendor-neutral online certificates without artifacts are ignored — a certification can decorate a portfolio; it cannot replace one.
10 · TargetingWhere to Aim, What to Ask For
The offer call is the last event in this story, and most of the number on it was decided months earlier, by which company you applied to. TrustBank's band is one point on a wide map: $187K to $457K in the United States at the top tier, and in India a 60 to 150 percent difference between a product company and a services firm for the same nine years. Priya can move an offer within her band; she cannot move you to a different band. This section is where you aim.
From the market map: at 9 YOE you fit four archetypes.
GenAI App Engineer is the fastest transition (your SWE depth is the moat); AI Solutions Architect leverages seniority and system-design strength; Staff MLE demands the most retooling (PyTorch internals, inference optimization); the consulting track enters at Manager level and pays for exactly the hybrid "codes the PoC, presents to the CIO" profile Modules 15 and 16 built.
Anchors for negotiation: US senior GenAI runs $187K–$457K median TC at the top tier, agentic-AI postings median $213K, and AI skills carry a 28% premium (43% with two or more).
In India, the single biggest comp lever is not negotiation tactics — it is which company type you target: the product-vs-services gap at equal experience is 60–150%, which means a Bengaluru product company at ₹40–70+ LPA versus the same résumé at a services major for a fraction. Aim your three deep projects at product companies first.
- The band is wide, and you sit somewhere in it. Two hundred and seventy thousand dollars separates the ends of the American band for the same job title. Which end you land on is set by the loop you just rehearsed, and by knowing the number before the recruiter asks.
- The services position. Roughly ₹16–25 lakh for nine years of the same work. Nothing you say in a negotiation closes this distance, because it is a different market, not a different offer.
- The product position. ₹40 lakh and up for the same résumé. This is why the targeting decision outranks every negotiation tactic in the module, and why the three portfolio projects should be aimed at product companies first.
Finally, know what your vocabulary signals. Interviewers calibrate seniority partly by which era your stack words come from:
| Reads as 2026 (signal) | Reads as 2024 (red flag) |
|---|---|
| MCP tool servers; agent-to-agent orchestration | "I integrate APIs with custom wrappers for each tool" |
| LangGraph state machines with checkpointing and interrupt() | AgentExecutor / initialize_agent / LLMChain (deprecated — deprecation radar!) |
| Validated LLM-as-judge, eval gates in CI | "We eyeballed outputs and they looked good" |
| Semantic caching, model routing, token economics | "We call GPT for everything" |
| Hybrid retrieval + reranking, measured on a golden set | "LangChain + Pinecone + similarity search" |
| Guardrails, injection defense, tenant isolation below the model | "The system prompt tells it to be safe" |
11 · The labFull Dress Rehearsal
You have now watched the whole of interview day, from Priya's 10:00 prompt to the offer call, from the other side of the glass. Watching is not rehearsal, and the difference between the two boards in Fig. 17.3g is entirely a matter of having said these things out loud before. The lab runs the same day again with you doing all of it: a cold 45-minute board, a timed session with an AI assistant, and three portfolio READMEs published. Do it once under the clock and interview day is a repeat performance.
Mission: run the entire loop once under exam conditions, then ship the portfolio that backs it. Three parts. No skipping part 3 — it's the deliverable recruiters can actually see.
- Part 1 — Solo design round: whiteboard "design an enterprise document Q&A service" in a timed 45 minutes, cold, without reopening this page. Photograph the board.
- Self-score against the worked example: all 7 steps present, at least one number attached to every step, and written answers to all four probes (chunking, staleness, tenancy, cost). Pass bar: 80% — redo in full if below.
- Part 2 — AI-Enabled practice session: pick one course lab repo and add a real feature with an AI assistant in 45 minutes (e.g., add a reranker-comparison eval to Lab 08), narrating aloud per the Module 15 protocol.
- Session evidence: every accepted diff is covered by a test you ran before accepting, and you caught + corrected at least one assistant mistake on the recording.
- Part 3 — Portfolio final: choose your 3 deep projects (must include one RAG-with-evals and one agent/MCP project), write all three READMEs to the template, and publish with working demo links.
- Measurement criterion: every README shows ≥4 measured metrics including one eval score and one cost figure, plus 3 documented failure modes with fixes.
- Write and rehearse the 90-second "walk me through your best project" script: problem → architecture in two sentences → the headline metric → the failure you found → the business number. Record one take.
Stretch goal: run the agent-platform prompt (worked example B) as a second timed round with a peer playing interviewer — and have them probe cost and security until you stall, then patch the stall.
Two rounds in a top-company loop sit outside this course's scope. The classic distributed-systems design round ("design a rate limiter") — refresh it with Appendix A2, which also maps every concept back to the AI systems you built in Modules 08–12. And the algorithms/DSA round — still opens most FAANG-tier loops; run a NeetCode-150-style track alongside Acts II–III (~6–8 weeks). Nine years of experience carries the behavioral and traditional-architecture rounds; these two still reward deliberate practice.
12 · The meta-radarTen Questions, One Course
Every module ended with a radar; this one is the meta-radar: the ten questions to be ready for across the whole loop, each pointing back to the module that answers it. It doubles as the course's final review index — any row you can't answer from memory is your reading list for the week before the loop.
| The question | Answered in | Strong-answer seed |
|---|---|---|
| "Design a document Q&A / RAG service for [domain] — and defend your chunking." | 08 · Production RAG | Fig. 17.3 + eval-measured chunking, hybrid + rerank, tenant filter below the model |
| "How do you know your LLM feature works?" | 07 · Evals | Error analysis → golden set → code asserts → validated judge → CI gate; never "we eyeballed it" |
| "Design an agent that files tickets / automates a workflow. Where do humans sit?" | 09 · Agentic AI | Fig. 17.4: checkpointed graph, interrupt() before writes, audit log, step budgets |
| "What's MCP, and why a tool server instead of hard-coded functions?" | 10 · MCP | Discovery over integration: teams own servers, agents discover capabilities, no redeploys |
| "When would you fine-tune instead of RAG or prompting?" | 11 · Fine-Tuning | Never for knowledge (RAG), never for format (structured outputs); yes for style/domain behavior at volume — with a cost-benefit sheet |
| "Your LLM bill hit $80K/month. Walk me through cutting it." | 12 · LLMOps | The Probe-4 arithmetic: semantic cache, routing, prompt caching, context trims — quality proven by evals |
| "When would you NOT use OpenAI's API?" (vendor-agnostic judgment) | 06 · 12 | Data residency, latency floors, unit economics at volume, capability parity — then vLLM/open models with the migration path |
| "Explain bias-variance — and why XGBoost still beats an LLM on tabular churn." | 02 · 03 | Classical ML is still the baseline expectation; trees exploit tabular structure LLMs can't see |
| "Prompt injection: attack and defense, in an enterprise doc-Q&A product." | 12 · 14 | OWASP #1 LLM risk; poisoned-document path; defenses below the model: scanning, grounding checks, least privilege, red-team evals in CI |
| "Tell me about a production AI failure and what you changed." (behavioral) | 07 · 12 | Story #1 from the behavioral table: incident → eval harness → CI gate → metric before/after |
Quick reference — System design and interviews
- The seven steps
- Problem → metrics → data → features → modelling → serving → monitoring. Say them out loud and then walk them; the structure is half the grade.
- Name the default, then the swap number
- For every box on a GenAI board say what you picked and the number that would change your mind: pgvector until about 10 million chunks, a gateway at the second provider, a semantic cache until it returns wrong answers more than 1 time in 100.
- Start with the metric
- Before any architecture, state what you are optimising and how you would know it worked. Candidates who start at the model lose the round here.
- Delayed labels
- Fraud and churn labels arrive days or weeks later. That shapes training, evaluation and monitoring — and mentioning it unprompted marks you as senior.
- training-serving skew
- Features computed differently in training and in production. The most common cause of a model that scored well and then did not work.
- Throughput vs latency
- Throughput is how many requests finish per second; latency is how long one takes. Requests in flight are the two multiplied: 10,000 a second × 15 ms = 150.
- p99
- The latency that 99 requests in 100 beat. A worker pool run near 100% busy keeps its throughput and loses its p99.
- Precision vs false-positive rate
- Precision divides by what was flagged; the false-positive rate divides by every legitimate case. When fraud is rare, precision is the stricter target.
- Semantic cache
- Returns a stored answer when a new question's vector is close enough, cosine 0.92 or more. At 35% hits it saves $126,000 a month; key it by tenant and document version.
- What loses the round
- No numbers, and no failure modes. Two things that cost nothing to add and that most candidates omit.
- The two AI rounds
- GenAI system design (design a RAG or agent system) and the AI-enabled coding round (code with an assistant, while explaining your judgement).
- Portfolio that works
- An architecture review, a postmortem writeup, and something running in a staging environment. Not a notebook.
13 · RecapWhat You Can Do Now
- You can run a 45-minute ML or GenAI system design answer on the 7-step framework — announcing the map, attaching a number to every step, and steering depth where the interviewer points.
- You can design and defend an enterprise document Q&A service through the four real probes: chunking, index staleness, tenant isolation, and cost at 100K users.
- You can sketch an agent platform with MCP tool discovery, HITL gates, audit, and trace-replay evals — and answer the runaway-loop and compromised-tool probes.
- You can choose shadow, canary, blue-green, interleaving, or a bandit for a rollout from the decision table and defend the choice with its cost and evidence tradeoffs.
- You can speak the serving vocabulary with the arithmetic behind it: KV cache memory math, TTFT vs TPOT, continuous batching, semantic caching.
- You can trace one question through the board with the milliseconds and cents each box adds, and say how many answers are streaming at once at 9 a.m.
- You can compare two designs in the same rows with a number in every cell, and name the scale at which the choice flips.
- You can pass an AI-Enabled coding round: spec first, small hunks, tests before trust, and catching the assistant's mistakes out loud.
- You can tell the three senior stories — eval-driven fix, cost win, stakeholder translation — in STAR form with real numbers.
- You can ship a three-project portfolio with metrics, failure modes, and demos, target product companies with 2026-current vocabulary, and negotiate from market data.
From this module: redraw Fig. 17.3 (the doc-Q&A board) from memory, then write one-sentence answers to all four probes without looking. Reaching back to Module 07: your doc-Q&A judge agrees with humans 65% of the time — do you trust the CI gate it powers? What was the validation protocol from Module 07, and what's the minimum agreement you'd accept before letting that judge block releases?