▚ The AI Engineer's Field Manual
Module 17 · Act IV — Production & the Business

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

~8 hours Builds on: everything — especially 07–12, 15, 16 Tools: whiteboard · timer · your GitHub Job-spec line it unlocks: "multi-agent orchestrations, MCP tool servers, RAG pipelines, and LLM-as-judge evaluation frameworks"

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.

Field report · Hiring debrief

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

— Priya Raman, Director of Engineering at "TrustBank"

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.

1 THIRTY LOOPS THIS QUARTER 27 no-hire — each one fell in one of the three places at right 3 reached her bar: one candidate in ten 2 of those 3 signed, at the top of the band 2 a framework list instead of a system the probe that finds it: so what did you just design? 3 cannot defend a chunk size past the second follow-up the probe that finds it: why 512? 4 refuses the AI assistant, or accepts its code unread the probe that finds it: the AI-Enabled coding round 5 designs the system, prices it at 100,000 users, and says what breaks first — unprompted
Fig. 17.0b — Priya's quarter, drawn. Thirty loops, twenty-seven no-hires in three named places, three candidates at the bar and two offers signed. Everything in this module exists to move you out of markers 2, 3 and 4 and into marker 5.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

You already know this

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.

Recruiter screen story · comp band Coding DSA · SQL 2 AI-Enabled coding verify, don't vibe 1 System design 45–55 min Behavioral STAR stories Domain / business metrics · ROI traditional ML system 3 GenAI system
Fig. 17.1 — The 2026 senior-AI loop. The system-design round now comes in three flavors; the GenAI flavor is the newest, the least practiced by candidates, and this module's centerpiece. The AI-Enabled coding round (Meta, spreading) is graded on direction and verification.
  1. 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.
  2. 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.
  3. 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.

The 7-step ML system design framework — the question each step answers, and the trap that fails candidates
StepThe question you're answeringThe trap
1 · Problem formulationWhat 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 metricsModel 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 strategyWhat exists, how it's collected, labeled or not, volume, freshness, privacy constraintsAssuming clean, on-time labels (they're usually late and dirty)
4 · FeaturesOffline (batch) vs online (streaming) features; a feature store to keep training and serving consistentIgnoring training-serving skew
5 · ModelingBaseline first, then earned complexity; selection justified by constraints, not fashionStarting with the fanciest model you know
6 · ServingBatch vs real-time, caching, autoscaling, versioning, rollout strategyHand-waving "deploy it on Kubernetes" with no latency math
7 · MonitoringDrift detection, decay alerts, retraining triggers, feedback loops, A/B testingEnding at deployment as if models don't rot
Anatomy of the opening line — the one sentence to say from memory
"Here's my map: problem1, metrics2, data3, features4, model5, serving6, monitoring7.
 I'll go deep where you steer me8."
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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 45-MINUTE CLOCK — every minute is spent on purpose 1 2 3 4 0:00 15:00 25:00 35:00 45:00 5 5 5 10 10 5 5 clarify metrics data draw the board deep-dive where they steer you monitoring and rollout reserve 5 THE RECITAL — the same 45 minutes, spent evenly on all seven steps 7 steps × 5 minutes = 35 minutes of coverage 0 decisions
Fig. 17.1b — The clock, drawn. Five plus five plus five, then ten to draw, ten to go deep, five for monitoring and rollout, five held back: forty-five minutes exactly. The bottom bar is the same forty-five minutes spent evenly, which covers everything and decides nothing.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Failure mode

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.

1 WHAT THE CANDIDATE HOLDS 9 years of shipped systems the real product has 200 users a week of traces would answer the cost question honestly none of this is visible from the other side of the table said 2 WHAT THE INTERVIEWER CAN SCORE 45:00 LangChain Pinecone 512 tokens, because standard why 512? — silence this is the whole of the evidence 3 THE 30 SECONDS THAT SETTLE IT 100,000 users × 5 a day = 500,000 questions a day 6,000 tok × $3 per M = $0.018 400 tok × $15 per M = $0.006 one question = $0.024 × 500,000 = $12,000 a day 4 WHAT THE ROUND IS ACTUALLY MEASURING a reason you did not say is a reason nobody can score an estimate with its assumptions attached beats I would need to measure, every single time
Fig. 17.1c — The two chairs, with their contents. The candidate holds nine years and a 200-user product; the interviewer holds a whiteboard with three tool names on it and a timer; the accent panel is the arithmetic that would have crossed the gap in thirty seconds.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Fireside chat

Tonight's talk: The Candidate and The Interviewer argue over the question, "Who's more important?"

The Candidate
The Interviewer

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:

Fraud detection success metrics — model, business, and system families
FamilyMetricTarget
ModelPrecision at recall ≥ 0.95≥ 0.70
ModelAUC-PR (imbalanced classes — not ROC)≥ 0.85
Business$ fraud prevented / monthtracked monthly
BusinessLegitimate users blocked (FP rate)< 0.5%
Systemp99 latency< 50 ms
SystemAvailability99.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.

🧠 Brain power

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.

ONE PAYMENT, FOUR ARRIVAL TIMES — the horizontal axis is days after the transaction days 0–30: no confirmed truth exists yet day 0 day 7 day 30 day 60 day 90 1 day 0 — the model scores the payment in under 50 ms and approves, blocks or queues it 2 day 0 — an analyst labels the ambiguous middle of the score range by hand: same-day truth 3 day 7 — the fraud ring has already changed tactics; it A/B tests you weekly 4 days 30–90 — the chargeback confirms it was fraud a monthly retrain on this data learns last quarter's fraud
Fig. 17.1d — Why the cleanest labels are the wrong ones. The decision happens on day 0, the adversary moves on day 7, and confirmed truth lands somewhere between day 30 and day 90 — so a model trained only on confirmed labels is always aiming one to three months behind.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

The five numbers every answer below uses. Four are printed in this section; the fraud share is an assumption, because the page gives none.
NumberValueWhere it comes from
Payments arriving10,000 a secondStep 1
Time budget for one paymentUnder 50 ms for 99 payments in 100Step 1 and the metrics table
Time inside the champion model15 ms, used as a flat figureThe champion box of Fig. 17.2, "under 15 ms"
Availability target99.99%The metrics table
Fraud share1 payment in 1,000An 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.

The two numbers side by side
ThroughputLatency
UnitPayments per secondMilliseconds per payment
The question it answersHow much work does the system get through?How long does one customer wait at the till?
TrustBank's target10,000 a secondUnder 50 ms at p99
What improves itMore workers, bigger batchesFaster 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.

  1. Draw a small version. One payment every 5 ms is 200 a second. Each one spends 15 ms in the model.
  2. 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.
  3. Check it against the rule. 200 a second × 0.015 s = 3. Payments in flight = rate × time each.
  4. Scale it up. 10,000 a second × 0.015 s = 150 payments inside the model at any instant.
  5. 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.

