End-to-End GenAI System Design: Architecture Deep-Dive
Machine LearningModel answerLast updated
Design and defend a complete GenAI system from data ingestion to production serving, covering model choice, evaluation, safety, and a scaling plan under hard latency and cost constraints.
Scenario
You are presenting at a technical review for a GenAI-powered product you have built or designed in depth. Your audience includes senior ML engineers and a tech lead who will push on every number and every decision.
What you need to cover
Walk through the full system in the following order. Spend roughly 60% of your time on serving, failure modes, and the scaling plan — that is where the real signal is.
- Problem framing — What is the task? What is the business metric of success (not just an offline ML metric)?
- Data sourcing and governance — Where did the data come from? How large is it? How did you handle quality, deduplication, and privacy (PII, consent, retention)?
- Model architecture — Did you use a retrieval-augmented system, a fine-tuned instruction model, a prompt-engineered frontier API, or something else? Why?
- Training or fine-tuning setup — Objectives, key hyperparameters, hardware, and wall-clock time.
- Evaluation — Both offline metrics (retrieval quality, generation faithfulness, format compliance) and online metrics (A/B test, business KPIs). How did you validate the offline metrics were meaningful proxies?
- Safety and guardrails — How did you handle toxicity, prompt injection, hallucinations, and out-of-scope requests?
- Key failure modes — What broke in production, and how did you find out?
- Scaling plan — The system now needs to handle 10× current traffic while meeting a 200 ms p95 latency SLO and achieving a 20% reduction in cost per request. How do you get there?
What a strong answer looks like
- States concrete numbers (QPS, token counts, dataset size, hardware, latency budget per stage).
- Explains trade-offs explicitly: why this model over that one, why RAG instead of full fine-tuning, why this caching strategy.
- Acknowledges mistakes or limitations honestly.
- Recognises and resolves the tension between the latency SLO and the cost target before proposing solutions.
- Covers the scaling plan with specific, prioritised levers rather than a generic wish list.
Hints
Hint 1
Before diving into the scaling plan, clarify what the 200 ms SLO actually covers. Generating 100+ tokens end-to-end in 200 ms is physically implausible on most hardware — so what exactly is being measured? Time-to-first-token? Per-token streaming budget? Getting this right shapes everything that follows.
Hint 2
Think about where requests spend their time before they even reach the GPU. Caching, routing, and batching can each remove large chunks of load without touching the model at all — and they often give you both latency and cost wins at the same time.
Hint 3
On safety, separate the input path, the retrieval path, and the output path. Each has its own attack surface. In particular, think about what happens when retrieved content itself contains instruction-like text — this is a different threat than a malicious user prompt.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
What this question is really testing
This is a project defence, not a textbook recitation. The interviewer wants to know three things: whether you actually owned the system (you can justify every number, including the bad decisions), whether you understand what happens inside the stack at a mechanistic level (batching, KV cache, prefill vs. decode, retrieval recall), and whether you can simultaneously satisfy a latency SLO and a cost target — two forces that usually pull in opposite directions.
Use a concrete example throughout. Vague answers lose credibility fast.
1. Problem and business metric
Example system: a self-service support assistant for an e-commerce platform, answering questions about orders, returns, and policies, with cited sources.
- Traffic: ~50 QPS average, ~150 QPS peak. Average response length: ~120 output tokens.
- Business metric: contact deflection rate. Baseline 18%, target 30%.
- Guardrail thresholds: hallucination rate below 2% on audited samples, CSAT stable or improving, escalation rate not increasing.
Opening with deflection rate, not BLEU or ROUGE, immediately signals product thinking.
2. Data and governance
- Corpus: ~400K policy/help articles and ~2M historical chat transcripts.
- After MinHash deduplication, quality filtering, and removing outdated policy versions: ~900K usable resolved conversations.
- Privacy: a NER model plus regex redacted names, addresses, order IDs, and payment data before anything touched training. Opted-out customers were excluded. Access was gated behind audited IAM roles.
- Fine-tuning set: ~30K curated examples (20K filtered from top-rated agent transcripts, 10K annotator-written or corrected). Inter-annotator agreement: Cohen's κ ≈ 0.7.
The most important lesson to state explicitly: label quality beats label volume. 30K clean examples outperformed 200K noisy ones in every ablation.
3. Model choice and trade-offs
Chosen design: RAG with a LoRA-tuned 8B instruction model.
| Option | Why accepted or rejected |
|---|---|
| RAG + fine-tuned 8B | Chosen. Retrieval handles freshness and citations; fine-tuning shapes tone, refusal behavior, and output structure without encoding knowledge in weights |
| Frontier API only | ~6× higher per-request cost at our QPS; p95 latency outside our control |
| Full fine-tune, no retrieval | Weekly policy changes would require retraining; no citation support |
| Encoder-decoder | Inferior open-ended generation quality; smaller instruction-tuned ecosystem |
Retrieval stack: hybrid BM25 + dense embeddings over ~1M chunks (300–500 tokens each), HNSW index, cross-encoder reranker narrowing top-50 to top-5. A frontier model was kept as a fallback for low-confidence cases.
4. Training setup
- SFT: next-token loss on response tokens only (not prompt tokens). LoRA rank 16, alpha 32, applied to attention and MLP projections. LR 2e-4 with cosine decay, 3% warmup, 3 epochs, effective batch size 128, bf16. Hardware: 8×A100, ~6 hours.
- Preference tuning: DPO on ~8K agent-ranked pairs, β = 0.1. Reduced over-long answers and false confidence.
- Embedding model: contrastive fine-tuning on (query, clicked article) pairs with in-batch and BM25-mined hard negatives. Recall@5 improved from 0.71 → 0.84.
5. Evaluation
Offline:
| Layer | Metric |
|---|---|
| Retrieval | Recall@k, MRR |
| Generation | Faithfulness (NLI/LLM judge vs. cited chunks), answer correctness on 2K golden set, citation precision, refusal accuracy on unanswerable questions |
| Behavior | Format compliance rate |
Human eval: weekly sample of 500 conversations rated on a 1–5 rubric (correct, grounded, helpful, safe). The LLM judge was calibrated against these labels — agreement ~85%. Critical point: LLM judges systematically favour longer answers. Always validate them against human ratings before trusting them.
Online: A/B test measuring deflection, CSAT, escalation, and cost per resolved contact. Ship criteria were defined before the experiment started.
6. Safety and guardrails
- Input path: toxicity/jailbreak classifier, PII redaction, topic scoping (off-domain requests receive a polite refusal rather than an attempt).
- Prompt injection via retrieval: retrieved chunks are wrapped in explicit delimiters and treated as data, never instructions. Instruction-like patterns are stripped at ingestion. Tool calls (e.g., refund initiation) are structured server-side; the LLM is never trusted to enforce permissions.
- Hallucination: answers require citations; a post-hoc grounding check flags unsupported claims and either triggers regeneration or abstains. If the reranker's top score falls below a threshold, the system escalates rather than guessing.
- Output path: toxicity filter and policy check before delivery. Red-team suites run in CI.
7. Key failure modes (be candid)
- Retrieval misses → confident hallucinations. ~60% of bad answers traced back here. Fixed by hybrid search, query rewriting, and the abstain threshold.
- Stale index. Policy updates lagged by ~24 hours. Fixed by event-driven re-indexing (SLA: under 5 minutes).
- Tail latency from long contexts. Multi-turn histories grew past 6K tokens. Fixed by conversation summarization after N turns.
- Distribution shift during peak events. Novel query clusters appeared. Fixed by embedding-space drift monitoring on query logs.
8. Scaling to 10× traffic, 200 ms p95, 20% lower cost per request
Clarify the SLO first. Generating 120 tokens end-to-end in 200 ms is physically impossible on current hardware at reasonable batch sizes. The 200 ms SLO should apply to time-to-first-token (TTFT), with a separate per-token streaming budget (~20 ms/token). If the interviewer means total response time, push back and negotiate.
Also note: "20% cost reduction at 10× traffic" needs unpacking. If it means 20% lower total cost, that requires a ~92% reduction in unit cost — a very different target than 20% per request. Assume per-request, but name the ambiguity.
Latency budget for 200 ms TTFT (p95):
| Stage | Budget |
|---|---|
| Gateway + auth | 10 ms |
| Semantic cache lookup | 5 ms |
| Query embedding (small model, batched) | 10 ms |
| ANN + BM25 retrieval (parallel) | 20 ms |
| Reranker (distilled, top-20 → top-5) | 25 ms |
| Prompt assembly | 5 ms |
| Prefill (~1.5K tokens, prefix-cached) | 80 ms |
| Headroom | 45 ms |
Levers, ordered by expected impact:
- Semantic and exact caching. Repetitive FAQ traffic can yield a 25–35% cache hit rate, removing those requests from the GPU path entirely. Invalidate on document change events, not TTL alone.
- Model cascade. A lightweight intent classifier routes easy, high-confidence requests to a distilled 1–3B model and sends ambiguous or sensitive ones to the 8B. This can cut average per-request cost by 40–60% if the traffic mix supports it.
- Quantisation. INT8 or INT4 weight quantisation on the 8B model reduces memory footprint and increases effective batch size with minimal quality loss on this task.
- Continuous batching and prefix caching. The system prompt and few-shot examples are identical across requests. Prefix caching reuses their KV cache, cutting prefill time significantly at scale.
- Retrieval scaling. Shard the vector index, or move to a managed ANN service. Distill the cross-encoder reranker to a smaller model — this stage has a disproportionate latency contribution.
- Speculative decoding. A small draft model generates candidate tokens that the larger model verifies in parallel. This can improve decode throughput by 2–3× without quality degradation, though it adds engineering complexity.
Common mistakes to avoid: proposing caching without a cache invalidation strategy; recommending quantisation without acknowledging that it needs re-evaluation on your task's quality metrics; treating the cost and latency targets as independent when the best levers (caching, cascades) improve both simultaneously.