Chapter
Production AI
Evals, guardrails, cost/latency, and observability — shipping AI systems that survive production interviews.
Evaluation Harnesses
Evals turn AI quality from opinion into a regression suite. Interviewers look for golden sets, automated graders, human review sampling, and gates that block bad prompt/model deploys.
| Eval type | Measures | Notes |
|---|---|---|
| Retrieval | Recall@k, nDCG | Needs labeled passages |
| Answer quality | Rubrics, pairwise prefs | Human or LLM-judge |
| Faithfulness | Grounding / NLI | Critical for RAG |
| Task success | Exact match, tests | Agents / tools |
| Safety | Policy violation rate | Red-team sets |
- Build a frozen golden set before optimizing prompts
- Split online metrics (thumbs, CSAT) from offline regression
- Version datasets; track which release was evaluated on which set
- CI gate: fail deploy if core metrics drop beyond threshold
Change (prompt/model/index)
↓
Offline suite (golden + safety)
↓
Shadow / canary traffic
↓
Online metrics + human sample
↓
Promote or rollbackLLM-as-judge bias
Judges favor verbosity and their own style. Calibrate against humans, randomize order, and do not chase judge scores alone.
Interview signal
"No eval set" is an automatic weak signal. Even 50–100 labeled examples with clear rubrics beats none.
Offline vs Online Evals
Offline evals are reproducible and cheap to iterate; online evals capture real user distribution and preference. Production AI design needs both, with clear promotion criteria between them.
| Offline | Online | |
|---|---|---|
| Speed | Fast iteration | Slow, needs traffic |
| Bias | Dataset bias | Popularity / novelty bias |
| Safety | Can hold out red-team | Needs careful exposure |
| Metric | Accuracy, faithfulness | CSAT, retention, $ |
- Interleave or A/B carefully; holdout users for measurement
- Use CUPED / variance reduction when effects are small
- Watch for Simpson's paradox across segments (locale, plan tier)
- Kill switches for experiments that spike toxicity or cost
Promotion rule example
Ship to canary only if offline faithfulness ≥ baseline and safety regressions = 0; promote if online thumbs-up lifts without p99 regression.
Interview signal
Explain how a change that wins offline could lose online (distribution shift) and what you'd monitor for two weeks post-launch.
Guardrails & Safety
Guardrails are layered controls: input filters, policy prompts, output classifiers, tool permissioning, and human escalation. Safety interviews reward defense-in-depth over a single system prompt ban list.
| Layer | Example controls |
|---|---|
| Ingress | PII detection, prompt-injection heuristics, allowlisted topics |
| Model | Safety-tuned model, refusal policies |
| Egress | Toxicity/PII classifiers, citation requirements |
| Tools | AuthZ, confirmations, sandboxes |
| Ops | Abuse rate limits, audit, incident runbooks |
- Fail closed on high-severity categories; fail open carefully on low-severity with logging
- Separate safety evals from product quality evals
- Red-team continuously — attackers iterate on jailbreaks
- Document residual risk for legal/compliance stakeholders
User input → Input filters / rewrite → LLM (+ policy system prompt) → Output classifiers → Tool policy (if any) → Response or safe refusal
Overblocking
Aggressive filters hurt product UX and hide real issues. Measure false positive rate on legitimate traffic, not only attack success rate.
Interview signal
Name injection, data exfiltration via tools, and unsafe advice as distinct threats with distinct mitigations.
Cost & Latency Budgets
Every AI feature needs an explicit latency SLO and a unit-economics model. Interviews push you to allocate milliseconds and dollars across retrieval, models, and tools — then name the knobs.
| Knob | Latency impact | Cost impact |
|---|---|---|
| Model size / tier | High | High |
| Context tokens | Medium–high | High |
| Retrieval k + rerank | Medium | Medium |
| Agent steps | Very high | Very high |
| Cache hit | Large win | Large win |
| Streaming UX | Perceived latency ↓ | Same token cost |
- Write a p50/p99 budget waterfall (auth + retrieve + LLM + post)
- Estimate $/1k queries at expected QPS and cache hit rate
- Set max tokens and max tool steps in config — not tribal knowledge
- Prefer early exits: classify → retrieve → generate only if needed
Gateway/auth 50ms Retrieve+rerank 200ms LLM TTFT 400ms LLM generate 1500ms Post/validate 50ms ──────────────────── Total 2200ms (300ms slack)
Semantic cache
Exact-match cache first; semantic cache for paraphrases with similarity threshold and ACL keys. Measure invalidation and wrong-hit risk.
Interview signal
Do the napkin math out loud. Candidates who only say "use a bigger GPU" fail the systems bar.
Observability for LLM Apps
LLM observability extends classic metrics/logs/traces with prompts, retrieval sets, tool traces, token counts, and quality scores — under strict redaction. Without it, production incidents are un-debuggable.
| Signal | Why |
|---|---|
| Latency breakdown | Find which hop dominates p99 |
| Tokens in/out | Cost attribution per feature |
| Retrieval ids + scores | Debug wrong answers |
| Tool call traces | Agent loop forensics |
| User feedback | Online quality signal |
| Error taxonomies | Timeout vs policy vs model |
- Trace id across gateway → retrieve → model → tools
- Sample raw prompts; never store secrets or full PII by default
- Dashboards: quality, cost, latency, safety hits — same pane of glass
- Alert on distribution shifts, not only hard errors
[trace_id]
gateway → retrieve (chunk_ids)
→ llm (model, tokens, TTFT)
→ tool_x (args hash, latency)
→ llm
→ response (policy flags)
feedback ←── userPrivacy
Prompt logs are a compliance bomb. Encrypt, retain briefly, role-gate access, and strip credentials before persistence.
Interview signal
Describe how you'd debug "answers got worse after Tuesday's deploy" using traces + eval diffs — not guesswork.
Rollbacks & Incident Response
AI incidents include quality cliffs, cost explosions, safety bypasses, and provider outages. Treat model/prompt/index changes like code deploys with instant rollback and clear severity.
| Incident | First response |
|---|---|
| Provider outage | Failover model / degrade features |
| Cost spike | Tighten max tokens; disable agents |
| Safety breach | Kill switch; expand filters; preserve forensics |
| Bad prompt deploy | Revert config version |
| Corrupt index | Serve previous index alias |
- Feature flags for prompt packs, models, and retrieval configs
- Blue/green or alias-based index swaps
- Runbooks with owners, dashboards, and customer comms templates
- Post-incident: add an eval case that would have caught it
Interview signal
Always mention a kill switch and config rollback. AI systems without them are not production-ready.
Degraded mode
Define what still works when the LLM is down: keyword search, cached answers, human handoff. Resilience is a product feature.
Staff depth layer
Production AI — Staff Depth
Production AI is evals, safety, cost, latency, and observability welded together. Staff answers gate releases on golden sets, separate online metrics from offline judges, design prompt-injection defenses for tool users, and can walk a rollback when quality or spend blows up.
Anti-patterns → say instead
✕ Vibe-based prompt ship
A change that feels better on three examples silently regresses a long-tail class.
Say instead: CI gate on golden suite + slice metrics; require owner approval when safety slices move.
✕ LLM-as-judge with no calibration
Judges favor verbose answers and drift; you optimize for the judge, not users.
Say instead: Calibrate against human labels; mix rule checks (JSON, citations present) with judges; spot-check weekly.
✕ Cost ignored until finance pages
Token spend scales with success; viral features bankrupt the budget overnight.
Say instead: Per-tenant budgets, cascading models, semantic cache, and alerts on $/answer and tokens per session.
✕ Safety = blocklist keywords
Misses indirect injection in retrieved docs and encoded tool exfiltration.
Say instead: Defense in depth: isolate untrusted content, argue tool allowlists, outbound URL allowlists, human gates, red-team suite.
Swap mid-tier API model for a cheaper one on RAG Q&A. Must not drop groundedness or raise p95 latency.
- Offline: 400 golden questions — retrieval frozen — score exact match / rubric / citation overlap / refusal correctness.
- Require: groundedness ≥ 90%, citation precision ≥ 85%, critical safety slice 100% on must-refuse set (40 items).
- Shadow online 5% traffic: compare thumbs-up, escalation rate, p95 latency, $/query.
- Promote if offline gates pass and online deltas within bounds for 72h; else auto-rollback.
- Cost: old $3/1M in+$15/1M out vs new $0.40+$1.60; at 20M tokens/day expect ~$60 → ~$20 if quality holds (~$1.2k/mo save).
- Judge agreement target κ ≥ 0.6 vs humans on 100 double-labeled items before trusting automation
- Alert if $/query > 1.5× 7-day baseline or hallucination reports > 2×
- Rollback RTO: feature flag flip < 5 minutes; prompt pin to previous hash
Ship models like binaries: gates, shadow, canary, rollback — with cost SLOs beside quality SLOs.
Cheat sheet
- Golden set + CI gate before prod
- Split retrieval vs generation failures
- Online: latency, cost, escalations, thumbs, safety incidents
- Flags for prompt/model/config rollback
- Budgets and cascades for cost
- Injection: isolate, allowlist tools, approve side effects
- Tracing with prompt hash, retrieved IDs, tool calls