The model box alone, fed 10,000 random arrivals a second. Every millisecond above 15 is waiting. Values from rerunning throughput_vs_latency.py; 10,009 rather than 10,000 is the randomness of the arrivals.
WorkersBusyp50p99Finished per second
148101%842.6 ms1,508.7 ms, and still growing9,867
15299%17.0 ms30.7 ms10,009
15597%15.3 ms21.7 ms10,009
16094%15.0 ms18.0 ms10,009
17586%15.0 ms15.5 ms10,009
20075%15.0 ms15.0 ms10,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.

SMALL ENOUGH TO COUNT: a payment every 5 ms, 15 ms each #1 #2 #3 #4 #5 #6 #7 #8 0 10 20 30 40 50 ms 1 at 22 ms, 3 payments are inside 200 a second × 0.015 s = 3 in flight 2 10,000 a second × 0.015 s = 150 in flight and 150 workers, if nobody may ever wait p99 IN THE MODEL BOX, SAME 10,000 A SECOND 148 workers 1,508.7 ms, still growing 3 152 workers 30.7 ms 4 155 workers 21.7 ms 160 workers 18.0 ms 5 200 workers 15.0 ms 0 10 20 30 40 50 ms dashed line: 15 ms, the scoring itself; the rest is queue right edge: 50 ms, the budget for the whole path finished per second: 9,867 with 148 workers, 10,009 with 152, 155, 160 and 200
Fig. 17.1e — Throughput and latency, pulled apart. Left: payments in flight are the rate multiplied by the time each takes, 3 in a drawing and 150 at TrustBank's scale. Right: the same 10,000 payments a second through pools of different sizes; throughput hardly changes while the p99 goes from 15.0 ms to over a second. Values from rerunning throughput_vs_latency.py (the 175-worker row, 15.5 ms, is in the table above).
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

  1. Payments in a minute. 10,000 × 60 = 600,000.
  2. Split them. 600,000 × 0.001 = 600 fraudulent. 600,000 − 600 = 599,400 legitimate.
  3. Apply recall 0.95. 0.95 × 600 = 570 caught, so 30 missed.
  4. 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.
  5. Count the honest customers flagged. 814.3 − 570 = 244.3 a minute.
  6. 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 and the false-positive rate, on the same minute. Values from rerunning fraud_targets_by_hand.py.
PrecisionFalse-positive rate
Top of the fractionFraud caught: 570Legitimate payments flagged: 244.3
Bottom of the fractionEverything flagged: 814.3Every legitimate payment: 599,400
Value on target0.700.0408%
Who feels itWhoever works the flags: 3 in 10 are honest customersThe customers: 244 blocked payments a minute
If fraud becomes half as common and the model stays the sameFalls to 0.538Stays 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.

ONE MINUTE OF PAYMENTS, MODEL EXACTLY ON TARGET 600,000 payments 600 fraud 1 in 1,000, assumed 1 599,400 legitimate 999 for every fraud 570 caught 30 missed 244.3 honest, flagged 599,155.7 passed 2 flag queue 814.3 a minute 3 PRECISION: divide by the flag queue 570 ÷ 814.3 = 0.70 3 flags in 10 are honest customers falls to 0.538 if fraud is 1 in 2,000 4 FALSE-POSITIVE RATE: divide by every honest payment 244.3 ÷ 599,400 = 0.0408% 5 the 0.5% limit alone would allow 2,997 a minute, and precision 570 ÷ 3,567 = 0.16
Fig. 17.1f — Two fractions with the same honest customers on top and very different numbers underneath. Precision divides the 244.3 wrongly flagged customers into a queue of 814.3; the false-positive rate divides them into 599,400. The fraud share of 1 in 1,000 is an assumption. Values from rerunning fraud_targets_by_hand.py.
  1. 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.
  2. The flag queue. Everything the model flags: 570 frauds and 244.3 honest customers, 814.3 a minute. Precision is measured here.
  3. 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.
  4. 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.
  5. 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.

  1. Minutes in a month. 43,830 on average, which is 365.25 days × 24 × 60 ÷ 12. It is the month Appendix A2 uses.
  2. The share allowed to be down. 1 − 0.9999 = 0.0001.
  3. Downtime in minutes. 43,830 × 0.0001 = 4.383 minutes, about 4 min 23 s.
  4. 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.

  1. Four boxes at 99.99% each. 0.9999 × 0.9999 × 0.9999 × 0.9999 = 0.99960.
  2. Downtime of the chain. 43,830 × (1 − 0.99960) = 17.53 minutes a month, four times the target. That is 10,517,622 payments.
  3. 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.
  4. 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.
FOUR BOXES IN A ROW — a payment is scored only when every box answers 1 online features 99.99% 4.383 min a month bandit router 99.99% 4.383 min a month champion model 99.99% 4.383 min a month decision engine 99.99% 4.383 min a month 0.9999 × 0.9999 × 0.9999 × 0.9999 = 0.99960 one box at 99.99% 4.383 min · 2,629,800 payments 2 four in a row 17.53 min · 10,517,622 payments 3 each box, for a 99.99% chain 1.096 min each (0.999975) 4 two independent copies of one box: 1 − 0.0001 × 0.0001 = 0.99999999, about 0.026 seconds a month WHAT A PAYMENT GETS DURING 4.383 MINUTES OF DOWNTIME fail open: approve all 2,630 frauds go through fail closed: decline all 2,627,170 honest payments declined 5 fall back to a rule degraded, not dark
Fig. 17.1g — Four nines, four times. Each box of the real-time path meets 99.99% on its own; the chain of four is down 17.53 minutes a month; and whatever the downtime is, 10,000 payments a second still need an answer chosen in advance. Minutes use Appendix A2's 43,830-minute month. Values from rerunning fraud_targets_by_hand.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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:

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.

REAL-TIME PATH — every box lives inside the <50 ms p99 budget Payment event 10,000 TPS Online features Redis · Feast · <5 ms 1 Bandit router UCB1 Champion XGB + NN · <15 ms Challenger candidate model 95% 5% Decision engine approve · block · review OFFLINE LOOP — training on delayed truth Event log (Kafka) every score + decision Offline store S3 Parquet · daily batch Training pipeline auto-retrain triggers 2 Fraud labels chargebacks · 30–90 d late register as challenger review cases 3 Analyst queue human review same-day confirmed labels feed training
Fig. 17.2 — Fraud detection at 10K TPS. The real-time path stays under 50 ms end-to-end; the bandit router earns the challenger traffic only as it proves itself; the offline loop closes the circle with delayed chargeback labels plus same-day analyst labels.
  1. 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.
  2. 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.
  3. 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:

