Every RAG tutorial works cleanly on 50 PDFs. At 500,000 technical documents, naive fixed-size chunking collapses: the retriever pulls isolated table rows without headers, embeddings blur similar product SKUs together, and the LLM confidently invents answers from partial context.
Quick Answer: At 500,000 documents, pure vector RAG failed 34% of our clientโs queries due to broken table chunks and keyword dilution. Switching to parent-child hierarchical chunking, hybrid BM25 + vector RRF fusion, and a cross-encoder reranker raised answer accuracy from 66% to 94.5% at โน0.14 per query.
Key Architecture Takeaways
- Fixed 500-Token Chunks Destroy Context: Splitting Markdown tables or pricing clauses mid-sentence strips the column headers and conditions the LLM needs to reason accurately.
- Parent-Child Retrieval: Index small 250-token child chunks for sharp vector matching, then return the full 1,200-token parent section to the LLM.
- Hybrid RRF (BM25 + Dense): Dense embeddings miss exact error codes, GST numbers, and model IDs (
ERR_504_VALKEY). Reciprocal Rank Fusion (RRF) merges exact keyword hits with semantic matches. - Cross-Encoder Reranking: Reranking the top 40 hybrid candidates down to the top 6 before generation eliminates 80% of "lost in the middle" hallucinations.
flowchart TD
A[500k Enterprise Docs: PDFs / SOPs / Tables] --> B[Parent-Child Chunker: 1200t Parent / 250t Child]
B --> C[Hybrid Index: BM25 + Dense Vectors]
D[User Query] --> C
C --> E[Top 40 Candidates via RRF Fusion]
E --> F[Cross-Encoder Reranker: Top 6 Parents]
F --> G[94.5% Grounded Accuracy | โน0.14/Query]
The โน4,20,000 Mistake We Debugged in Junagadh
Earlier this year, a B2B manufacturing client came to my Junagadh lab after spending โน4,20,000 with an external vendor on an internal SOP assistant. Their 500,000-document knowledge base had a 34% error rate on warranty and SKU queries. When engineers asked "What is the torque spec for Valve X-402?", the vector DB returned specs for Valve X-408 because both sentences shared 95% identical phrasing.
We replaced the entire ingestion and retrieval pipeline in 9 days without changing their LLM provider:
# hybrid_rerank_rag.py โ Reciprocal Rank Fusion + Parent-Child Lookup
from collections import defaultdict
def reciprocal_rank_fusion(
dense_ids: list[str],
bm25_ids: list[str],
k: int = 60,
top_n: int = 40,
) -> list[tuple[str, float]]:
# Merge dense semantic hits and exact BM25 hits without score normalization issues.
scores: dict[str, float] = defaultdict(float)
for rank, doc_id in enumerate(dense_ids, start=1):
scores[doc_id] += 1.0 / (k + rank)
for rank, doc_id in enumerate(bm25_ids, start=1):
scores[doc_id] += 1.0 / (k + rank)
return sorted(scores.items(), key=lambda x: x[1], reverse=True)[:top_n]
def expand_to_parent_sections(child_ids: list[str], child_to_parent: dict[str, str], parent_store: dict[str, str]) -> list[str]:
# Deduplicate and return full parent context blocks in ranked order.
seen = set()
contexts = []
for cid in child_ids:
pid = child_to_parent.get(cid, cid)
if pid not in seen and pid in parent_store:
seen.add(pid)
contexts.append(parent_store[pid])
return contexts
# table_aware_chunker.py โ Never Split Markdown Tables Mid-Row
def split_preserving_tables(markdown: str, max_chars: int = 1800) -> list[str]:
blocks = markdown.split("
")
chunks, current = [], []
current_len = 0
for block in blocks:
is_table = block.strip().startswith("|")
if current and (current_len + len(block) > max_chars) and not is_table:
chunks.append("
".join(current))
current, current_len = [], 0
current.append(block)
current_len += len(block)
if current:
chunks.append("
".join(current))
return chunks
Before vs After: 500k-Document Production Metrics
| Metric | Naive Vector RAG (Before) | Hybrid + Rerank + Parent-Child (After) | Delta |
|---|---|---|---|
| Verified Answer Accuracy | 66.0% | 94.5% | +28.5% |
| Exact SKU / Code Recall | 41.0% | 98.2% | +57.2% |
| P95 End-to-End Retrieval | 180 ms | 290 ms | +110 ms (acceptable) |
| Cost Per Query (INR) | โน0.11 | โน0.14 | +โน0.03 |
Ingestion & Evaluation Lessons from 500k Documents
Fixing retrieval at 500,000+ documents is as much about ingestion hygiene and automated evaluation as it is about vector math. During our 9-day overhaul in Junagadh, three additional practices locked in the 94.5% accuracy score:
-
Preserve Document Lineage & Section Headers: Every child chunk carries a compact header prefix (
[Doc: Valve-X402-Spec | Section: Torque Limits]) prepended before embedding. Even when a paragraph contains pronouns like "it must not exceed 45 Nm", the embedding retains the exact product identity. -
Build a 100-Question Golden Eval Set First: Before tuning
k, chunk sizes, or reranker models, we collected 100 real questions that failed in productionโincluding tricky SKU lookups, multi-page warranty tables, and Hinglish/abbreviated queriesโand measured Recall@10 and groundedness on every code change. -
Enforce Strict Citation Grounding: Our generation prompt requires the LLM to cite the exact
[doc_id]for every technical number it outputs, and refuses to answer when the top reranked score falls below0.35. Saying "Not found in approved SOPs" is infinitely cheaper than hallucinating a wrong torque limit on a factory floor. -
Incremental Hash-Based Re-Indexing: When a PDF updates, we hash each section with SHA-256 and only re-embed changed sections, cutting nightly re-indexing costs by 92%.
-
Separate Vector Updates from Metadata Updates: When a documentโs access permissions or approval status changes without text edits, update only the PostgreSQL or Qdrant payload metadata in place instead of paying to re-compute 1,536-dimensional embeddings.
-
Monitor Retrieval Score Drift Weekly: Track the median cosine similarity and cross-encoder rerank score across live user queries. If median scores drop after a new batch of scanned PDFs is ingested, inspect OCR quality immediately before users start seeing degraded answers.
-
Cache Repeated Enterprise Queries in Valkey: In B2B internal knowledge bases, 30%โ40% of employee questions repeat weekly. Hashing normalized queries and caching verified cited answers for 6 hours cuts reranker and LLM costs by a third.
When NOT to Use Hybrid Rerank RAG
- Small Static Datasets (< 100k Tokens): If your entire knowledge base fits inside a single 128k-token prompt with prompt caching, skip RAG completely. Prompt caching is simpler and has zero retrieval miss rate.
- Real-Time Transactional Lookups: Never use RAG to check live inventory counts or order statusesโexpose a typed SQL/API tool call instead.
Build Reliable Knowledge Systems Skip weeks of RAG debugging with AI Codebase Documentation & Knowledge Agent and Multi-Agent Deep Research & Competitive Dossier Engine. Clean and inspect your ingestion documents with our free PDF Compress and Word Counter utilities.
References & Engineering Papers
- Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods
- Anthropic Contextual Retrieval Engineering Guide
- PostgreSQL Full-Text Search (
tsvector) Documentation
Related Engineering Guides
Frequently Asked Questions
Why does pure vector search fail on SKU codes and error IDs?
Embedding models compress meaning into dense geometry, so ERR_504 and ERR_502 look almost identical mathematically. BM25 keyword matching catches exact alphanumeric tokens.
How much latency does a cross-encoder reranker add?
Reranking 40 short passages on a GPU or hosted rerank API adds 60msโ110ms, which is negligible compared to 1,500ms+ LLM generation time.
What is parent-child chunking?
You embed small 200โ300 token child chunks for precise matching, then pass the surrounding 1,000โ1,500 token parent section to the LLM so it never loses surrounding context.
Should I delete old RAG chunks when documents update?
Always use deterministic document hashes (sha256(doc_id + version)) to upsert and prune stale chunks atomically so outdated policies never surface.