RAG in Production
After this lesson, you will be able to:
- Build a 'report card' for your RAG system using four RAGAS metrics: faithfulness (Is the answer grounded in the retrieved sources?), answer relevancy (Does it address the question?), context precision (Are the retrieved chunks useful?), and context recall (Did retrieval find all the relevant information?)
- Set up monitoring, caching (so repeated questions are instant and free), and cost controls to keep your RAG system fast and affordable in production
- Spot the ways a RAG system fails silently, wrong answers with high confidence, and build guardrails so it says 'I am not sure' instead of making things up
- Construct a robust evaluation dataset that covers happy-path queries, multi-hop queries, out-of-corpus queries, and adversarial queries, and run automated evaluation on a schedule to catch quality regressions before users do
Before you start
This is the lesson that separates hobbyists from professionals. Building a RAG demo is a weekend project. Running one in production that people trust is engineering. You are about to learn the skills that make that jump possible.
#Measuring the Unmeasurable
A RAG system that works perfectly in demos can fail catastrophically in production. Documents change, user queries are unpredictable, edge cases multiply, and silent failures, wrong answers delivered with confidence, erode trust. This lesson covers the full production lifecycle: evaluation, monitoring, caching, scaling, and cost control.
#RAGAS: The Evaluation Framework
#1. Faithfulness
Does the generated answer faithfully represent the retrieved context? Or does the LLM add information that is not in the context (hallucinate)?
#2. Answer Relevancy
Is the answer relevant to the question? An answer can be faithful to the context but completely miss the point of the question.
#3. Context Precision
Of the retrieved contexts, how many were actually relevant? High precision means you are not wasting context window space on irrelevant chunks.
The current RAGAS library averages this precision at each rank where a relevant chunk appears, so it also rewards ranking relevant chunks first; that rank-aware form is derived in RAG Evaluation.
#4. Context Recall
Of all the information needed to answer the question, how much was actually retrieved? High recall means you are finding everything relevant.
A RAG system has high faithfulness (0.95) but low context recall (0.3). What is the user experience?
#Building an Evaluation Dataset
You need a labeled test set: questions paired with expected answers and the ground-truth relevant documents.
evaluation_set = [
{
"question": "What is the refund policy for enterprise customers?",
"ground_truth_answer": "Enterprise customers get 90-day refund windows.",
"ground_truth_contexts": ["doc_enterprise_terms_chunk_3"],
},
# ... 50-200 labeled examples
]Try it! Write 5 question-answer pairs about a topic you know well (your favorite hobby, your school subject, a book you read). For each pair, write the ideal answer and which document section it comes from. Congratulations — you just built an evaluation dataset. This is the exact process used to test production RAG systems.
#Monitoring in Production
Evaluation tells you how the system performs on a test set. Monitoring tells you how it performs on real user queries, in real time.
#Key Metrics to Track
| Metric | What It Measures | Alert Threshold |
|---|---|---|
| Retrieval latency (p50, p99) | How fast is vector search? | p99 > 500ms |
| Generation latency (TTFT) | Time to first token from LLM | > 3 seconds |
| End-to-end latency | Total time from query to response | > 5 seconds |
| Retrieval confidence | Average similarity score of top-k results | Mean < 0.5 |
| Empty retrieval rate | Percentage of queries with no relevant results | > 15% |
| Fallback rate | How often the system says "I don't know" | Spike > 2x baseline |
| Token usage per query | Prompt + completion tokens | Spike > 2x baseline |
| User feedback (thumbs up/down) | Direct quality signal | Negative rate > 20% |
| Query volume | Requests per minute | Anomalies (spikes or drops) |
#Latency Budgets and Percentiles
The end-to-end latency is the sum of the stage latencies, so the budget adds up. The percentiles do not: the p95 of the total is not the sum of the stage p95s, and budgeting each stage at its own p95 then adding wastes headroom. Open the derivation to see exactly why.
Fan-out makes tails worse, not better. If one query waits for n parallel calls (n shards of a vector index, n retrievers, n tool calls), it is as slow as the slowest. Open the derivation for how often that slowest call lands in its own tail.
Try it: leave the slow-call chance at 1 percent, drag fan-out N from 1 up to 100, and watch the median request land on a single call's p99; then switch hedging on.
#Capacity: Little's Law
How many requests are in the system at once decides how many connections, GPU slots or workers you need. Little's law ties it to throughput and latency without any assumption on arrival or service patterns.
#The Feedback Loop
#Logging Architecture
Every RAG query should log:
{
"query_id": "q_abc123",
"timestamp": "2024-03-15T10:30:00Z",
"user_query": "What is the refund policy?",
"processed_query": "customer refund return policy",
"retrieved_chunks": [
{"chunk_id": "c_456", "score": 0.87, "source": "refund_policy.pdf"},
{"chunk_id": "c_789", "score": 0.72, "source": "enterprise_terms.pdf"}
],
"generated_answer": "The standard refund policy allows...",
"model": "your-model-name",
"prompt_tokens": 1250,
"completion_tokens": 150,
"latency_ms": {"retrieval": 45, "generation": 890, "total": 1050},
"user_feedback": null
}
This logging enables retroactive analysis: when a user reports a wrong answer, you can trace exactly what was retrieved and why.
#Caching Strategies
RAG queries are expensive: embedding API call + vector search + LLM generation. Caching reduces cost and latency dramatically.
Figure
Three cache layers sit in front of the expensive path, each catching what the one above it missed. The exact query cache is a hash lookup: instant, but only fires on character-identical repeats. The semantic cache matches on embedding similarity, so it also catches paraphrases of a question already answered. Below both sits the full retrieval-and-generation pipeline, which only runs when the question is genuinely new. Hit rates climb as you move up; cost falls the same way.
#Level 1: Exact Query Cache
Cache the full response for identical queries. Simple but effective — many users ask the same questions.
import hashlib
def query_cache_key(query):
return hashlib.sha256(query.lower().strip().encode()).hexdigest()
cache = {}
def cached_rag(query):
key = query_cache_key(query)
if key in cache:
return cache[key] # Cache hit!
result = rag_pipeline(query)
cache[key] = result
return result#Level 2: Semantic Query Cache
Use embedding similarity to match semantically equivalent queries. "What's the refund policy?" and "How do I get a refund?" should hit the same cache.
#Level 3: Retrieval Cache
Cache the retrieval results (not the final answer) for recent query embeddings. The embedding + search is a share of total latency worth measuring.
#Cache Invalidation
When documents in the knowledge base are updated, cached answers that reference those documents become stale. Strategies:
- TTL-based: Expire all cache entries after N hours
- Document-aware: Track which documents each cached answer references. When a document is updated, invalidate related cache entries.
- Hybrid: Short TTL (1 hour) for fast-changing content, long TTL (24 hours) for stable content.
When a document changes, the question is how often a TTL cache still serves the old answer. Open the derivation for a simple model of that fraction, which shows how the TTL trades staleness against cost.
#Cost per Query and per Month
The effective cost of a cache is (1 - h) times the miss cost plus h times the hit cost, derived in Building a Diffusion App. What is new here is the miss cost of a RAG query, and the monthly bill. Open the derivation to build the arithmetic from the stages.
#Failure Modes and Mitigations
#Failure Mode 1: Retrieval Misses
The relevant information exists in the corpus but is not retrieved.
#Failure Mode 2: Context Poisoning
Irrelevant or contradictory information is retrieved and misleads the LLM.
#Failure Mode 3: Unfaithful Generation
The LLM ignores the retrieved context and generates from its parametric knowledge.
#Failure Mode 4: Stale Knowledge
Documents in the knowledge base are outdated, leading to correct retrieval of wrong information.
#Re-embedding: What Freshness Costs
Keeping the index fresh means embedding again. Chunk overlap makes you embed some text twice, and switching the embedding model means embedding everything. Open the derivation for the bill.
#Try It Yourself
Tests: Verify Q3 (no answer in corpus) gets high faithfulness for correctly abstaining. Verify Q4 (fabricated email) gets low faithfulness for hallucinating an email address.
#Key Takeaways
- RAGAS metrics provide systematic RAG evaluation. Faithfulness (does the answer match the context?), answer relevancy (does it address the question?), context precision (are retrieved docs relevant?), and context recall (were all needed docs found?) cover the key quality dimensions
- Caching and cost optimization are essential at scale. Embedding frequently asked questions, caching retrieval results, and using smaller models for simple queries can reduce costs several-fold without sacrificing quality (caching alone is capped at 1/(1 - hit rate))
- Production RAG systems need guardrails. Handle out-of-scope queries gracefully, detect when retrieved context is insufficient, and implement fallback strategies rather than generating confident but wrong answers
- Monitoring must cover the entire pipeline. Track latency, retrieval quality, answer quality, and user feedback at each stage; a degradation in any component cascades through the entire system
#Quick Check
What does the RAGAS 'faithfulness' metric measure?