News-feed ranking — the 7 steps at sketch depth
StepDesign decision
ProblemRank 500+ candidate posts per user to maximize engagement
MetricsModel: NDCG@20 · Business: time-on-feed, DAU · System: p50 < 200 ms
DataClick logs, dwell time, likes/shares/hides, profile, social graph
FeaturesAuthor-user affinity, freshness, content embedding, user history
ModelTwo-tower retrieval (candidates) → LightGBM ranker → diversity re-ranker
ServingPre-computed candidate embeddings offline; real-time scoring; cache hot users
MonitoringPer-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:

The 7 steps, adapted for LLM systems — what interviewers listen for in each
StepClassic ML versionGenAI version (what they listen for)
1 · ProblemWhich ML task?Is this retrieval, generation, or action? Does it even need an LLM? (Module 06)
2 · MetricsAUC, NDCGOffline evals: faithfulness, relevancy, validated LLM-as-judge. Online: TTFT, cost/query, containment rate (Module 07)
3 · DataLabels, freshnessCorpus and ingestion: parsing, chunking, update feeds, index staleness (Module 08)
4 · FeaturesFeature storeContext engineering: retrieval quality, reranking, the context-window token budget (Module 08)
5 · ModelBaseline → complexModel routing: frontier API vs open model vs fine-tune — a decision framework, not a favorite (Modules 11, 12)
6 · ServingBatch vs real-timeKV cache, continuous batching, semantic cache, prompt caching, streaming — and the bill (Module 12)
7 · MonitoringDrift, retrainingEval-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:

LLM-serving vocabulary the interviewer is listening for
TermWhat it isDrop it when discussing…
KV cacheStored attention keys/values so each new token doesn't recompute the whole prefixWhy long contexts eat GPU memory; why serving ≠ training hardware math
Continuous batchingSlot-level batching that refills the GPU per token, not per requestThroughput on vLLM; why naive batching wastes half the GPU
Semantic cacheCache keyed on embedding similarity, not exact string matchCost cuts: 30–40% hit rates on FAQ-shaped traffic
TTFT vs TPOTTime-to-first-token (prefill) vs time-per-output-token (decode)Latency budgets; why streaming makes TTFT the UX metric
Context-window budgetExplicit token allocation: system + retrieved chunks + history + queryChunking and rerank choices; cost-per-query arithmetic
GuardrailsInput injection scanning + output grounding/PII checks around the modelSecurity step of any enterprise design (Module 12)
LLM-as-judgeA model grading outputs — only trustworthy after validation against human labelsEval 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.

Sharpen your pencil

Before you draw a single box, size the system. Interviewers call this a back-of-envelope estimate: rough arithmetic from assumptions you say out loud. Take the requirements above and add four assumptions: 5 questions per employee per workday; 6,000 tokens of context in and 400 tokens out per question; $3 per million input tokens and $15 per million output tokens on the frontier model; and about 480,000 chunks per tenant, each embedded as a list of 1,024 numbers.

Questions per day = 100,000 users × 5500,000 questions per day
Average questions per second = 500,000 ÷ 86,400 seconds
Workday rate = 500,000 ÷ (8 hours × 3,600 seconds), then × 3 for the busiest hour
Input tokens per day = 500,000 × 6,000
Output tokens per day = 500,000 × 400
Cost per day = (input ÷ 1,000,000) × $3 + (output ÷ 1,000,000) × $15
Chunks per tenant = 12,000 documents × 40 chunks480,000 chunks (about 20 pages per document, two chunks per page)
Bytes per vector = 1,024 dimensions × 4 bytes (one 32-bit float per dimension)4,096 bytes
Raw vector storage per tenant = 480,000 × 4,096 bytes

Work each line to four decimal places where there are any. Then answer: which of these numbers would you say out loud first, and why?

Check your answers
Average questions per second500,000 ÷ 86,400 = 5.7870 per second
Workday rate and busiest hour500,000 ÷ 28,800 = 17.3611 per second across the workday; × 3 = 52.0833 per second at the peak — rung 2 of Fig. 17.2b below
Input tokens per day3,000,000,000: three billion tokens read by the model every day
Output tokens per day200,000,000: two hundred million tokens written
Cost per day3,000 × $3 = $9,000 for input, plus 200 × $15 = $3,000 for output: $12,000 per day, about $360,000 per month
Raw vector storage per tenant480,000 × 4,096 = 1,966,080,000 bytes, about 1.9661 GB, vectors only

Say the peak, not the average — rung 2 of Fig. 17.2b, just below this exercise. Fifty-two questions per second is small for a web service and large for a language model, because every uncached question carries 6,000 tokens of reading. Capacity is bought for the busiest hour. A system sized for 5.8 per second falls over every morning at nine.

The cost rung is the one to say first, marker 3 in Fig. 17.2b. Twelve thousand dollars a day is $360,000 a month, and three quarters of it is the input side. Input tokens cost a fifth of the output price, but there are fifteen times as many of them. That is why every lever in Probe 4 below shrinks the context before it reaches the model.

The storage rung is the least alarming and the most often forgotten. Two gigabytes of raw vectors per tenant fits in memory on one database node. The HNSW index, the graph structure that makes nearest-neighbour search fast, adds roughly as much again. Fifty tenants, with their indexes, would reach about 200 GB, which is the point where you shard by tenant or pick a smaller embedding. Storage sets the shape of the index; cost sets the shape of the pipeline.

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.

THE CAPACITY LADDER — six rungs, said in this order, from the four stated assumptions 1 100,000 employees × 5 questions each workday = 500,000 questions a day 2 ÷ 86,400 s = 5.7870 per second · ÷ 28,800 workday s = 17.3611 per second × 3 for the busiest hour = 52.0833 questions per second at the peak 500,000 × 6,000 tokens of context read per question = 3,000,000,000 input tokens a day 500,000 × 400 tokens of answer written per question = 200,000,000 output tokens a day 3 3,000 M × $3 = $9,000 in · 200 M × $15 = $3,000 out = $12,000 a day, about $360,000 a month 4 480,000 chunks × 1,024 dimensions × 4 bytes each = 1,966,080,000 bytes = 1.9661 GB of vectors per tenant every rung is one multiplication from the rung above it, and every assumption in it was said out loud first
Fig. 17.2b — The capacity ladder for Priya's prompt. Four stated assumptions at the top, six rungs of arithmetic, and the two numbers that shape the design at the bottom: $360,000 a month and 1.9661 GB of vectors per tenant.
  1. 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.
  2. 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.
  3. 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.
  4. 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 LATENCY BUDGET — 1 millisecond is half a pixel wide p95 target 1,500 ms 4 auth, tenant filter and the semantic-cache lookup 50 ms hybrid retrieve, dense plus BM25, top 50 120 ms 1 cross-encoder rerank, 50 candidates down to 8 180 ms assemble the context: system prompt, 8 chunks, question 50 ms 2 model prefill: 6,000 tokens read before the first token is written 600 ms 3 TOTAL time to the first token the user sees 1,000 ms 500 ms spare the 400-token answer keeps streaming for another 12 seconds after this, and no user waits for it
