Why This Matters at Engineering Leadership Scale
Almost every engineering team can wire up a Retrieval-Augmented Generation (RAG) demo in an afternoon: split PDFs into 500-token chunks, call an embeddings API, run cosine similarity search, and paste the top five chunks into a prompt. That naive design breaks quietly the week it hits real enterprise traffic.
Exact identifiers such as Jira keys (CORE-4812), HTTP error codes (ERR_SETTLEMENT_409), and financial tickers vanish in dense vector space. Worse, teams that fetch the top ten vectors globally and filter by tenant_id in application code create both a cross-tenant data leakage risk and empty-result bugs whenever a high-volume customer dominates the nearest-neighbor index. Finally, without an automated evaluation suite in CI, every prompt tweak or chunking adjustment turns into guesswork. At engineering leadership scale, RAG must operate like a deterministic search and testing system, not an unmonitored prompt experiment.
Core Mental Model & Architecture
A production RAG pipeline has five explicit stages, each solving a specific failure mode:
- Structure-Aware Parent-Child Ingestion: Parse Markdown headings, HTML sections, and tables cleanly instead of slicing mid-sentence. Attach mandatory metadata (
tenant_id,acl_roles,doc_type,updated_at). Embed small 256-token child chunks for high retrieval precision, while returning their 1,024-token parent blocks to the generator so the model never loses surrounding context. - Metadata & ACL Pre-Filtering: Enforce tenant and role permissions inside the database query (
WHERE tenant_id = $1 AND acl_roles && $2), never in Python or TypeScript after retrieval. - Hybrid Retrieval via Reciprocal Rank Fusion (RRF): Run
pgvectorHNSW dense vector search in parallel with PostgrestsvectorBM25-style full-text search, merging their ranks with RRF so both semantic concepts and exact IDs surface in the top 25 candidates. - Cross-Encoder Reranking: Pass the top 25 hybrid candidates through a lightweight cross-encoder reranker (such as Cohere Rerank or a hosted BGE reranker) to prune noisy matches down to the top 5 high-signal parent chunks.
- Grounded Generation & Strict Abstention: Constrain the generator to output structured JSON containing inline chunk citations (
[chunk_12]) and an explicit abstention path ("Insufficient evidence in provided documents") whenever retrieved chunks cannot support a claim.
| Component | Naive Prototype RAG | Production Enterprise RAG | Measurable Impact |
|---|---|---|---|
| Chunking | Fixed 500-token sliding window across raw text | Structure-aware 256-token child / 1,024-token parent | Prevents split tables and lost policy exceptions |
| Search Strategy | Dense cosine similarity only | Hybrid pgvector HNSW + Postgres tsvector via RRF | Captures exact Jira keys, tickers, and error codes |
| Authorization | Global top-k search + app-layer post-filtering | SQL-level tenant_id and acl_roles pre-filtering | Eliminates cross-tenant leakage and zero-result holes |
| Precision Layer | Direct top-5 vector hits to generator | Top-25 RRF candidates rescored by cross-encoder to top-5 | Raises Recall@5 and cuts irrelevant context tokens |
| Quality Assurance | Manual spot checks before deploy | 50 to 100 golden cases in CI (RAGAS + latency gate) | Blocks silent regressions on every pull request |
Step-by-Step Implementation Tutorial
Follow these four steps to build a Postgres pgvector hybrid retrieval layer and wire an automated evaluation gate into CI:
- Create Tenant-Partitioned Schema & Dual Indexes: Store child embeddings (
vector(1536)), parent text,tenant_id,acl_roles, and a generatedtsvectorcolumn in Postgres with both an HNSW index and a GIN full-text index. - Execute Pre-Filtered Hybrid RRF in One SQL Query: Filter by
tenant_idandacl_rolesinside both CTEs before fusing rankings using1.0 / (60 + rank). - Rerank & Enforce Grounded JSON Output: Rescore the top 25 parent chunks down to 5 with a cross-encoder, then pass those 5 chunks with IDs into a schema-constrained LLM call.
- Gate Merges with Automated Retrieval & Faithfulness CI Tests: Maintain 50 to 100 curated
(question, expected_chunk_ids, reference_answer)pairs and fail CI ifRecall@5,Faithfulness(target> 0.95),Answer Relevance(target> 0.90), or p95 latency regresses beyond threshold.
-- hybrid_search.sql - Tenant-isolated dense + sparse retrieval with RRF
WITH semantic_hits AS (
SELECT
c.parent_id,
ROW_NUMBER() OVER (ORDER BY c.embedding <=> $3::vector) AS dense_rank
FROM rag_child_chunks c
WHERE c.tenant_id = $1
AND c.acl_roles && $2::text[]
ORDER BY c.embedding <=> $3::vector
LIMIT 40
),
lexical_hits AS (
SELECT
c.parent_id,
ROW_NUMBER() OVER (
ORDER BY ts_rank_cd(c.search_tsv, plainto_tsquery('english', $4)) DESC
) AS sparse_rank
FROM rag_child_chunks c
WHERE c.tenant_id = $1
AND c.acl_roles && $2::text[]
AND c.search_tsv @@ plainto_tsquery('english', $4)
LIMIT 40
),
fused AS (
SELECT
COALESCE(s.parent_id, l.parent_id) AS parent_id,
COALESCE(1.0 / (60 + s.dense_rank), 0.0) +
COALESCE(1.0 / (60 + l.sparse_rank), 0.0) AS rrf_score
FROM semantic_hits s
FULL OUTER JOIN lexical_hits l ON s.parent_id = l.parent_id
)
SELECT p.id, p.doc_title, p.content, f.rrf_score
FROM fused f
JOIN rag_parent_chunks p ON p.id = f.parent_id
WHERE p.tenant_id = $1
ORDER BY f.rrf_score DESC
LIMIT 25;Pair that SQL query with a pytest CI quality gate so no prompt, chunking, or embedding model change ships blind:
# tests/test_rag_ci_gate.py - Automated RAG quality & latency regression gate
import pytest
from eval_harness import run_golden_eval_suite
FAITHFULNESS_FLOOR = 0.95
RELEVANCE_FLOOR = 0.90
RECALL_AT_5_FLOOR = 0.88
MAX_P95_LATENCY_MS = 1800
@pytest.mark.eval_gate
def test_rag_pipeline_meets_production_slo():
report = run_golden_eval_suite("evals/golden_compliance_v2.jsonl")
assert report.recall_at_5 >= RECALL_AT_5_FLOOR, (
f"Recall@5 regressed to {report.recall_at_5:.3f} (floor {RECALL_AT_5_FLOOR})"
)
assert report.faithfulness >= FAITHFULNESS_FLOOR, (
f"Faithfulness dropped to {report.faithfulness:.3f} (floor {FAITHFULNESS_FLOOR})"
)
assert report.answer_relevance >= RELEVANCE_FLOOR, (
f"Relevance dropped to {report.answer_relevance:.3f} (floor {RELEVANCE_FLOOR})"
)
assert report.p95_latency_ms <= MAX_P95_LATENCY_MS, (
f"p95 latency regressed to {report.p95_latency_ms}ms (cap {MAX_P95_LATENCY_MS}ms)"
)Log operational metrics (p95 end-to-end latency, tokens per query, cost per 1,000 queries) alongside MRR and Context Precision on every CI run so teams see quality and cost trade-offs in one PR comment.
Worked Production Scenario: Before vs. After
A multi-tenant fintech compliance platform serving 400 enterprise tenants ran an internal RAG assistant over Jira tickets, GitHub PR diffs, and SOC 2 runbooks.
- Before: The v1 pipeline used fixed 500-token chunks, cosine-only vector search in a shared namespace, and Python-side tenant post-filtering. Support teams reported that searching for exact Jira ticket keys or error codes failed 34% of the time. During a security review, engineers noticed noisy tenants crowded out smaller tenants from global top-20 vector results, causing false empty answers. Prompt tweaks frequently broke older use cases because there was no automated eval suite. Faithfulness sat at
0.79,Recall@5was0.64, and p95 latency hit2.9s. - After: The squad migrated to Postgres
pgvectorwith parent-child chunking (256-token child, 1,024-token parent), SQL-leveltenant_idandacl_rolespre-filtering, BM25 plus HNSW Reciprocal Rank Fusion, a cross-encoder reranker (top-25 to top-5), and an 80-questionpytestRAGAS gate in GitHub Actions. Within one month,Recall@5rose from0.64to0.93, Faithfulness climbed from0.79to0.97, cross-tenant retrieval leakage dropped to zero, and p95 latency settled at1.65s.
Common Failure Modes & Anti-Patterns
- Post-Filtering Vector Results in Application Code: Pulling top-20 nearest neighbors globally and discarding other tenants' rows in memory leaks cross-tenant document existence metadata and returns zero hits when one noisy tenant dominates the index. Structural Fix: Always apply
tenant_idandacl_rolesfilters inside the SQL or vector database query, and indextenant_idcleanly (or partition large tables by tenant tier). - Stale Embeddings After Document Edits or Permission Changes: Engineers build an ingestion script for initial backfill but forget incremental upserts, deletes, and ACL syncs. Revoked users keep seeing cached chunks from deleted policies. Structural Fix: Emit document change and ACL mutation events to an idempotent indexing worker that upserts by
source_doc_id+content_hashand deletes tombstoned chunks within minutes. - Evaluating Only the Generator While Ignoring Retrieval: Teams swap between three frontier LLMs trying to fix hallucinations when the real bug is that the right chunk never reached the prompt (
Recall@5 < 0.70). Structural Fix: Split CI dashboards into retrieval metrics (Recall@5,MRR,Context Precision) and generation metrics (Faithfulness,Answer Relevance), and fix retrieval first.
How to Handle Pushback in the Room
Pushback 1 (Skeptical Principal Engineer): "Why add BM25, RRF, and a cross-encoder reranker? Let's just use a new model with a 200k context window and stuff the documents into the prompt."
Verbatim Response: "Long-context models are great for analyzing one known contract, but stuffing 150k tokens per query blows up our latency and per-query cost across 400 tenants. It also hurts needle-in-a-haystack accuracy and complicates row-level ACL auditing. Hybrid search plus a reranker runs inside our existing Postgres stack in under 180 milliseconds and lets us prove exactly which five authorized chunks backed every answer."
Pushback 2 (Delivery-Focused PM): "Blocking pull requests on an 80-question LLM-as-a-judge suite adds six minutes to CI. Can we run evals weekly instead of on every PR?"
Verbatim Response: "Running evals weekly means we merge five prompt or chunking changes and then spend two days debugging which commit caused faithfulness to drop. We can keep fast unit tests on every commit and trigger the RAG eval gate strictly when PRs touch prompts/, retrieval/, or chunking/ paths, running cases in parallel so it completes in under 90 seconds."
Key Takeaways & This Week's Action Rep
- Retrieval quality and database-level permission enforcement matter far more than swapping foundation models in production RAG.
- Combine parent-child chunking (256-token child, 1,024-token parent), SQL
tenant_idandacl_rolespre-filtering, BM25 + vector RRF, and cross-encoder reranking to handle both semantic questions and exact IDs. - Force inline chunk citations and explicit abstention in your output schema so unsupported claims are caught deterministically.
- Never ship prompt, embedding, or chunking changes without a CI evaluation gate tracking
Recall@5,Faithfulness (> 0.95),Answer Relevance (> 0.90), and p95 latency.
This Week's Action Rep: Curate your first 25 real user questions with expected source chunk IDs into a JSONL file, run your current retrieval layer against them, and calculate baseline Recall@5. Fix every query that misses exact IDs before touching a single system prompt.