All blogs
AI SystemsDec 2, 20268 min read

Production RAG & Vector Databases: Hybrid Search, Chunking, and Evaluation Beyond Demos

Why naive vector similarity fails on real enterprise queries, and how combining pgvector with BM25 hybrid search, Reciprocal Rank Fusion, and strict access-control filtering builds trustworthy retrieval.

RAG ArchitectureVector DatabasesHybrid Search
Isometric dark-mode illustration of translucent document shards in semantic vector clusters illuminated by acid-lime and amber hybrid search beams

Retrieval-Augmented Generation (RAG) is the fastest way to ground an LLM in private product data, documentation, or meeting history. Yet most teams hit a sharp wall between a working weekend prototype and a production system users actually trust. When users ask about a specific error code like `ERR_WEBHOOK_409`, a customer SKU, or a clause from last week's contract, naive cosine similarity frequently returns semantically adjacent fluff instead of the exact passage.

Reliable RAG is primarily a search engineering and data-modeling problem. Fixing it requires upgrading three layers: how documents are chunked, how dense and sparse signals are fused, and how retrieval quality is measured continuously.

1. Why Naive Vector-Only Chunking Fails

Fixed 500-token character splits tear markdown tables in half, separate headings from their body paragraphs, and strip out document-level metadata like author, date, or product version. Without structure-aware chunking, the embedding represents a fragment with no context.

  • Structure-aware boundaries: Split by semantic structure first (markdown headings, HTML sections, function definitions, or transcript speaker turns) before enforcing max-token bounds.
  • Parent-child context expansion: Embed compact child chunks for crisp search matching, but inject the surrounding parent section into the LLM prompt so reasoning has complete context.
  • Pre-filter tenant ACLs: Always index `workspace_id` and permission tags alongside the embedding so unauthorized documents are excluded before HNSW or IVFFlat candidate scoring.
Production Hybrid RAG flow showing parallel Vector Search and BM25 Keyword Search merged through Reciprocal Rank Fusion and Cross-Encoder Reranking
Hybrid RAG combines pgvector semantic recall with BM25 lexical precision, fused via Reciprocal Rank Fusion and refined with a reranker.

2. Hybrid Search: Combining pgvector and BM25 with Reciprocal Rank Fusion

Dense embeddings excel at paraphrased intent ('how do I cancel my plan?'), while sparse lexical search (BM25 / PostgreSQL full-text search) excels at exact tokens ('Stripe invoice_payment_failed' or 'v2.4 migration'). Running both in parallel and merging their rankings with Reciprocal Rank Fusion (RRF) gives you the strengths of both without having to calibrate incompatible similarity score scales.

hybrid-rrf-search.sqlsql
WITH semantic AS (
  SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1) AS rank
  FROM document_chunks
  WHERE workspace_id = $2
  ORDER BY embedding <=> $1
  LIMIT 40
),
keyword AS (
  SELECT id, ROW_NUMBER() OVER (
    ORDER BY ts_rank_cd(search_tsv, websearch_to_tsquery('english', $3)) DESC
  ) AS rank
  FROM document_chunks
  WHERE workspace_id = $2
    AND search_tsv @@ websearch_to_tsquery('english', $3)
  ORDER BY rank
  LIMIT 40
)
SELECT
  c.id,
  c.content,
  c.source_url,
  COALESCE(1.0 / (60 + s.rank), 0) + COALESCE(1.0 / (60 + k.rank), 0) AS rrf_score
FROM document_chunks c
LEFT JOIN semantic s ON s.id = c.id
LEFT JOIN keyword k ON k.id = c.id
WHERE s.id IS NOT NULL OR k.id IS NOT NULL
ORDER BY rrf_score DESC
LIMIT 20;

Notice how keeping both signals inside PostgreSQL (`pgvector` + `tsvector`) eliminates dual-write sync bugs for many SaaS workloads. Once your corpus reaches tens of millions of vectors or needs dedicated sharding, the exact same RRF pattern transfers cleanly to dedicated engines like Qdrant, Milvus, or Elasticsearch.

3. Cross-Encoder Reranking and Automated Retrieval Evals

Bi-encoder embeddings compress an entire chunk into a single vector, which loses fine-grained word-to-word interaction. Passing the top 20 RRF candidates through a fast cross-encoder reranker scores the query and each candidate passage jointly, pushing the true top 5 chunks to the front of the prompt and dramatically reducing hallucinations.

Key takeaways
  • Never rely on dense vector similarity alone: pair vector search with BM25 lexical search using Reciprocal Rank Fusion (RRF) so exact IDs, SKUs, and error codes rank accurately.
  • Apply tenant, workspace, and document ACL filters inside the database query—never as a post-retrieval JavaScript filter after Top-K truncation.
  • Measure retrieval recall and citation faithfulness in CI with a golden evaluation set before tweaking prompts or swapping foundation models.
Keep reading

More engineering notes

View all