I Broke RAG at 50K Documents. Here’s What Actually Works at 1 Million.
From the publisher’s feed, collected in the ZeroLabs newsroom.
A no-fluff engineering guide to production RAG — the stuff I wish someone had told me before I wasted three months chasing the wrong bottlenecks.1.1 Rag in production and where it breaks!Let me start with something nobody wants to admit: most RAG tutorials are useless for production.They embed 200 PDFs, hit 95% accuracy on a toy benchmark, and ship it. Then you come along trying to handle a million support tickets, a decade of legal documents, or a sprawling enterprise knowledge base — and the whole thing falls apart in ways that are genuinely hard to debug.I’ve been through this. We started with a reasonably clean setup: OpenAI embeddings, a basic FAISS index, LangChain retrieval chain. It worked great in staging. In production, with real query volume and a corpus that kept growing, latency went sideways and recall dropped off a cliff. We spent days thinking it was a model problem. It wasn’t. It was an engineering problem, almost entirely in the retrieval layer.This is what we learned.The real bottlenecks (they’re not where you think)When RAG gets slow or inaccurate at scale, people immediately blame the LLM or the embedding model. In my experience, the actual culprits are almost always:A vector index that wasn’t built for the data sizeEmbeddings that don’t get batched properly during ingestionNo reranking — so you’re passing mediocre chunks straight to the LLMContext that’s assembled in the wrong order (yes, this matters a lot)Let’s go through the whole pipeline, layer by layer.Before retrieval even starts — the query layerThis is probably the most underrated part of the whole system. Most teams spend weeks optimizing their vector store and then just pass raw user queries straight into it. That’s a mistake.User queries are messy. They use abbreviations, skip context, use pronouns without referencing the noun. “How does it handle auth?” is a real query I’ve seen in production. When you embed that and search for it, you’re going to get mediocre results because the embedding of a vague question doesn’t live anywhere near the embeddings of detailed technical documentation that answers it.Query rewriting is the fix. Before hitting your index, run a lightweight LLM call — GPT-3.5-turbo or a small local model is fine — that expands the query into a cleaner, more explicit version. Takes ~100ms and meaningfully improves recall. Worth every millisecond.The more aggressive version of this is HyDE — Hypothetical Document Embeddings. Instead of embedding the question, you generate a hypothetical answer to the question and embed that. The intuition is that a fake answer lives in the same embedding neighborhood as real answers, whereas a question lives somewhere else entirely. Weird as it sounds, it works. We saw 12–15% recall improvement on our knowledge-dense corpus.Semantic caching is the third piece. At scale, a surprising percentage of queries are variations on the same handful of questions. Cache the retrieval results keyed on embedding similarity — if a new query has cosine similarity > 0.97 with a cached one, just return the cached results. With Redis and a small in-memory FAISS index over cached queries, we hit a 40-ish percent cache rate within two weeks of production traffic. That’s 40% of queries that skip the vector store entirely.The vector index — where most of the performance livesAt a million documents, index choice isn’t academic. It determines whether your p99 latency is 30ms or 3 seconds.HNSW is the default for most use cases. It’s an in-memory graph structure — hierarchical layers of connections that let you navigate to approximate nearest neighbors extremely efficiently. At 1M vectors with decent ef values, you’re looking at ~10ms query latency and recall around 0.97. The catch is memory. 1536-dimensional OpenAI embeddings take about 24GB RAM for a million vectors before graph overhead.The fix is quantization. Scalar quantization to int8 cuts memory to roughly 6GB with less than 2% recall loss. If you’re on Qdrant, this is one config parameter. Do it.IVF-PQ is what you reach for when memory is genuinely constrained. It clusters your vector space into Voronoi regions and compresses each vector with product quantization, getting you down to 64–128 bytes per vector. A million vectors in under 512MB. The tradeoff is that you need to tune nprobe carefully — how many clusters you scan at query time — and accept slightly softer recall guarantees.For disk-based workloads, DiskANN (from Microsoft Research) is the modern answer. Near-HNSW recall, running entirely off SSD. If you can’t fit your index in RAM and you need better recall than IVF-PQ, this is the path.The most important single change you can make to retrieval: go hybrid.Pure vector search misses exact keyword matches. Somebody searches for a specific product SKU or a proper noun, and cosine similarity on embeddings doesn’t help you. Pure BM25 (keyword search) misses semantic meaning — synonyms, paraphrases, related concepts.Run both in parallel. Combine the results with Reciprocal Rank Fusion:def reciprocal_rank_fusion(dense_results, sparse_results, k=60): scores = {} for rank, doc_id in enumerate(dense_results): scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1) for rank, doc_id in enumerate(sparse_results): scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank + 1) return sorted(scores, key=scores.get, reverse=True)RRF is simple, robust, and doesn’t require tuning blend weights. In every benchmark I’ve run on our data, hybrid consistently beats either approach alone — usually by 8–12% NDCG. This is table stakes for production RAG now.Chunking — the silent killerBad chunking strategy is responsible for more RAG failures than any other single factor, and it’s the thing that’s hardest to debug because the failures look like model failures.The naive approach — split every document into 512-token chunks at regular intervals — has an obvious flaw: it cuts sentences mid-thought, separates headers from content, and destroys paragraph coherence. Your embedding for a chunk that starts mid-sentence is meaningfully worse than one for a complete semantic unit.Semantic chunking splits on content similarity rather than token count. Compute embeddings for consecutive sentences; when cosine similarity drops below a threshold (around 0.7 works well), that’s a natural topic boundary. This sounds expensive but you only do it at ingestion time, not query time.The pattern I’d actually recommend for production is hierarchical chunking, sometimes called small-to-big retrieval. Store small chunks — 128 tokens or so — for retrieval purposes. But when you surface a result, return the parent chunk (512 tokens) as the actual context. Small chunks give you precise embedding matches; parent chunks give the LLM enough surrounding context to answer coherently. The precision of a scalpel, the context of a page.If you’re dealing with questions that require synthesizing information across multiple sections or documents — multi-hop questions — you need RAPTOR. It clusters chunks, summarizes each cluster with an LLM, embeds the summary, and repeats recursively. You end up with a tree of summaries at different granularities. It handles the kind of question that flat retrieval simply can’t answer: “How does our refund policy differ across enterprise vs. standard plans?” That answer might live across five separate documents and requires a summary-level understanding to retrieve properly.Reranking — the step most teams skipFirst-stage retrieval is optimizing for recall. You want the right answer somewhere in your top-50 results. Reranking is optimizing for precision. You want it at position 1.These are different problems that need different approaches.A bi-encoder (which is what you’re using for vector search) embeds the query and each document independently and compares them. Fast, but it misses interaction effects. A cross-encoder reranker takes the query and each candidate chunk together as a single input and scores the pair directly. It sees the full semantic interaction. It’s 2–3x slower per query, but it’s also substantially more accurate.The practical pattern: retrieve top-50 with hybrid search → rerank to top-5 with a cross-encoder. Options include Cohere Rerank, BGE-reranker, and Jina Reranker. Run it only on your top-20 or top-50 — not on the full corpus obviously.ColBERT is worth knowing about as a middle ground. It computes token-level embeddings offline and uses a MaxSim scoring function at query time. Close to cross-encoder quality at something closer to bi-encoder speed. If latency is critical and you still want the quality, ColBERT is the answer.I’ve seen teams go from 60% answer accuracy to 82% just by adding a reranking step after retrieval, with no other changes. It’s the highest-leverage addition to a mature retrieval pipeline.Context assembly — details that make a real differenceBy the time you’ve retrieved and reranked your top-5 chunks, you’re almost there. But how you assemble those chunks into context still matters.There’s a documented phenomenon called “lost in the middle” — LLMs recall information at the beginning and end of their context window better than the middle. If you just concatenate your chunks in order of retrieval score, chunks 3 and 4 are going to get less attention than chunks 1 and 5. The fix is to put your most relevant chunk first, your second-most-relevant last, and the rest in between. Slight reorganization, meaningful quality improvement.Metadata filtering needs to happen at the index level, not after retrieval. If a query is about Q3 2024 financials, filter on year=2024, quarter=3 before the vector search happens. Most modern vector databases support pre-filtering — Qdrant's payload filtering is particularly good. If you filter after retrieval, you wasted compute retrieving irrelevant documents and then discarding them.Context compression is worth knowing about for high-volume systems. Tools like LLMLingua can compress prompt context by 3–5x while preserving the semantic content the LLM needs to answer the question. At scale, that’s direct cost reduction and latency reduction. Not something you need on day one, but worth having in the toolkit.Infrastructure choices at this scaleVector database: Qdrant and Weaviate are the production workhorses right now. Qdrant’s Rust implementation handles 1M vectors with HNSW plus scalar quantization in around 4GB RAM and has excellent payload filtering for metadata. Weaviate has first-class hybrid search (BM25 + vector) built in natively. Pinecone is great if you want a serverless option and want to skip ops entirely. I’d stay away from running raw FAISS in production unless you’re wrapping it with persistence, filtering, and distributed support yourself — that’s a lot of engineering work that the dedicated databases have already done for you.Embedding ingestion: Never embed synchronously on the write path. The moment a document comes in, drop it on a queue — Celery with Redis works fine; Kafka if you have serious throughput. Process ingestion asynchronously. More importantly, batch your embedding calls. OpenAI’s batch API runs at 50% cost, and calling with batches of 2048 texts instead of one at a time is a 20–30x throughput improvement. This is so easy to do and so often ignored.Observability: This is what separates production RAG from a demo. Without instrumentation, you’ll have no idea whether a degradation in answer quality is coming from retrieval, reranking, context assembly, or the LLM itself. At minimum, track:Retrieval recall@k — does your ground-truth answer land in the top-k retrieved chunks? You need an eval set for this.Latency broken down by pipeline stage. Is the bottleneck the vector store? The reranker? The LLM?Cache hit rate on your semantic cache.Answer faithfulness using Ragas or DeepEval — automated scores comparing the answer to the retrieved context.Run faithfulness scoring in your CI pipeline. If a change to your chunking or retrieval drops faithfulness by more than a threshold, catch it before it hits users.What this looks like end-to-endA query comes in. Before anything else, check the semantic cache — if a similar query was handled recently, return the cached result immediately. No vector store, no LLM call.On a cache miss, rewrite the query (and optionally generate a HyDE document). Run hybrid retrieval — dense vector search and BM25 in parallel, merged with RRF — with metadata pre-filters applied at the index. Take the top-20 or so results.Pass those candidates to a cross-encoder reranker. Get your top-5. Assemble context with most relevant first, least relevant last. Compress if you’re watching token costs. Stream the LLM response.Cache the result. Log the retrieval chunks, the reranked order, the answer, and the faithfulness score.The performance targets that are achievable with this architecture on commodity hardware:Stage Target Semantic cache hit The honest summaryMost RAG problems aren’t model problems. They’re retrieval problems and infrastructure problems. I spent too long tweaking prompts and switching embedding models before I understood that the retrieval layer was the actual constraint.If I had to prioritize: get hybrid retrieval working first, then add a reranker, then fix your chunking, then tune the rest. Each of those steps has an outsized impact relative to the effort involved. The semantic cache and batched async ingestion are operational necessities once you have any real query volume — add them early.The rest — query rewriting, HyDE, context compression, RAPTOR — are real improvements but they’re refinements. Get the foundation right first.If this was helpful, the follow-up I’m planning is a deep dive on RAG evaluation — how to build an eval set, what metrics actually matter, and how to run automated quality regression in CI. Follow along if that’s interesting to you. I am a data scientist and AI engineer with 10 years of experience.I Broke RAG at 50K Documents. Here’s What Actually Works at 1 Million. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.