Skip to main content
HS
HiSETSuccess
LeetCode Prep

AI & FDE Interview Room

Role paths, mocks, cost studio, chapters, cases, and staff-level depth.

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 typeMeasuresNotes
RetrievalRecall@k, nDCGNeeds labeled passages
Answer qualityRubrics, pairwise prefsHuman or LLM-judge
FaithfulnessGrounding / NLICritical for RAG
Task successExact match, testsAgents / tools
SafetyPolicy violation rateRed-team sets
  1. Build a frozen golden set before optimizing prompts
  2. Split online metrics (thumbs, CSAT) from offline regression
  3. Version datasets; track which release was evaluated on which set
  4. CI gate: fail deploy if core metrics drop beyond threshold
Eval in the release path
Change (prompt/model/index)
        ↓
 Offline suite (golden + safety)
        ↓
 Shadow / canary traffic
        ↓
 Online metrics + human sample
        ↓
 Promote or rollback

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

OfflineOnline
SpeedFast iterationSlow, needs traffic
BiasDataset biasPopularity / novelty bias
SafetyCan hold out red-teamNeeds careful exposure
MetricAccuracy, faithfulnessCSAT, 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.

LayerExample controls
IngressPII detection, prompt-injection heuristics, allowlisted topics
ModelSafety-tuned model, refusal policies
EgressToxicity/PII classifiers, citation requirements
ToolsAuthZ, confirmations, sandboxes
OpsAbuse 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
Layered guardrails
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.

KnobLatency impactCost impact
Model size / tierHighHigh
Context tokensMedium–highHigh
Retrieval k + rerankMediumMedium
Agent stepsVery highVery high
Cache hitLarge winLarge win
Streaming UXPerceived latency ↓Same token cost
  1. Write a p50/p99 budget waterfall (auth + retrieve + LLM + post)
  2. Estimate $/1k queries at expected QPS and cache hit rate
  3. Set max tokens and max tool steps in config — not tribal knowledge
  4. Prefer early exits: classify → retrieve → generate only if needed
Example p99 budget (2.5s)
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.

SignalWhy
Latency breakdownFind which hop dominates p99
Tokens in/outCost attribution per feature
Retrieval ids + scoresDebug wrong answers
Tool call tracesAgent loop forensics
User feedbackOnline quality signal
Error taxonomiesTimeout 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 of one request
[trace_id]
 gateway → retrieve (chunk_ids)
        → llm (model, tokens, TTFT)
        → tool_x (args hash, latency)
        → llm
        → response (policy flags)
 feedback ←── user

Privacy

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.

IncidentFirst response
Provider outageFailover model / degrade features
Cost spikeTighten max tokens; disable agents
Safety breachKill switch; expand filters; preserve forensics
Bad prompt deployRevert config version
Corrupt indexServe previous index alias
  1. Feature flags for prompt packs, models, and retrieval configs
  2. Blue/green or alias-based index swaps
  3. Runbooks with owners, dashboards, and customer comms templates
  4. 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.

  1. Offline: 400 golden questions — retrieval frozen — score exact match / rubric / citation overlap / refusal correctness.
  2. Require: groundedness ≥ 90%, citation precision ≥ 85%, critical safety slice 100% on must-refuse set (40 items).
  3. Shadow online 5% traffic: compare thumbs-up, escalation rate, p95 latency, $/query.
  4. Promote if offline gates pass and online deltas within bounds for 72h; else auto-rollback.
  5. 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