Fig. 17.2c — Where 1.5 seconds goes. Four stages of plumbing spend 400 ms between them, the model's prefill on a 6,000-token context spends 600 ms, and 500 ms is left as margin. Stage times other than the 600 ms prefill are the ones this design assumes; they are the numbers you would say on the board and then measure.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

INGEST — continuous, incremental Sources SharePoint · wiki · PDF Parse LlamaParse · keeps tables Chunk heading-aware · 400–800 tok Embed BGE-M3 · te-3-large Index pgvector · dense + BM25 change feed re-embeds only what changed · tenant_id stamped on every chunk QUERY PATH — p95 TTFT under 1.5 s 1 Query + auth tenant filter first 2 Semantic cache hit rate 30–40% miss Hybrid retrieve dense + BM25 · top 50 Rerank BGE-v2 · top 8 Assemble context system + chunks + query ANN + keyword lookup 3–6K token budget LLM + guardrails inject-scan in · grounded out stream Answer + citations streamed · TTFT first User answer + source links hit: serve stored answer ALWAYS ON — evals, traces, cost every request logged Traces Langfuse · every call Eval harness Ragas + LLM-as-judge 3 CI gate promptfoo · blocks regress Cost + latency dash $/query · cache hits · TTFT
Fig. 17.3 — The flagship board: enterprise doc-Q&A. Tenant filtering happens before retrieval, the semantic cache short-circuits 30–40% of traffic, hybrid retrieval + rerank is the quality core, and prompt or index changes ship only through the eval CI gate. Practice until you can draw this in ten minutes.
  1. 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.
  2. 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.
  3. 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.

Fig. 17.3 again, concretely: each stage in the naive answer and on the production board
StageIn the naive answer (section 03)On the production board (Fig. 17.3)What flows out
Ingest and parseA plain text extractor over the PDFs; tables come out as word soupLlamaParse or another layout-aware parser; a change feed re-parses only what changedClean text with document id, page, version and tenant_id
Chunk512 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
EmbedOne embedding call per chunk, model unnamedBGE-M3 or text-embedding-3-large, the same model.encode(...) as mini_rag.py, model name pinned in the schemaOne vector of 1,024 or 3,072 numbers per chunk
IndexPinecone, similarity search onlypgvector with dense plus BM25 and tenant_id on every row: the chunks table from schema.sqlAn index that answers meaning queries and exact-identifier queries
Query and authThe question goes straight to searchThe tenant filter is a hard metadata predicate applied before retrieval, with row-level security as the second wallA query that can only reach one tenant's rows
Semantic cacheNone, or a cache keyed on the exact stringA cache keyed on embedding similarity; 30–40% of questions hit itA stored answer in milliseconds, or a miss that continues
Hybrid retrieveTop 5 by cosine similarityDense plus BM25 fused by rrf() in hybrid_rrf.py, top 50A ranked shortlist of candidates
RerankNoneCrossEncoder in rerank.py reads question and chunk together, keeps the top 8The chunks that answer the question, not just resemble it
Assemble contextPaste the chunks into the promptA 3–6K token budget: system prompt, numbered chunks, then the questionA 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-firstAn 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 billNumbers 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.

INGEST Sources 12,000 docs / tenant ~40 change a day Parse layout-aware tables survive Chunk 400–800 tokens 480,000 chunks Embed 1,024 dimensions 4 bytes each Index 1 1.9661 GB / tenant graph index doubles it QUERY PATH Query + auth 52.0833 q/s at peak tenant filter first Cache 30–40% hit misses go right Retrieve dense + BM25 top 50 Rerank 2 top 8 survive 180 ms Assemble 6,000 tokens in 400 tokens out LLM 3 $0.024 / question p95 TTFT 1.0 s 4 ALWAYS ON — traces on every call, eval gate in CI, cost and latency dashboard $12,000 a day · $360,000 a month at the naive setting · about $78,000 with the cache, the router and a tighter context
Fig. 17.3b — The same board, third pass: nothing but boxes, arrows and the numbers that size them. This is the version you reproduce on a whiteboard in ten minutes, and every number on it came off the ladder in Fig. 17.2b.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

A DOCUMENT CHANGED YESTERDAY — two ways the index finds out 1 WE RE-INDEX EVERYTHING NIGHTLY — the usual answer all 12,000 documents re-parsed from scratch 480,000 chunks re-embedded every night, for a 0.33% change up to 24 hours of stale answers and nothing tells you it is happening 2 A CHANGE FEED — the strong answer 40 documents changed 0.33% of the corpus 1,600 chunks re-embedded 300 times less work 3 stale for minutes, and an alarm when source time outruns index time documents are versioned either way, so a citation pins to the version the answer actually used
Fig. 17.3c — The staleness probe, in numbers. Forty of 12,000 documents change in a day, which is 0.33% of the corpus and 1,600 of the 480,000 chunks. A nightly full re-index does three hundred times the necessary work and still leaves a day-long window where the index quietly lies.
  1. 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.
  2. 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.
  3. 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.

1 NO FILTER BELOW THE MODEL one index · shaded = tenant A · hollow = tenant B the query searches all 960,000 chunks top 8 to the model — one of them is tenant B's document asking the model not to use it is not a control 2 HARD PREDICATE BEFORE RETRIEVAL same index · the search never sees the hollow rows tenant_id = A: only 480,000 chunks are reachable top 8 to the model — every one of them is tenant A's the filter sits below the model, where instructions cannot reach 3 the second and third walls: row-level security in the database, and a red-team eval in CI that tries cross-tenant retrieval on every release — including from inside a poisoned PDF
Fig. 17.3d — Tenant isolation is a filter, not an instruction. Left: one index, no predicate, and one of the eight chunks handed to the model belongs to another customer. Right: tenant_id = A applied before the search, so the other 480,000 chunks are not candidates at all.
  1. 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.
  2. The filter is a predicate, not a prompt. Stamp tenant_id on 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.
  3. 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.
🧠 Brain power

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 MONTHLY BILL — each bar is what is left after the lever above it 1 naive — every question to the frontier model: $0.024 each, 15,000,000 a month $360,000 2 − semantic cache: 35% of questions are paraphrased repeats and never reach a model $234,000 3 − tighter context: rerank to the top 5, so 6,000 tokens become 3,000 $146,250 4 − model router: 70% of the remaining questions go to the cheap model $78,000 a 78% cut · $0.024 becomes $0.008 per question that reaches a model the levers multiply: 0.65 × 0.625 × 0.533 = 0.217, and 0.217 × $360,000 = $78,000 none of it is worth saying without the eval suite that proves the answers did not get worse
Fig. 17.3e — The bill, cut three times. $360,000 a month becomes $78,000 because 35% of questions never reach a model, the ones that do carry half the context, and seven in ten of those go to a model that costs a third as much. The $0.008 is the price of a question that reaches a model; across all 15 million, including the cached ones, the bill works out at $0.0052 a question.
  1. 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.
  2. 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%.
  3. 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.
  4. 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.

