Hybrid Retrieval Before Bigger Models: Practical RAG with RRF and Reranking
A production-oriented way to improve RAG retrieval with lexical search, vector search, reciprocal rank fusion, reranking, and retrieval-specific evaluation before changing the generation model.
On this page
A RAG answer can be perfectly written and still be wrong for a boring reason: the useful evidence never reached the model.
That is the first place I look when a knowledge assistant starts missing questions it should be able to answer. Swapping the LLM is tempting because generation is the visible part of the system. Retrieval is less visible, but it determines what facts the model is allowed to work with.
A useful mental model is to treat RAG as two systems joined together:
- an information-retrieval system that has to find strong evidence;
- a generation system that has to use that evidence correctly.
If the first one fails, the second one cannot rescue it reliably.
This article focuses only on the retrieval half. The example is an internal engineering knowledge assistant indexing API documentation, incident notes, architecture decisions, and runbooks. The design combines lexical search and vector search, fuses their rankings, then reranks a small candidate set before anything enters the prompt.
Why vector search alone eventually disappoints
Embeddings are very good at matching meaning. They are less reliable for tokens whose exact spelling carries the meaning.
Suppose an engineer asks:
Why does checkout return PAYMENT_409 after a retry?A semantic query can retrieve material about payment conflicts, duplicate requests, or retry behavior. That is useful. But the exact error code may exist in one runbook and nowhere else. Traditional text search has an advantage there.
The reverse also happens. A user may ask, “why does the order job run twice?” while the document says “duplicate background delivery.” Lexical overlap is weak, while semantic retrieval can connect the two.
I do not want to decide which search method wins globally. I want both to produce candidates and let a later stage decide which evidence is strongest for this query.
That is the reason for hybrid retrieval.
Keep retrieval results as evidence, not strings
Before combining rankings, I give each candidate enough identity to debug later.
type SearchHit = { chunkId: string; documentId: string; tenantId: string; source: string; text: string; score: number;};A real system usually carries more metadata: document version, access-control labels, section heading, timestamps, and perhaps a content hash. I keep those fields outside the model prompt unless they are useful to the answer, but they should exist in the retrieval layer.
Without stable chunk and document IDs, it is difficult to answer basic production questions later: which document was retrieved, whether it was stale, how often it appears, or whether a ranking change improved anything.
Run lexical and semantic search concurrently
The two searches are independent, so there is little reason to serialize them.
interface Retriever { lexical(query: string, tenantId: string, limit: number): Promise<SearchHit[]>; semantic(query: string, tenantId: string, limit: number): Promise<SearchHit[]>;}async function retrieveCandidates( retriever: Retriever, query: string, tenantId: string,): Promise<{ lexical: SearchHit[]; semantic: SearchHit[] }> { const [lexical, semantic] = await Promise.all([ retriever.lexical(query, tenantId, 30), retriever.semantic(query, tenantId, 30), ]); return { lexical, semantic };}The tenant filter belongs inside both searches. Filtering after retrieval is too late for a multi-tenant product because unauthorized candidates may already have crossed a boundary they should never cross.
Fuse rankings instead of comparing unrelated scores
A lexical engine and an embedding index do not produce scores on the same scale. A text-search rank of 0.72 and a cosine similarity of 0.72 do not mean equivalent relevance.
That makes naive score averaging brittle.
A practical alternative is reciprocal rank fusion (RRF). It ignores the raw score and rewards documents that appear near the top of either ranked list.
For a document at rank r, its contribution is:
1 / (k + r)
k is a smoothing constant. It prevents the first result from completely dominating the list. The exact value is something to tune against your evaluation set rather than treat as a universal constant.
function reciprocalRankFusion( rankedLists: SearchHit[][], k = 60,): SearchHit[] { const byChunk = new Map<string, { hit: SearchHit; fusedScore: number }>(); for (const list of rankedLists) { list.forEach((hit, index) => { const rank = index + 1; const current = byChunk.get(hit.chunkId); const contribution = 1 / (k + rank); if (current) { current.fusedScore += contribution; } else { byChunk.set(hit.chunkId, { hit, fusedScore: contribution, }); } }); } return [...byChunk.values()] .sort((a, b) => b.fusedScore - a.fusedScore) .map(({ hit, fusedScore }) => ({ ...hit, score: fusedScore }));}RRF is useful because it combines *ordering*, which each retriever knows, without pretending their scoring functions are directly comparable.
It is not magic. If both underlying retrievers are poor, fusing them creates a more confidently organized bad list.
Retrieval wants recall; the prompt wants precision
The first stage should be generous. I would rather retrieve twenty plausible chunks than accidentally exclude the one chunk that answers the question.
The prompt has the opposite requirement. Filling it with twenty weak passages increases token cost and can make generation less focused.
That is where reranking earns its place.
The pipeline becomes:
- lexical search for high-recall exact matches;
- semantic search for high-recall meaning matches;
- RRF to merge and deduplicate;
- rerank perhaps the top 20 candidates against the original query;
- send only the strongest few chunks to the model.
I like to keep the reranker behind a small interface so the rest of the retrieval system does not depend on one vendor or model.
type RankedChunk = SearchHit & { rerankScore: number };interface Reranker { rerank(query: string, hits: SearchHit[]): Promise<RankedChunk[]>;}async function retrieveForPrompt( retriever: Retriever, reranker: Reranker, query: string, tenantId: string,): Promise<RankedChunk[]> { const { lexical, semantic } = await retrieveCandidates( retriever, query, tenantId, ); const fused = reciprocalRankFusion([lexical, semantic]).slice(0, 20); const reranked = await reranker.rerank(query, fused); return reranked.slice(0, 6);}The important design choice is not whether the final number is six. It is that candidate generation and final context selection are separate jobs with different objectives.
Measure retrieval without involving the LLM
If I change chunking, embedding models, ranking weights, or filters, I want to know whether retrieval improved before I look at answer quality.
A small retrieval dataset can be enough to start:
type RetrievalCase = { query: string; relevantChunkIds: string[];};function recallAtK( retrieved: SearchHit[], relevantChunkIds: string[], k: number,): number { const expected = new Set(relevantChunkIds); const found = new Set( retrieved.slice(0, k).map((hit) => hit.chunkId), ); let matches = 0; for (const id of expected) { if (found.has(id)) matches += 1; } return expected.size === 0 ? 1 : matches / expected.size;}For a single-answer support corpus, hit rate at K may be enough. For broader research questions, recall at K, MRR, or nDCG can be more informative.
The metric is less important than the separation. If retrieval recall drops after an indexing change, I should not need to discover it by reading generated answers manually.
Failure modes I would watch in production
Hybrid retrieval adds moving parts, so it creates its own ways to fail.
Duplicate evidence. Two chunks from the same section may occupy half the final prompt. Deduplicate by content hash or apply diversity rules at document/section level.
Old documents winning exact search. A stale runbook can rank perfectly for an error code. Freshness belongs in metadata and can become a filter or a ranking feature.
Permission filtering after fusion. Do not do this. Authorization needs to be enforced inside every retrieval source before candidates are returned.
Reranker latency. Reranking 100 candidates is different from reranking 20. Put a latency budget around the stage and measure whether the quality gain justifies it.
One retriever silently failing. If lexical search starts returning zero results because an index is broken, the vector side can hide the outage. Trace both candidate counts separately.
Tuning on pretty demo questions. Real retrieval tests should contain abbreviations, identifiers, vague wording, misspellings, and questions whose evidence spans multiple chunks.
When hybrid retrieval is unnecessary
I would not build this pipeline by default for a tiny, clean corpus.
If you have fifty short documents, semantic search already retrieves the right chunk almost every time, and latency matters more than squeezing out another point of recall, adding full-text search plus a reranker may just create operational work.
Start with the simplest retriever you can measure. Add another retrieval channel when the failures show a reason for it.
The key is to diagnose retrieval as retrieval. If exact identifiers are being missed, lexical search is a targeted fix. If candidate ordering is noisy, reranking is a targeted fix. If the right chunk is not indexed at all, neither helps.
A larger language model should be much further down the debugging list.
For production RAG, I want the generator to receive a small set of evidence I can explain, reproduce, and evaluate. Hybrid search and reranking are useful because they turn that goal into an explicit retrieval pipeline rather than another instruction hidden inside a prompt.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article