Build a Production RAG Pipeline with Strict Latency Requirements
Machine LearningModel answerLast updated
Design an end-to-end retrieval-augmented generation architecture for customer support that meets p99 latency targets under 1.5s while handling multi-tenancy and scale.
You're building a retrieval-augmented generation pipeline to power an AI assistant that answers customer support questions. The system must retrieve relevant information from a knowledge base and generate grounded responses while meeting strict performance requirements.
Requirements
Performance targets:
- p99 latency under 1.5 seconds
- Support 50 queries per second at peak load
- Handle 10 million documents across the knowledge base
Functional requirements:
- Multi-tenant architecture with complete data isolation
- Document updates must be searchable within 5 minutes
- Deletions must take effect immediately
- Responses must include citations to source material
- System should refuse to answer when confidence is low
What to design
Present a complete architecture covering:
- Ingestion pipeline: How documents are processed, chunked, and indexed
- Retrieval strategy: Vector search, keyword search, or hybrid; index selection and configuration
- Ranking and filtering: How you select the most relevant content
- Generation pipeline: LLM integration, prompt construction, and streaming
- Caching strategy: What to cache and how to invalidate
- Safety mechanisms: Input/output validation and hallucination prevention
- Multi-tenancy: How you isolate tenant data and enforce access controls
- Failure handling: What happens when retrieval fails, timeouts occur, or cache is stale
Additionally:
- Capacity planning: Estimate infrastructure costs and sizing for the index, compute, and API calls
- Evaluation framework: Define metrics and design an experiment to compare retrieval approaches
- Prioritization: If you had limited time, what would you focus on first and what could you defer?
Provide concrete technology choices, latency budgets per component, and quantitative reasoning where appropriate.
Hints
Hint 1
Break down the 1.5s budget across pipeline stages: guardrails, retrieval, reranking, and generation each need allocated time
Hint 2
Consider both dense embeddings and lexical search - each excels at different query types (paraphrases vs exact product codes)
Hint 3
Multi-tenant isolation requires filtering at the infrastructure level, not just in application logic
Hint 4
Design for failure: what's your fallback when the top retrieved documents have low relevance scores?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Production RAG Pipeline Design
1. Requirements Clarification
First, translate ambiguous requirements into measurable targets:
- Latency definition: Propose measuring time-to-first-token (TTFT) ≤ 1.5s with streaming output, rather than full completion. Generating 200 tokens fully within 1.5s is unrealistic; streaming lets users see progress.
- Scale assumptions: 50 QPS peak likely means ~20 QPS sustained average. Plan for 10M documents with ~5 chunks each = 50M searchable chunks.
- Freshness vs consistency: Updates searchable in 5 minutes allows async indexing; immediate deletes require synchronous index updates or filtering.
2. Architecture Overview
Ingestion Pipeline (Async)
Document processing runs in the background:
- Ingestion: Connectors pull from sources (docs, wikis, tickets); CDC streams capture updates
- Preprocessing: Parse formats (PDF, HTML, Markdown), extract text, normalize
- Chunking: Split into 400-500 token segments with 50-token overlap; preserve structure (prepend section headers like "Billing → Refunds → Policy")
- Embedding: Generate 768-dimensional vectors using a domain-tuned encoder
- Indexing: Write to both vector index (ANN) and keyword index (inverted index for BM25)
- Metadata storage: Store document/chunk mappings, ACLs, and versions in Postgres
Key: Make the pipeline idempotent using (doc_id, version) as the key for retries.
Serving Pipeline (Sync, Latency-Budgeted)
Allocate the 1.5s budget across stages:
| Component | Time Budget (p99) | Purpose |
|---|---|---|
| Input guardrails | 30ms | Check for PII, prompt injection attempts |
| Query embedding | 20ms | Convert query to vector (with caching) |
| Hybrid retrieval | 40ms | Parallel vector + BM25, fetch top 50 each |
| Reranking | 80ms | Cross-encoder scores 100 candidates → keep top 5 |
| Prompt construction | 5ms | Assemble context with citations |
| LLM prefill + first token | 600ms | Generate with ~3k input tokens |
| Output validation | 50ms | Check groundedness, filter PII |
| Total | ~825ms | Leaves 675ms buffer for p99 variance |
3. Key Design Decisions
Chunking Strategy
Use structure-aware chunking:
- Split on semantic boundaries (headings, list items)
- Keep 400-500 tokens per chunk with 50-token overlap to prevent context loss at boundaries
- Prepend hierarchical context: "Billing > Refunds > International Returns" helps retrieval and attribution
- Keep tables and code blocks atomic (don't split mid-table)
Retrieval: Hybrid Search
Use both retrieval methods in parallel:
Dense retrieval (vector search):
- Handles paraphrases and semantic similarity
- Use approximate nearest neighbors (HNSW or IVF-PQ)
- Fine-tune the embedding model on (support query, relevant doc) pairs if you have logs
Sparse retrieval (BM25):
- Catches exact matches: product SKUs, error codes, specific terminology
- Much smaller index, extremely fast
Fusion: Use Reciprocal Rank Fusion (RRF) to merge the two ranked lists before reranking. RRF is parameter-free and works well in practice.
Reranking
A cross-encoder rescores the merged candidate set (top 50 from each retriever = ~100 after dedup). Cross-encoders see the full query-document interaction and provide much better relevance scores than cosine similarity. Keep the top 5 chunks for generation.
Caching Layers
- Response cache: Exact query match (after normalization) → full response. Key:
(tenant_id, normalized_query, index_version). - Embedding cache: Frequently-seen queries → pre-computed vectors.
- LLM prefix cache: Cache the system prompt tokens (often 1-2k tokens of instructions) to reduce prefill time on every request.
- Semantic cache (optional): Use cautiously - only for near-exact FAQ matches to avoid serving stale or incorrect answers.
Include index_version (incremented on any update) in cache keys so stale entries are automatically invalidated.
4. Multi-Tenancy & Security
Isolation:
- Every query includes
tenant_id, injected by the API gateway (never trusted from client) - Vector/BM25 queries use mandatory filters:
WHERE tenant_id = ? AND status = 'active' - Large tenants get dedicated index shards; small tenants share shards with partitioning
- ACL groups applied at retrieval time if doc-level permissions exist
Testing: Add a canary probe that verifies tenant A's queries never return tenant B's documents.
5. Updates & Deletions
Updates:
- Increment document version, re-chunk and re-embed
- Write new chunks with
version = N+1 - Atomically flip the document's active version pointer
- Old chunks marked inactive, cleaned up async
Deletions:
- Set
status = 'deleted'immediately - Retrieval filters on
status = 'active', so deletions effective instantly - Cache invalidation: increment tenant's
index_versionto expire all cached entries - Physical deletion (for compliance) purges index, database, and logs
6. Failure Modes & Fallbacks
| Failure | Response |
|---|---|
| Empty retrieval or low scores | Ask clarifying question or escalate to human; don't let LLM answer from parametric knowledge |
| Retrieval timeout | Use only the index that responded; if both fail, return "please try again" |
| Reranker timeout | Skip reranking, use RRF-fused order |
| LLM timeout or unavailable | Fall back to smaller/faster model, then to escalation message |
| Stale cache | Prevented by versioned cache keys + TTL backstop |
7. Safety & Guardrails
Input:
- Classify for abuse, jailbreaks, PII leakage attempts
- Sanitize but don't block legitimate edge cases (e.g., debugging error messages that look like injections)
Output:
- Require citations: configure the LLM to always reference source chunks
- Groundedness check: verify answer is supported by retrieved text (lightweight NLI model or LLM self-verification)
- Abstain if confidence is low or citations are weak
- Redact PII before logging
8. Capacity Estimates
Index sizing:
- 50M chunks × 768 dims × 4 bytes (fp32) = 153 GB for vectors
- With int8 quantization: ~38 GB + ~12 GB for HNSW graph (M=32) = 50 GB per replica
- BM25 index: ~25 GB
- Need 3 shards × 2 replicas = 6 vector index instances with ~64 GB RAM each
Throughput:
- Vector search: one replica handles 200+ QPS; not a bottleneck
- Reranking: 50 QPS × 100 pairs = 5k pairs/sec; one GPU handles this
- LLM: 50 QPS × 3k tokens = 150k prefill tokens/sec + ~10k decode tokens/sec. Size GPU fleet or API tier accordingly.
Costs (using hosted LLM):
- Embedding: 50M chunks × 400 tokens = 20B tokens at $0.02/1M ≈ $400 one-time
- LLM inference: ~$0.0006 per query (3k input + 200 output tokens)
- At 20 QPS sustained:
1.7M queries/day = **$1,000/day** - Caching (20-30% hit rate on FAQs) reduces cost by $200-300/day
9. Evaluation Plan
Offline metrics:
- Retrieval: Recall@5, Recall@50, nDCG@10 on a golden set (~2k labeled queries)
- Generation: Answer correctness (LLM-as-judge or human eval), hallucination rate (claims not in sources), citation quality
Experiment: BM25+reranker vs dense-only:
- Hypothesis: Hybrid improves recall on product-specific queries
- Split evaluation set by query type (factual vs navigational vs product-specific)
- Measure recall improvement and latency impact
Online A/B test:
- Metrics: thumbs-up rate, escalation rate, response latency, cost per query
- Segment by query complexity and tenant
- Run for 1-2 weeks to reach significance
10. Prioritization Under Time Pressure
Must have (core MVP):
- Basic chunking + single retriever (dense or BM25)
- Simple LLM integration with citations
- Multi-tenant filtering
- Latency budgets and timeouts
High value, add next: 5. Hybrid retrieval + reranking (big quality boost) 6. Response caching (easy latency/cost win) 7. Output guardrails (groundedness check)
Defer if needed: 8. Query rewriting (mainly helps multi-turn) 9. Semantic cache (risky, requires tuning) 10. Advanced failure modes and canary tests
Reasoning: Get a working, safe pipeline first. Hybrid search and caching offer the best ROI for quality and latency. Advanced features can be A/B tested post-launch.
Common Mistakes
- Ignoring tenant isolation: Filtering only in application code (not infrastructure) risks leakage
- No fallback for low-confidence retrieval: The LLM will hallucinate if forced to answer without good context
- Tight coupling: If one component fails, the whole system breaks; design timeouts and fallbacks
- Cache invalidation bugs: Not versioning cache keys leads to serving stale or cross-tenant data
- Underestimating LLM cost: At scale, generation dominates cost; always estimate $/query