Sharpen your pencil

Below are eleven lines lifted from doc_qa_cost_model.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. The file is forty lines of arithmetic; if you can read these eleven, you can read all forty.

USERS = 100_000the number of people who can ask questions; the underscore is a digit separator Python ignores, so this is one hundred thousand
CTX_TOKENS = 6_000 # system prompt + 8 reranked chunks + query
"claude-sonnet-5": (3.00, 15.00),one entry of the price table: for this model, $3 per million input tokens and $15 per million output tokens
p_in, p_out = PRICE[model]
return ctx / 1e6 * p_in + out / 1e6 * p_out
queries = USERS * QUERIES_PER_DAY * 30
return queries * (1 - cache_hit) * sum(s * c for s, c in mix)
naive = monthly([(1.0, per_query("claude-sonnet-5"))])scenario one: all traffic (share 1.0) goes to the frontier model with the full context, and there is no cache
(0.70, per_query("claude-haiku-4-5", ctx=3_000)),
cache_hit=0.35,
print(f"Saved: ${naive - engineered:,.0f} ({1 - engineered / naive:.0%})")
Check your answers
USERS = 100_000the number of people who can ask questions; the underscore is a digit separator Python ignores, so this is one hundred thousand
CTX_TOKENS = 6_000 # system prompt + 8 reranked chunks + queryhow many tokens the model reads per question: the instructions, the eight retrieved chunks and the question itself. This is the input side of the bill, and the bigger side
"claude-sonnet-5": (3.00, 15.00),one entry of the price table: for this model, $3 per million input tokens and $15 per million output tokens
p_in, p_out = PRICE[model]look up the model's pair of prices and unpack the pair into two names: the input price and the output price
return ctx / 1e6 * p_in + out / 1e6 * p_outthe cost of one uncached question: context tokens in millions times the input price, plus answer tokens in millions times the output price
queries = USERS * QUERIES_PER_DAY * 30how many questions arrive in a month: users, times questions per user per day, times thirty days
return queries * (1 - cache_hit) * sum(s * c for s, c in mix)the monthly bill: total questions, minus the share the cache answers for free, times the blended cost of one uncached question (each traffic share times its per-query cost, added up)
naive = monthly([(1.0, per_query("claude-sonnet-5"))])scenario one: all traffic (share 1.0) goes to the frontier model with the full context, and there is no cache
(0.70, per_query("claude-haiku-4-5", ctx=3_000)),one entry of the engineered mix: 70% of the uncached questions go to the cheap model, with the context trimmed to 3,000 tokens
cache_hit=0.35,35% of questions are answered from the semantic cache and never reach a model
print(f"Saved: ${naive - engineered:,.0f} ({1 - engineered / naive:.0%})")print the dollar saving with thousands separators and no decimals, and the saving as a percentage of the naive bill

If you got the two return lines, you have the whole model: one function prices a single question, the other multiplies by volume and takes the cache off the top. Everything else is a named assumption. That is the point of writing it as code: every number you say on the whiteboard has a line you can point at.

Step-by-step: what doc_qa_cost_model.py does, in plain English
  1. 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.
  2. 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.
  3. 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 by 1e6 turns token counts into millions. The result is the cost of one uncached question, in dollars.
  4. Define monthly(mix, cache_hit). mix is 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.
  5. Multiply by (1 - cache_hit): cache hits are served from stored answers and cost nothing here, so only misses are billed. The sum over mix is the blended cost of one miss.
  6. 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.
  7. 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.
  8. 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.
doc_qa_cost_model.pyruns offline
# 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.

BE the interviewer

Your turn on the other side of the table. A candidate has just answered "Design a document Q&A service for our enterprise customers" with the paragraph below. Score it against the five-line rubric, 0 to 2 points per line, 10 in total. Then name the single biggest gap, the thing you would raise first in the debrief. Only then open the reveal.

The candidate's answer: "I'd parse the PDFs, chunk them at about 500 tokens, embed each chunk and store the vectors in a vector database. At query time I embed the question, fetch the top five chunks by cosine similarity, put them in the prompt and ask the model to answer with citations. p95 under two seconds, streamed. Cache answers so repeats are cheap. Updates: re-index nightly. Quality: have the model check its own answers. Kubernetes with autoscaling, and if the bill gets high, switch to a cheaper model."

  1. Requirements and metrics: users, a latency target, and a quality metric with a number on it
  2. Retrieval: the mechanism, and a reason for each choice (chunk size, hybrid search, reranking)
  3. Freshness: how a changed document reaches the index, and how staleness is detected
  4. Tenancy and security: where the tenant filter lives, and what stops a poisoned document
  5. Cost and evals: arithmetic for the bill, and how quality is measured before a change ships

Score each line 0, 1 or 2. What is the total, and what is the biggest gap?

Check your answer

A calibrated score is 4 out of 10: metrics 1, retrieval 1, freshness 1, tenancy 0, cost and evals 1. That is a lean no-hire at senior level and a pass at mid-level. If you gave it 6 or more, you were grading fluency, and the answer is fluent. Fig. 17.3f marks the five scores and circles the zero; the table under it is the reasoning behind each one.

THE FIVE-LINE RUBRIC — 0, 1 or 2 points each, scored on the answer above 0 1 2 1 · requirements and metrics one number, the p95 — no user count, no quality metric 2 · retrieval mechanism complete, nothing justified — about 500 tokens 3 · freshness nightly re-index, no alarm, up to 24 hours stale 1 4 · tenancy and security nothing at all, on a prompt that said enterprise customers 5 · cost and evals a cheaper model named, no arithmetic; an unvalidated judge 2 TOTAL 4 of 10 — a lean no-hire at senior level, a pass at mid-level 3 every lost point has one cause: the answer names no failure mode
Fig. 17.3f — The same rubric with the scores filled in. Four ones and one zero, and the zero is circled because a zero on a stated requirement loses the round outright, while the missing numbers are what keep a 4 from being a 7.
  1. The circled zero. The prompt said enterprise customers, plural, and the answer contains no tenant filter and no input scanning. That is not a missing refinement, it is a missing requirement, and in a bank or a healthcare loop it ends the conversation there.
  2. Four ones, not four zeros. Every other line got half marks because the mechanism was right and the reasoning was absent. That is the profile of an engineer who has built the pipeline once and never operated it, which is exactly what the four probes were written to detect.
  3. The single cause. Read the five reasons in the right-hand column together and they say the same thing five times: no failure mode is named anywhere. Not a stale document, not a poisoned upload, not a wrong answer a validated judge would have caught.
