Zero Labs
Industry News / AI

Building a RAG Pipeline That Doesn’t Fall Apart

Source · Towards AI By Moiz Ezzy

From the publisher’s feed, collected in the ZeroLabs newsroom.

Source: Created by AuthorI thought we were done in two weeks.The prototype was working. You typed a question, the system found the right documents, the LLM synthesized a clean answer. Our internal Slack was buzzing. A VP called it “genuinely impressive.” We demoed it to three teams in one afternoon.Six weeks later, I was staring at a 3AM alert. The pipeline had been silently returning confident, fluent, completely wrong answers for four hours. Nobody had noticed because the system never crashed. There were no 500 errors. No latency spikes. Just an AI that had quietly lost the plot and users who trusted it.That’s the thing about RAG systems that nobody warns you about. They don’t fail loud. They fail soft.This is the article I wish I had before we built that system.What is RAG, and Why Does It Break in Ways You Don’t Expect?The basic flow looks deceptively simple:User query → Embed the query into a vector → Search a vector database for similar document chunks → Stuff the top-k chunks into the LLM prompt → Return the generated answerIt’s simple enough to prototype in an afternoon. That’s actually the trap.Because each of those arrows hides a failure mode. And unlike a REST API that returns a 404 when something goes wrong, a broken RAG pipeline returns a 200 with a confidently stated lie.The Anatomy of Our Pipeline (Before It Broke)Here’s what we built. A knowledge base assistant for internal documentation the kind of tool every engineering team wants and nobody wants to maintain.Clean. Straightforward. Worked great in staging. ┌─────────────────┐ User question ──▶ │ Embedding API │ ──▶ query vector └─────────────────┘ │ ▼ ┌─────────────────┐ │ Vector Store │ ──▶ top-5 chunks │ (pgvector) │ └─────────────────┘ │ ▼ ┌─────────────────┐ top-5 chunks ──▶ │ Prompt Builder │ + user question └─────────────────┘ │ ▼ ┌─────────────────┐ │ LLM (GPT-4) │ ──▶ Answer └─────────────────┘Failure #1: The Chunking Problem (Or: Why Your Documents Are Lying to Your Model)The first thing that broke wasn’t the code. It was our assumptions about documents.A runbook for “restart the payment service” got split mid-step. Step 3 ended up in one chunk. Step 4 the one that says “only do this after verifying the database checkpoint” ended up in the next chunk. When someone asked how to restart the payment service, the model retrieved chunk A and gave a confident, dangerous, incomplete answer.The lesson: Fixed-size chunking is a baseline, not a strategy.What actually works in production:from langchain.text_splitter import RecursiveCharacterTextSplitter# Don't just split by token count.# Split by structure first — respect document boundaries.splitter = RecursiveCharacterTextSplitter( chunk_size=512, chunk_overlap=64, # overlap prevents context loss at boundaries separators=[ "\n## ", # respect heading boundaries first "\n### ", "\n\n", # then paragraph breaks "\n", # then line breaks ".", # sentences last ])# Always attach metadata — you'll need it for debugging laterchunks = splitter.create_documents( texts=[doc.content], metadatas=[{ "source": doc.source_url, "doc_type": doc.doc_type, # runbook, adr, wiki, etc. "last_updated": doc.updated_at, "section": doc.section_title }])The overlap is not optional. Without it, a sentence split across a boundary loses its meaning in both chunks. With 64-token overlap, each chunk has enough context from its neighbour to stand alone.We also added document-type-aware chunking runbooks got split at step boundaries, not at token counts. It took an extra day. It prevented the dangerous incomplete answers.Failure #2: Retrieval That Looks Right But Isn’tThree weeks in, we started getting user complaints. “The system keeps giving me docs from last year.” “It answered my Kubernetes question with an AWS answer.”Our retrieval was returning semantically similar but contextually wrong documents. High cosine similarity does not mean high relevance. It means the vectors are close. That’s not the same thing.We were running pure vector similarity search with no filters. A query about “restarting a service in production” was matching against a blog post someone had imported about “restarting your career in a new city.” Same semantic neighbourhood. Very different intent.The fix: hybrid search + metadata filtering.from pgvector.sqlalchemy import Vectorfrom sqlalchemy import textasync def retrieve_chunks( query_embedding: list[float], doc_type: str | None = None, max_age_days: int = 90, top_k: int = 5) -> list[Chunk]: # Combine vector similarity with hard filters # Never let old or irrelevant doc types pollute your context query = text(""" SELECT id, content, metadata, source_url, 1 - (embedding :query_vec) AS similarity FROM document_chunks WHERE -- Hard filter: doc type if specified (:doc_type IS NULL OR metadata->>'doc_type' = :doc_type) -- Hard filter: freshness — stale docs mislead more than they help AND updated_at >= NOW() - INTERVAL ':max_age days' -- Soft filter: minimum similarity threshold AND 1 - (embedding :query_vec) > 0.72 ORDER BY embedding :query_vec LIMIT :top_k """) results = await db.execute(query, { "query_vec": str(query_embedding), "doc_type": doc_type, "max_age": max_age_days, "top_k": top_k }) return results.fetchall()The 0.72 similarity threshold was the number we tuned over two weeks of eval. Below that, almost nothing useful was being retrieved — just noise that confused the model. Above 0.85, we were missing genuinely relevant docs that used different terminology.That threshold is your most important hyperparameter. Log it. Track it. It will drift as your document corpus changes.Failure #3: The Embedding Drift Nobody Told Us AboutThis is the one that caused the 3AM alert.Three months after launch, OpenAI quietly updated their text-embedding-ada-002 model. Not a breaking change by any API definition. Same endpoint, same request format, same response shape. Just... slightly different vectors.Our entire vector index had been built with the old model. Our query embeddings were now being generated by the new model. The distance calculations were meaningless we were comparing apples to slightly different apples, and the system had no idea.Retrieval quality collapsed silently. The model kept generating fluent answers. The answers were based on wrong context. Nobody noticed for four hours because there were no errors to alert on.What we built after that incident:import hashlibimport jsonclass EmbeddingVersionGuard: """ Tracks the embedding model version used to build the index. Raises an alert if the query model doesn't match. This is the canary in your RAG coal mine. """ def __init__(self, vector_store_client, metrics_client): self.store = vector_store_client self.metrics = metrics_client async def get_index_model_fingerprint(self) -> str: """Sample 10 random chunks and hash their embedding dimensions + model tag.""" samples = await self.store.sample_chunks(n=10) fingerprint_data = { "model": samples[0].metadata.get("embedding_model"), "dimensions": len(samples[0].embedding), "sample_norm": round(sum(s.embedding[0] for s in samples) / 10, 4) } return hashlib.md5( json.dumps(fingerprint_data, sort_keys=True).encode() ).hexdigest() async def validate_or_alert(self, current_model: str, current_dimensions: int): stored_fingerprint = await self.store.get_metadata("embedding_fingerprint") current_fingerprint = hashlib.md5( json.dumps({ "model": current_model, "dimensions": current_dimensions, }, sort_keys=True).encode() ).hexdigest() if stored_fingerprint != current_fingerprint: # This is a page-worthy event — retrieval quality is now undefined self.metrics.increment("rag.embedding_drift_detected") raise EmbeddingMismatchError( f"Index built with different embedding model. " f"Expected: {stored_fingerprint}, got: {current_fingerprint}. " f"Re-index required before serving queries." )The rule we established: the model that built the index must be the model that runs queries. Always. No exceptions. Any model update triggers a full re-index before traffic switches over. It’s expensive. It’s also the only correct behaviour.Failure #4: Context Window Stuffing (Or: More Is Not Better)Early on, we defaulted to retrieving the top 10 chunks and stuffing them all into the prompt. More context, better answers seemed logical.It wasn’t. It was backwards.When you give an LLM 10 chunks, it doesn’t carefully read all 10 and synthesize the best answer. It gets confused by the noise, loses the signal in the middle of the context window (a well-documented phenomenon called “lost in the middle”), and hedges. Our answers got longer, vaguer, and more frequently wrong.The sweet spot for most RAG systems is 3–5 chunks. But more importantly, the chunks you retrieve need to be ranked, not just returned.from sentence_transformers import CrossEncoder# Cross-encoders re-rank retrieved chunks with higher accuracy than# vector similarity alone. They're slower but worth it for final ranking.reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")async def retrieve_and_rerank( query: str, query_embedding: list[float], top_k_retrieve: int = 20, # cast a wide net initially top_k_final: int = 4 # return only the best) -> list[Chunk]: # Step 1: broad vector search candidates = await retrieve_chunks(query_embedding, top_k=top_k_retrieve) if not candidates: return [] # Step 2: re-rank with cross-encoder (query-aware scoring) pairs = [(query, chunk.content) for chunk in candidates] scores = reranker.predict(pairs) # Step 3: return only the top-k after re-ranking ranked = sorted( zip(candidates, scores), key=lambda x: x[1], reverse=True ) return [chunk for chunk, score in ranked[:top_k_final]]This two-stage approach broad retrieval, tight re-ranking cut our “wrong context” errors by roughly 60% in our internal evals. The cross-encoder is slower than vector similarity, but it runs on only 20 candidates, not the full corpus. It’s fast enough.Failure #5: No Eval, No Signal (The SRE Problem)Here’s where my SRE instincts finally kicked in embarrassingly late.We had been running this system for two months with no systematic way to measure whether it was working. We knew when it spectacularly failed (the 3AM incident). We had no idea how often it quietly gave a mediocre answer instead of a good one.In SRE terms: we had no SLI for retrieval quality.We built one.from dataclasses import dataclassfrom prometheus_client import Histogram, Counter, Gauge# SLIs for RAG — treat retrieval quality like a service reliability metricrag_retrieval_score = Histogram( "rag_retrieval_relevance_score", "Cross-encoder relevance score of top retrieved chunk", buckets=[0.3, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95])rag_answer_grounded = Counter( "rag_answer_grounded_total", "Answers where model cited a retrievable source", ["grounded"] # true / false)rag_fallback_rate = Counter( "rag_fallback_invoked_total", "Times the system fell back to LLM-only due to no good retrieval",)rag_empty_retrieval = Counter( "rag_empty_retrieval_total", "Queries where no chunks met the similarity threshold",)@dataclassclass RAGMetrics: """Wrap every RAG response with quality signals.""" def record_retrieval(self, top_chunk_score: float, chunk_count: int): rag_retrieval_score.observe(top_chunk_score) if chunk_count == 0: rag_empty_retrieval.inc() def record_answer(self, is_grounded: bool, used_fallback: bool): rag_answer_grounded.labels(grounded=str(is_grounded)).inc() if used_fallback: rag_fallback_rate.inc()# SLIs for RAG — treat retrieval quality like a service reliability metricrag_retrieval_score = Histogram( "rag_retrieval_relevance_score", "Cross-encoder relevance score of top retrieved chunk", buckets=[0.3, 0.5, 0.6, 0.7, 0.8, 0.85, 0.9, 0.95])Our SLO: 95% of queries should return at least one chunk with a relevance score above 0.72. When that drops below 90% over a 1-hour window, we page.That single alert would have caught the embedding drift incident within 15 minutes instead of four hours.The Fallback Strategy (For When Retrieval Genuinely Has Nothing)Not every query has a good answer in your corpus. “What’s the capital of France?” is not in your internal runbooks. You need a policy for this not silence, not hallucination, but an explicit fallback.async def answer_with_fallback(query: str) -> RAGResponse: query_embedding = await embed(query) chunks = await retrieve_and_rerank(query, query_embedding) # If retrieval confidence is too low, don't pretend otherwise if not chunks or chunks[0].relevance_score rag_fallback_rate.inc() return RAGResponse( answer=await llm_answer_without_context(query), sources=[], confidence="low", fallback_used=True, warning="This answer is based on general knowledge, not your internal docs." ) context = build_context(chunks) answer = await llm_answer_with_context(query, context) return RAGResponse( answer=answer, sources=[c.source_url for c in chunks], confidence="high", fallback_used=False )The warning field matters. Users who see "this is based on general knowledge, not your internal docs" calibrate their trust appropriately. Users who get a confident answer with no signal have no idea when to push back.Transparency is a feature.What a Production-Ready RAG Pipeline Actually Looks LikeAfter six months and several painful incidents, here’s the architecture we settled on -:Source: Created by AuthorEach box is a potential failure point. Each failure point has a metric. Each metric has a threshold. That’s the SRE mental model applied to AI.The Re-indexing RunbookOne thing nobody writes about: what happens when you need to re-index your entire corpus? It will happen. Embedding model update. Schema change. Bulk document refresh. You need a process before you need it urgently.#!/bin/bash# re-index.sh — run this before switching embedding models# Never run against the live index. Build a shadow index first.set -euo pipefailNEW_MODEL="text-embedding-3-small"SHADOW_INDEX="documents_shadow_$(date +%Y%m%d)"LIVE_INDEX="documents"echo "Building shadow index: ${SHADOW_INDEX}"# Step 1: Create shadow index with new embeddingspython3 scripts/build_index.py \ --model "$NEW_MODEL" \ --index "$SHADOW_INDEX" \ --batch-size 100 \ --workers 4# Step 2: Run eval suite against shadow indexecho "Running eval against shadow index..."python3 scripts/eval_retrieval.py \ --index "$SHADOW_INDEX" \ --test-set evals/golden_set.json \ --min-ndcg 0.80 # don't promote if quality drops# Step 3: Only promote if eval passesecho "Promoting shadow index to live..."python3 scripts/promote_index.py \ --from "$SHADOW_INDEX" \ --to "$LIVE_INDEX" \ --zero-downtime # swap atomically, keep old index for 24h rollbackecho "Re-index complete. Monitor rag_retrieval_relevance_score for 30 minutes."The golden set (evals/golden_set.json) is a manually curated set of 50–100 query/expected-source pairs. You build it once, you maintain it as your corpus grows, and it is your quality gate before every index change. It's the equivalent of a smoke test suite for your retrieval layer.The ChecklistIf you’re building a RAG system right now, here’s what to verify before you call it production-ready:IngestionChunking respects document structure, not just token countChunks have meaningful overlap (50–100 tokens)Every chunk carries metadata: source, type, timestamp, sectionEmbedding model version is stored with every chunkRetrievalMetadata filters prevent stale or irrelevant docs from polluting contextMinimum similarity threshold is tuned and documentedCross-encoder re-ranking applied to final candidate setEmpty retrieval is handled explicitly, not silentlyReliabilityEmbedding version guard alerts if model/index mismatch is detectedCircuit breaker on the LLM provider (provider outages happen)Explicit fallback policy when retrieval confidence is lowGrounding check: does the answer reference the retrieved context?ObservabilityRetrieval relevance score is a tracked metric with an SLOFallback rate is tracked and alerted onEmpty retrieval rate is tracked and alerted onQuery latency is broken down by stage (embed / retrieve / rerank / generate)OperationsShadow index process exists for model/schema changesGolden eval set with minimum NDCG threshold gates index promotionsRe-index runbook is documented and tested before you need itKey TakeawaysRAG fails soft. No errors, just wrong answers delivered confidently. Design your monitoring assuming the system will betray you silently.Chunking is strategy, not implementation. Respect document structure. Add overlap. Store metadata on every chunk.Vector similarity is not relevance. Add metadata filters and a re-ranker. The two-stage pipeline (broad retrieval → tight re-ranking) is worth the complexity.Embedding drift is a production incident. Version your embeddings. Build a guard that detects mismatches before they cause four hours of silent failures.Define your SLO before you launch. Retrieval relevance score is your SLI. Fallback rate is a leading indicator of corpus decay. Instrument both from day one.Transparency is a feature. Tell users when you’re in fallback mode. An honest “I’m not sure” is better than a confident lie.“A RAG system that fails loudly is a good RAG system. A RAG system that fails silently is the most dangerous tool you’ve ever shipped.”If this helped you, consider following for more production engineering stories. I write about SRE, cloud infrastructure, and building AI systems that actually stay up.Building a RAG Pipeline That Doesn’t Fall Apart was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.