1 · Metrics: 1 of 2One number, the p95. No user count, so nothing can be sized; no quality metric, so "quality" cannot be measured. Two seconds is also total latency, not time-to-first-token, which is the metric that matters once you stream.
2 · Retrieval: 1 of 2The mechanism is complete and correct: chunk, embed, cosine, top five. Nothing is justified. "About 500 tokens" is the exact silence from the failure-mode box. No keyword leg, so an exact identifier such as a form number will miss; no reranker.
3 · Freshness: 1 of 2Nightly re-indexing is a real answer and the wrong one for 12,000 documents that change 40 a day: a full re-embed every night for a 0.3% change, and up to 24 hours of stale answers with no alarm to say so.
4 · Tenancy: 0 of 2Nothing. The prompt said enterprise customers, plural. Without a tenant filter below the model, tenant A can retrieve tenant B's documents; without input scanning, a poisoned PDF can instruct the model. In an enterprise loop this line alone ends the round.
5 · Cost and evals: 1 of 2The candidate knows a cheaper model is a lever but has no arithmetic. "Have the model check its own answers" is an unvalidated judge, which Module 07 showed you cannot trust until it agrees with human labels. Nothing gates a prompt change.

The biggest gap is tenancy, and most first-time interviewers name the missing numbers instead. Both are defensible. A zero on a hard requirement loses the round outright; the missing numbers are what keeps a 4 from being a 7. Notice the pattern behind every lost point: the answer names no failure mode. Not a stale document, not a poisoned PDF, not a wrong answer that a validated judge would have caught.

Notice also what the candidate did well. The retrieval steps are mechanisms, not product names. Streaming is there, and so is a cache. This is not the framework-list answer from section 03. It is the answer of an engineer who has built the pipeline once and never had to operate it, which is exactly the profile the four probes above — chunking, staleness, tenancy and cost — were written to sort.

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.

1 WHAT WAS SAID — 4 of 10 parse → chunk at about 500 → embed → vector DB top 5 by cosine similarity p95 under 2 seconds, streamed updates: re-index nightly quality: the model checks its own answers Kubernetes with autoscaling; cheaper model if the bill grows 2 WHAT WINS THE ROUND — 10 of 10 100,000 users · 52.0833 questions/s at peak p95 TTFT 1.5 s · faithfulness ≥ 0.90 heading-aware 400–800 tokens: 600 beat 300 and 1,200 by six points of faithfulness on the golden set hybrid dense + BM25 top 50 → cross-encoder top 8 change feed: 40 docs a day, 1,600 chunks, staleness alarm tenant_id predicate below the model, row-level security, red-team eval in CI on every release $0.024 a question = $12,000 a day → $78,000 a month engineered 3 same stages, same engineer, same forty-five minutes — the right board says why and how much
Fig. 17.3g — The same prompt, two boards. Nothing on the right requires knowledge the left board lacks; it requires the arithmetic from Fig. 17.2b and a reason attached to each choice.
  1. 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.
  2. 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.
  3. 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.

THE LANE MOST CANDIDATES NEVER DRAW Live answers 500,000 a day, all cited 1 Traces prompt, chunks, latency, cost Error analysis the failures nobody predicted each new failure becomes a permanent test case 2 Golden set 120 questions with known answers Eval harness judge agrees with humans at 0.88 3 CI gate blocks anything below 0.90 pass → canary a prompt or index change ships, or it does not merge 4 ALWAYS-ON ALARMS — index staleness against the source, cost per question against $0.008, cache hit rate against 35%, guardrail hits, and p95 time-to-first-token against 1.5 s
Fig. 17.3h — The loop that keeps the board true. Live answers produce traces, traces produce failures nobody predicted, failures become permanent cases in the 120-question golden set, and nothing ships past the gate that drops faithfulness below 0.90.
  1. 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.
  2. 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.
  3. 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.
  4. 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 four questions every answer below uses, in the order they arrive. The similarities come from made-up four-number vectors in semantic_cache_by_hand.py; the 0.92 cache threshold is the one Module 12 uses.
#The questionNearest question already in tenant A's cacheSimilarityWhat the cache does
Q1How many days of annual leave can I carry over?None: it is the first question of the morningnoneMiss. Full path, answer stored
Q2How much unused annual leave rolls over into next year?Q10.9846Hit. Q1's answer, and it is right
Q3Which form do I file for an expense over $5,000?Q10.0558Miss. Full path, answer stored
Q4How many days of sick leave can I carry over?Q10.9530Hit. 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.

Q1, station by station, on the cache-miss path. Values from rerunning one_question_through_the_board.py.
StationWhat it does to Q1What comes outAddsClock
Query and authFinds 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 ms50 ms
Hybrid retrieveDense search matches by meaning; BM25, a keyword score, matches exact words such as "carry over".50 candidate chunks120 ms170 ms
RerankA cross-encoder reads Q1 beside each candidate and scores how well it answers.The 8 best chunks180 ms350 ms
Assemble contextInstructions and citation rules, the 8 numbered chunks, then Q1.6,000 tokens: 8 × 600 of chunks, 1,200 of the rest50 ms400 ms
Model prefillThe model reads all 6,000 tokens before writing anything.The first word of the answer600 ms1,000 ms
DecodeOne token at a time, 30 ms each, streamed to the screen.400 tokens with [n] citations12,000 ms13,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.

  1. 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.
  2. Price the writing. 400 ÷ 1,000,000 × $15 = $0.006.
  3. Add them. $0.018 + $0.006 = $0.024 for Q1.
  4. 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.

Q1 ON THE CACHE-MISS PATH — what each box adds, and what leaves it 1 auth + cache +50 ms clock 50 ms tenant_id = A: 480,000 chunks cache empty: a miss retrieve +120 ms clock 170 ms dense + BM25, one ranking 50 candidates 2 rerank +180 ms clock 350 ms reads Q1 with each of the 50 8 chunks kept assemble +50 ms clock 400 ms 8 × 600 = 4,800 + 1,200 prompt 6,000 tokens 3 model prefill +600 ms clock 1,000 ms reads all 6,000 tokens, then first word out 4 decode +12,000 ms clock 13,000 ms 400 tokens × 30 ms each, streamed Q1's clock: drawn to scale up to 1,000 ms, then the 12-second stream, shortened 120 ms rerank 180 ms prefill 600 ms: 60% of the wait for the first word 12,000 ms 0 50 170 350 400 1,000 13,000 ms 5 THE BILL FOR Q1 reading: 6,000 ÷ 1,000,000 × $3 = $0.018 writing: 400 ÷ 1,000,000 × $15 = $0.006 total $0.024, three quarters of it reading 6 Q2, A CACHE HIT similarity to Q1: 0.9846, above 0.92 stored answer returned whole at 50 ms no retrieval, no rerank, no model charge
Fig. 17.3i — One question through the board. Q1 misses the cache and meets every box: 400 ms of plumbing, 600 ms of the model reading, then twelve seconds of streamed writing, for $0.024. Q2 hits the cache and is finished at 50 ms. Stage times are the budget of Fig. 17.2c; values from rerunning one_question_through_the_board.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. The bill. Reading is $0.018 of the $0.024, which is why the levers in Fig. 17.3e cut context first.
  6. 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

  1. Count the hits. 500,000 questions a day × 0.35 = 175,000 answered from the cache.
  2. Count the misses. 500,000 − 175,000 = 325,000 go down the full path.
  3. 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.
  4. Subtract from the bill without a cache. $12,000 − $7,800 = $4,200 saved a day.
  5. Make it a month. $4,200 × 30 = $126,000 a month. This is the first cut in Fig. 17.3e.
  6. 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.

Made-up four-number vectors for the four questions. Each column is a pretend "meaning" so the numbers can be read.
QuestionAbout leaveAbout carrying overAbout annual leaveAbout expense claims
Q1 annual leave, carry over0.80.50.30.0
Q2 annual leave, rolls over0.70.60.30.1
Q3 expense form0.00.10.00.9
Q4 sick leave, carry over0.80.50.00.0

Q2 against Q1, the only question stored so far:

  1. 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.
  2. Find Q1's length. √(0.64 + 0.25 + 0.09 + 0) = √0.98 = 0.9899, where √ (square root) undoes the squaring.
  3. Find Q2's length. √(0.49 + 0.36 + 0.09 + 0.01) = √0.95 = 0.9747.
  4. 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.
  5. 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.

WHAT 35% HITS DO TO ONE DAY OF QUESTIONS no cache: 500,000 questions × $0.024 $12,000 a day 35% hits: 175,000 from the cache, 325,000 to a model hits: $0 $7,800 a day 1 saved $4,200 a day = $126,000 a month at 40% hits: $7,200 a day, $144,000 a month saved THE WAIT FOR THE FIRST WORD 2 average: 0.35 × 50 + 0.65 × 1,000 = 667.5 ms p95: the slowest 5 in 100 are all misses, the slowest 7.7% of them, so it stays on the full path at 9 a.m. a model still gets 52.08 × 0.65 = 33.85 a second HOW A HIT IS DECIDED — similarity to Q1 threshold 0.92 raised to 0.96 0.90 0.92 0.94 0.96 0.98 1.00 Q2 0.9846 right hit Q4 0.9530 wrong hit 4 3 5 Q3 scores 0.0558: far to the left of this axis, a miss THREE WAYS A HIT GOES WRONG, AND THE FIX near-identical wording: raise the threshold to 0.96 a changed document: evict answers that cited it another tenant: tenant_id is part of the cache key
Fig. 17.3j — The cache, in dollars and in similarity. Left: 35% hits turn a $12,000 day into a $7,800 day and pull the average first word to 667.5 ms, while the p95 stays on the full path. Right: Q2 and Q4 both clear the 0.92 threshold, and only one of them should. Values from rerunning semantic_cache_by_hand.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

Three ways a hit returns the wrong answer, in the four questions' terms
FailureIn tenant A's morningFixWhat the fix costs
Wrong hit on near-identical wordingQ4 gets Q1's answer at 0.9530Raise the threshold to 0.96Fewer hits, so a smaller saving
Stale hitThe carry-over policy changes at noon; Q1's stored answer cites the old versionStore the document versions each answer cited, and evict it when one changes, from the change feed of Probe 2Hits dip after every update
Cross-tenant hitTenant B types Q1 word for word and sees tenant A's policyOne cache per tenant, with tenant_id in the key, as in Probe 3Each 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.

  1. Name each design in one line. So both sides know what is being compared.
  2. 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.
  3. Put a number in every cell. A cell holding a word is a cell you will be probed on.
  4. Say which stated requirement decides. One Priya gave in the first five minutes, not a preference.
  5. Say the number that would flip your choice. It shows judgement rather than a favourite.
Steps 1 to 3 for Priya's prompt at 100,000 users. Values from rerunning two_designs_side_by_side.py, which reuses the formulas of doc_qa_cost_model.py.
RowDesign A: the board as first drawnDesign B: cache, 5 chunks, router
In one lineEvery question: 8 chunks, 6,000 tokens, the frontier model35% 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.0240.7 × $0.005 + 0.3 × $0.015 = $0.008
Cost averaged over every question$0.0240.65 × $0.008 = $0.0052
Questions a second reaching a model at the peak52.0833.85
First word on a miss1,000 ms700 ms on the frontier model (prefill 600 → 300 ms); the cheap model must be timed. A hit: 50 ms.
New ways to be wrongNone addedWrong cache hits; a needed chunk ranked 6th to 8th is dropped; the cheap model misreads a hard question
What must be proven before it shipsThe golden-set gateThe gate with each lever on, faithfulness still at least 0.90, plus a wrong-hit test
Extra parts to runNoneA 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.

  1. Questions a month at 1,000 users. 1,000 × 5 × 30 = 150,000.
  2. Design A's bill. 150,000 × $0.024 = $3,600.
  3. Design B's bill. 150,000 × 0.65 × $0.008 = $780. The 0.65 is the share that misses the cache.
  4. The saving. $3,600 − $780 = $2,820 a month.
  5. 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.

THE SAME TWO DESIGNS AT THREE SCALES — dollars a month, each tick 10× the last 1,000 users A B saved 1 A $3,600 B $780 saves $2,820 = 0.18 months' pay 10,000 users A B saved 2 A $36,000 B $7,800 saves $28,200 = 1.81 months' pay 100,000 users A B saved 4 A $360,000 B $78,000 saves $282,000 = 18.10 months' pay $100 $1K $10K $100K $1M 3 dashed line: one month's pay at the bottom of the band, $15,583
Fig. 17.3k — Two designs, three customers. On a log axis Design B is always the same distance short of Design A, because it always costs 21.7% as much. The saving is what moves: short of one month of an engineer's pay at 1,000 users, eighteen months of it at 100,000. Values from rerunning two_designs_side_by_side.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.)

The reference GenAI whiteboard stack, with the alternatives you should be able to defend against
LayerWe useAlternativesWhy this oneSwitch when
GatewayA 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 directlyOne 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.
Modelsclaude-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 vLLMTwo 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 storepgvector inside Postgres, dense plus BM25, tenant_id on every rowQdrant, Pinecone, Milvus, OpenSearchVectors 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 cacheA cache keyed on embedding similarity (semantic_cache_by_hand.py)Exact-string cache in Redis, a provider’s prompt caching, no cacheCatches 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.
QueueA 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 queueRe-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.
ObservabilityLangfuse traces on every callLangSmith, Arize Phoenix, OpenTelemetry with your existing tracing backendOpen 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.
EvalsRagas plus a judge checked against human labels, with a promptfoo gate in CI (eval_rag.py)DeepEval, LangSmith evals, hand-graded spreadsheetsTurns “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).

Triggers Slack · cron · API Orchestrator LangGraph StateGraph checkpointed · resumable plans · routes · retries propose next step LLM routing: cheap first discover + call 2 MCP tool registry Jira GitHub SQL (ro) Docs writes 1 HITL gate interrupt() before writes approved Production systems ticket · PR · payout log 3 Audit log append-only · every tool call traces Eval harness replay traces · success rate
Fig. 17.4 — Agent platform sketch. The HITL gate is the design's center of gravity: reads flow freely, writes pause for a human, everything lands in the audit log, and rejected steps return to the planner with feedback. MCP makes the tool registry pluggable instead of hard-coded.
  1. 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.
  2. 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.
  3. 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 1 traffic v1 serves users v2 logs only compare offline zero user risk · 2× inference cost CANARY 2 95% 5% v1 (proven) v2 (canary) compare live metrics hold 24–48 h widen 5 → 25 → 100% BLUE-GREEN 3 router / LB 100% blue = v1 (live) green = v2 (warm, idle) flip = instant cutover flip back = instant rollback 2× infra while both run INTERLEAVING 4 ranker v1 list ranker v2 list interleaved page clicks which model's items win? most sensitive test for ranking
Fig. 17.5 — Four ways to ship a model. Shadow risks nothing and proves nothing about user behavior; canary trades a small blast radius for real evidence; blue-green buys instant rollback with double infrastructure; interleaving detects ranking-quality differences with far less traffic than A/B.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Decision table: choosing a deployment strategy
StrategyChoose whenAvoid whenTypical cost
ShadowNew model class, unknown failure modes; you need production-shaped evidence with zero user riskYou need behavioral evidence (clicks, conversions) — shadow can't see user reactions2× inference, 0 user risk
CanaryDefault for most model and prompt rollouts; real evidence, bounded blast radiusEffects too small to detect at 5% traffic in daysSmall risk on 5% of users
Blue-greenRollback speed is everything (payments, healthcare); infra changes ship with the modelBudget can't carry two full environments2× infra during the switch
InterleavingRanking systems — mixes both models' results on one page; very sample-efficientNon-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 reportRewards 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
  1. Import numpy and create a random number generator with a fixed seed, so every run produces the same sequence and the output is reproducible.
  2. 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.
  3. Create two bookkeeping dictionaries keyed by model name: pulls, how many requests each model has served, and reward, how many of those decisions were later confirmed correct.
  4. 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.
  5. Otherwise compute the model's observed mean reward, then add a bonus of c times the square root of ln t divided by its pull count. The bonus is large for a model with few pulls and shrinks as evidence accumulates; c sets how adventurous the router is.
  6. 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.
  7. 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.
ucb_bandit_router.pyruns offline
# 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.

Prepare eight to ten stories. But for senior GenAI roles three of them are effectively mandatory, because screeners now probe for each explicitly:

The three stories every senior GenAI candidate needs prepared
StoryModules that arm itNumbers 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 recur07 · 12Failure 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 kept12$ 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 decision16The 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.

STAR, WORKED — the recommendation story, one block at a time S · Situation the recommendation engine click-through 2.0% T · Task I owned the number +50% in one quarter A · Action two-tower retrieval, a feature store, an interleaving test — what I did, not what we did 1 R · Result 2.0% → 3.8%, a 90% lift $1.2M a year THE THREE STORIES A SENIOR GENAI SCREEN PROBES FOR — each one a pair of numbers 2 the production failure and the eval-driven fix faithfulness 0.71 → 0.94, and a gate in CI that now blocks the regression from coming back 3 the cost win $46,000 → $19,000 a month, with the eval suite that proved the answers did not get worse 4 the stakeholder translation not ROC-AUC 0.94 on 150 estimators, but: we flag 94% of leavers two weeks early, $380K retained
Fig. 17.5b — A senior story is a pair of numbers with a mechanism between them. The worked example moves click-through from 2.0% to 3.8%; the three mandatory stories move faithfulness, a monthly bill, and an executive's understanding.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

Boardroom translation

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:

The four portfolio patterns that matter in 2026 — all four exist in your course labs
PatternCourse lab it extendsWhat it provesHeadline metric
RAG service with evals in CILab 08 + Lab 07's harnessRetrieval judgment and the #1 differentiator: shipped evals with measurable outcomesFaithfulness 0.94 on a 120-question golden set
Multi-tool agent with observabilityLab 09Orchestration, HITL judgment, and trace-level debuggingTask success rate across replayed traces
Fine-tune with a cost-benefit sheetLab 11The rarest proof: "widely claimed, rarely proven" — a QLoRA model that beats the API option and shows the mathQuality delta + $/1K requests vs the API baseline
MCP server, publishedLab 10Fluency 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
  1. 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.
  2. Problem: who is hurt, what it costs them, and why a generic chat product fails at it. Two sentences, no back-story.
  3. Architecture: one image and two sentences naming the mechanism (hybrid retrieval, reranker, model, guardrails, cache). A design note in docs/ holds the rest.
  4. 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.
  5. Failure modes: three things that broke, each with the fix. This is the section most templates leave out and the one interviewers read first.
  6. 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.
  7. Run it: one command. If it takes more than one, the reader stops here.
README_template.mdmarkdown template
# 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
![architecture](docs/architecture.svg)
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 SAME NINE YEARS, TWO MARKETS — where the number is really decided UNITED STATES · senior GenAI total compensation, top tier 1 $187K $457K $213K — median for agentic-AI postings $150K $200K $300K $400K $500K INDIA · 9 years of experience, Bengaluru, lakhs per annum 2 a services firm 3 ₹40L ₹70L+ a product company 0 ₹20L ₹40L ₹60L ₹80L the distance between the two Indian bands is 60–150% — no negotiation tactic is worth that much
Fig. 17.5c — Where the offer is really decided. In the United States the top-tier senior GenAI band runs $187K to $457K with agentic-AI postings sitting at a $213K median; in India the same nine years is worth ₹40–70+ lakh at a product company and 60 to 150 percent less at a services firm.
  1. 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.
  2. 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.
  3. 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:

Vocabulary signals: what reads as current vs stale in 2026 screens
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.

LAB 17 — The interview dress rehearsal (and the portfolio ships)

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.

What this course does NOT prep — plan these in parallel

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

Interview radar — final form

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 10 questions of the full loop — and where this course answered each
The questionAnswered inStrong-answer seed
"Design a document Q&A / RAG service for [domain] — and defend your chunking."08 · Production RAGFig. 17.3 + eval-measured chunking, hybrid + rerank, tenant filter below the model
"How do you know your LLM feature works?"07 · EvalsError 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 AIFig. 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 · MCPDiscovery over integration: teams own servers, agents discover capabilities, no redeploys
"When would you fine-tune instead of RAG or prompting?"11 · Fine-TuningNever 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 · LLMOpsThe 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 · 12Data 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 · 03Classical 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 · 14OWASP #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 · 12Story #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.
🧠 Flex your memory

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?