Forward Deployed EngineeringAI EngineeringHybrid Retrieval
Design a hybrid retrieval stack: BM25, vectors, and a reranker. What does each stage rescue?
Question 22 of 73 · Updated
On this page
- Interview-ready answer
- 1. What each stage rescues
- 2. End-to-end hybrid retrieval architecture
- 3. BM25: lexical retrieval
- What BM25 rescues
- 4. Dense retrieval: semantic matches
- What dense retrieval rescues
- 5. Reciprocal rank fusion
- Worked example
- 6. Cross-encoder reranking
- 7. Tested Python implementations
- BM25 baseline
- Reciprocal rank fusion
- 8. Candidate budgets and latency
- 9. Context selection after reranking
- 10. Practical failure-rescue example
- 11. Evaluate what each stage actually contributes
- 12. Authorization, freshness and scalability
- 13. Production failure modes and fallbacks
- FDE interview follow-ups
Interview-ready answer#
I would design hybrid retrieval as a two-stage search system: first maximize the recall of relevant authorized candidates using complementary lexical and dense retrievers, then maximize precision near the top of the ranking using a reranker.
BM25 rescues exact lexical evidence: product identifiers, error codes, names, rare domain terms and specific phrases when supported by the analyzer and query configuration. Dense vector retrieval rescues semantic matches that use different words, such as a customer asking "I cannot sign in" when the documentation says "Reset your password." A cross-encoder reranker rescues ranking errors by jointly examining the query and each candidate passage, which can help distinguish genuinely useful evidence from superficially related results.
I would run BM25 and vector retrieval in parallel, apply the same trusted authorization scope to both, merge their ranked lists using reciprocal rank fusion (RRF) as a simple baseline, and rerank a bounded candidate pool. Finally, I would deduplicate, preserve source metadata and select passages within the final context budget. A reranker cannot recover evidence that never entered its candidate pool, so I would measure candidate recall before tuning reranking.
In production, I would evaluate each stage independently and the complete customer workflow. I would compare BM25-only, dense-only, fused and reranked configurations on representative customer queries, measuring evidence recall, ranking quality, latency, cost and access-control correctness. I would use the simplest configuration that meets the customer's requirements.
1. What each stage rescues#
| Stage | Rescues | Typical limitation |
|---|---|---|
| BM25 | Exact terminology, rare terms, identifiers and lexical evidence | Vocabulary mismatch and paraphrases |
| Dense retrieval | Semantic similarity and vocabulary mismatch | Exact codes, negation and subtle domain distinctions |
| Rank fusion | Candidates missed or ranked poorly by one retrieval branch | Does not directly understand the query-passage relationship |
| Cross-encoder reranker | Relevant candidates buried beneath distractors | Cannot recover candidates omitted upstream |
| Context selection | Duplicate passages, missing surrounding context and inefficient token use | Incorrect selection or expansion can remove evidence or violate permissions |
The central design principle is recall first, precision second. A good reranker is valuable only if the initial retrieval stages find the necessary information.
2. End-to-end hybrid retrieval architecture#
Use a common passage ID across both indexes so a matching lexical and dense result can be fused. The source store preserves text, provenance, document version and access-control metadata. Index both retrieval branches from compatible corpus versions and reconcile edits and deletions.
At query time, the authorization layer derives scope from the authenticated identity, not from model-generated tenant or permission arguments. The search engines apply that scope, and the passage-fetching layer independently verifies authorization before sending content to a reranker or generator.
A reranker may itself run on an external service. Only send permitted, minimized data to that service, subject to the customer's data-processing requirements.
3. BM25: lexical retrieval#
BM25 is a widely used ranking function built around term frequency, inverse document frequency and document-length normalization. A common BM25 variant scores a document D for a query Q using:
BM25(D, Q) = sum over unique query terms t of IDF(t) × f(t, D)(k1 + 1) / [f(t, D) + k1(1 − b + b × |D| / avgdl)]
Here:
- f(t, D) is the term frequency in the document.
- |D| is the document length measured in the analyzer's tokens.
- avgdl is average document length in the indexed corpus or relevant collection statistics.
- k1 controls term-frequency saturation.
- b controls length normalization.
A commonly used nonnegative IDF variant is:
IDF(t) = ln(1 + (N − df(t) + 0.5) / (df(t) + 0.5))
N is the document count and df(t) counts documents containing the term.
A rare error code receives more weight than a word appearing in nearly every document. Repeating a term increases its contribution but with diminishing returns. Length normalization can reduce the advantage that longer passages have simply because they contain more words.
What BM25 rescues#
Consider a query asking about an error code AUTH-1042. A dense model may retrieve several related authentication errors without distinguishing the exact code. A well-configured lexical index can prioritize the specific identifier.
BM25 alone does not guarantee exact phrase matching: analyzer choices, token boundaries, case handling and the query operator matter. Preserve important identifiers with suitable keyword fields, exact-match filters or phrase queries when required. Do not let a tokenizer split away distinctions the business depends on.
4. Dense retrieval: semantic matches#
A dense retrieval model encodes queries and passages into compatible vector representations. A similarity function such as cosine similarity or dot product scores their relationship. An exact or approximate nearest-neighbor index retrieves the highest-scoring authorized vectors.
What dense retrieval rescues#
Suppose the customer asks "Why does the app keep kicking me out?" while the correct article is titled "Troubleshoot unexpected session termination." These inputs may share few meaningful tokens. A suitable embedding model can place them close enough to retrieve the article.
Dense retrieval still has limitations. It may confuse "enable two-factor authentication" with "disable two-factor authentication," or retrieve the policy for a similarly named product. Embedding input truncation, domain mismatch, chunk boundaries and an incorrectly configured distance metric can further degrade results.
Evaluate the embedding model on actual customer tasks. When using ANN, distinguish the approximate index's recall against exact vector search from semantic recall against human-labeled evidence. Excellent ANN recall is not proof of semantic relevance.
5. Reciprocal rank fusion#
BM25 and dense retrieval produce scores on different scales. A raw BM25 score of 15 and a cosine similarity of 0.83 are not inherently comparable. Reciprocal rank fusion combines the positions of documents in each ranked list instead of directly adding their raw scores.
For document d and retrieval lists L:
RRF(d) = sum over lists containing d of 1 / (c + rank_L(d))
Ranks begin at one. The constant c is positive; 60 is a common illustrative starting point, not an optimal value for every workload. A document absent from a list contributes zero for that list. Higher c generally reduces the relative advantage of very high rank positions.
Worked example#
Assume the BM25 branch returns [A, C, B] and the dense branch returns [B, D, A]. With c = 60:
| Document | BM25 rank | Dense rank | RRF score |
|---|---|---|---|
| A | 1 | 3 | 0.032266 |
| B | 3 | 1 | 0.032266 |
| C | 2 | absent | 0.016129 |
| D | absent | 2 | 0.016129 |
A and B tie because their rank contributions are symmetric. C and D remain in the fused pool even though only one branch found each. Use an explicit tie-break rule for reproducibility.
RRF rewards agreement between retrievers, but agreement is not evidence of correctness. A document found by only one branch may be the only correct result. Tune the per-branch candidate counts, fusion settings and fused cutoff on customer data. For exact identifiers, a dedicated exact-match constraint or protected candidate slot may be more reliable than hoping the fused score is high enough.
Weighted RRF is another option when one branch is empirically stronger for a particular intent. Calibrated score fusion can also work, but requires reliable score normalization and more tuning. Start with a simple baseline.
6. Cross-encoder reranking#
In a typical dense bi-encoder, query and document representations are computed independently. This independence enables precomputed document vectors and scalable search. A cross-encoder processes the query and a candidate passage together and predicts a relevance score. Joint attention can model interactions between specific query terms, negation, conditions and passage details.
| Dimension | Dense bi-encoder | Cross-encoder reranker |
|---|---|---|
| Inputs | Independently encoded query and passage | Joint query-passage input |
| Main role | Large-scale candidate retrieval | Fine-grained relevance ranking |
| Document work | Precompute embeddings | Score each candidate for the current query |
| Cost | Efficient index search after encoding | Additional computation per candidate |
For example, a query asks whether contractors can return company equipment after an assignment ends. A semantic retriever may find both employee equipment-return rules and contractor-specific exceptions. A trained reranker may recognize that the contractor passage is more applicable to the query.
A cross-encoder is not a policy engine, a fact verifier or an authorization system. It can still misrank passages, especially when key details are truncated or outside its training distribution. If a required passage is absent from the reranker's input, no ranking algorithm can restore it without additional retrieval.
7. Tested Python implementations#
The following dependency-free examples demonstrate lexical ranking and rank fusion. They operate on already-tokenized documents and ranked document IDs. They are educational reference implementations, not production search engines.
BM25 baseline#
PYTHONfrom collections import Counter, defaultdict import math def bm25(query, docs, k1=1.2, b=0.75): if not math.isfinite(k1) or k1 <= 0 or not 0 <= b <= 1: raise ValueError('Invalid BM25 parameters') if not docs: return [] n = len(docs) avgdl = sum(map(len, docs.values())) / n if avgdl == 0: return [] counts = {i: Counter(tokens) for i, tokens in docs.items()} terms = set(query) df = {t: sum(t in c for c in counts.values()) for t in terms} scores = [] for i, c in counts.items(): norm = k1 * (1-b+b*len(docs[i])/avgdl) score = math.fsum( math.log1p((n-df[t]+0.5)/(df[t]+0.5)) * c[t]*(k1+1)/(c[t]+norm) for t in terms if c[t] ) if score > 0: scores.append((i, score)) return sorted(scores, key=lambda x: (-x[1], x[0]))
Here docs maps comparable unique string IDs to lists of tokens. Repeated query terms are deliberately deduplicated, and zero-score results are omitted. The corpus is assumed to have been supplied within an appropriate authorized processing boundary. This example recomputes corpus statistics per call; a production engine uses an inverted index and maintained statistics rather than scanning every document for every query.
With N documents, T total document tokens and m unique query terms, the baseline requires O(T + Nm + N log N) time including sorting and O(T + N + m) auxiliary space in the worst case.
Reciprocal rank fusion#
PYTHONdef rrf(rankings, c=60): if not math.isfinite(c) or c <= 0: raise ValueError('c must be positive and finite') scores = defaultdict(float) for ranked in rankings: if len(set(ranked)) != len(ranked): raise ValueError('Duplicate ID in ranked list') for pos, doc_id in enumerate(ranked, 1): scores[doc_id] += 1/(c+pos) return sorted(scores.items(), key=lambda x: (-x[1], x[0])) print(rrf([['A','C','B'], ['B','D','A']])) # A and B: 0.032266...; C and D: 0.016129...
Each ranked list contains unique string IDs ordered best-first. A repeated ID across different lists is expected and contributes to fusion; a duplicate inside one list is rejected. If the total number of rank entries is R and the number of unique IDs is U, the algorithm takes O(R + U log U) time and O(U) score storage, plus temporary per-list duplicate-check storage bounded by U.
Local verification: Both implementations were executed using Python 3.13.5. All 1,926 checks passed: 1,152 BM25 corpus/query/parameter combinations compared against an independently expressed scoring formula; 768 RRF combinations of ranked lists and rank constants compared against exact rational reference scores; four invalid-parameter or duplicate-ID cases; and two empty-input cases. The worked RRF example also produced the expected ranking. These tests validate the mathematical implementations, not real-world retrieval relevance, production authorization or cross-encoder quality.
8. Candidate budgets and latency#
A reasonable experimental configuration might retrieve up to 50 BM25 candidates and 50 dense candidates, fuse and deduplicate the union, rerank the best 30–50 eligible passages, and select a small number of evidence-rich passages for generation. These values are starting points for benchmarking, not universal defaults.
Run lexical retrieval and query encoding plus vector retrieval in parallel when they have no dependencies on one another. An approximate latency model is:
This assumes the two branches actually overlap. Shared queues, rate limits, resource contention and network behavior can change observed latency. Do not calculate end-to-end p95 by simply adding stage p95 values; measure it directly.
Cross-encoder computation grows with the number and length of candidate pairs. Batch candidate scoring when supported, bound text length, and avoid reranking duplicate passages. Evaluate an adaptive policy that bypasses reranking for certain trusted exact-match cases or uses a smaller candidate budget for easy queries, provided the quality gates still pass.
9. Context selection after reranking#
The top-ranked passage is not always enough. A question may require both a general rule and an exception from a second passage. Select evidence with coverage, diversity and token limits in mind.
- Deduplicate equivalent or highly overlapping chunks while preserving genuinely distinct evidence.
- Preserve source IDs, effective dates, section references and citation offsets.
- Expand child chunks to authorized parent context only when needed; independently check permissions.
- Reconcile conflicting versions using the appropriate source-of-truth policy, not reranker score alone.
- Reserve output capacity and check the final serialized prompt for truncation.
- Abstain or request clarification when sufficient applicable evidence is missing.
This final stage matters because a relevant candidate retrieved upstream but removed during context packing is effectively unavailable to the generator.
10. Practical failure-rescue example#
Imagine an enterprise software support knowledge base with these fictional articles:
| ID | Article |
|---|---|
| A | AUTH-1042: expired API credentials |
| B | Troubleshoot unexpected session termination |
| C | AUTH-1043: invalid account permissions |
| D | Rotating credentials for service accounts |
For the query "Our integration gets AUTH-1042 after we changed the service token," lexical retrieval helps find the exact error article A. Dense retrieval may find D because it captures the concept of changing credentials. A reranker can compare the exact error code, account type and event context and prioritize the applicable troubleshooting instructions.
For "The app keeps logging me out," dense retrieval may rescue B even when the phrasing differs. BM25 can still contribute exact product or feature terms if supplied. A reranker can demote C and D if the question concerns an interactive session rather than API authentication.
These are illustrative expected behaviors, not actual benchmark results. An exact error code may require structured filtering, and a correct answer may need evidence from more than one article.
11. Evaluate what each stage actually contributes#
Construct a versioned relevance dataset with representative customer queries, required evidence spans, permission scope and expected answerability. Include exact identifiers, paraphrases, rare terminology, multilingual queries, negation, conflicting policies and multi-evidence questions.
| Experiment | Diagnostic question |
|---|---|
| BM25 only | How well do lexical signals cover the workload? |
| Dense only | How much semantic coverage does the model provide? |
| Candidate union | Which relevant evidence is found uniquely by each branch? |
| Fused ranking | Does fusion preserve relevant candidates before reranking? |
| Fused plus reranked | Does joint scoring improve the top-ranked evidence? |
| Final context | Does the required evidence survive deduplication and token packing? |
| End-to-end RAG | Does the answer use the evidence correctly and safely? |
Measure candidate Recall@k, all-evidence success, MRR and nDCG at appropriate cutoffs. Use the same source evidence units and permission scope when comparing branches. Compare matched candidate budgets and matched final context budgets; otherwise a system returning twice as many candidates may appear better simply because it searched more.
Useful marginal metrics include the number of relevant evidence units uniquely retrieved by BM25, uniquely retrieved by dense search, and lost at fusion or reranking cutoffs. Track reranking lift in nDCG or MRR and the additional latency and cost.
Measure the pipeline's upper bound with a gold-candidate or gold-context experiment. If correct evidence is absent before reranking, improve upstream retrieval or indexing. If it is present but low-ranked, inspect fusion and reranking. If it reaches the generator but the answer is incorrect, inspect generation and validation.
For ANN, also compare the approximate nearest-neighbor results with exact retrieval under the same vector metric and authorization filters. For no-answer cases, measure appropriate abstention rather than assigning arbitrary perfect recall to an empty gold set.
12. Authorization, freshness and scalability#
Apply tenant and document-level permission constraints to both retrievers and independently verify the passage before reranking, context construction and final response. An unauthorized record must not become visible through lexical snippets, vector results, rank fusion, parent expansion, cache hits or diagnostic logs.
Use shared stable IDs and compatible metadata schemas across lexical and dense indexes. Version the index configuration, analyzer, chunker, embedding model and reranker. Make ingestion idempotent, track synchronization lag and delete or revoke stale entries. Treat the source-of-truth access policy as authoritative even when an index is behind.
For large collections, select an appropriate inverted-index and ANN implementation based on latency, recall, filter selectivity, index size, update behavior and operational expertise. Highly selective filters may require partitioning, filtered ANN strategies or exact search over a small authorized subset. Test the actual filtered workload; performance on unrestricted benchmarks may not generalize.
A cache must include relevant identity/scope, query, model and corpus version information or otherwise be proven safe to share. Recheck permissions when serving cached evidence, and handle revocation and deletion according to the customer's requirements.
13. Production failure modes and fallbacks#
| Failure | Diagnosis and response |
|---|---|
| Exact identifier absent | Inspect analyzer, keyword fields, filters and index coverage |
| Paraphrase missed | Evaluate embeddings, domain fit and chunking |
| Correct document in a branch but absent after fusion | Increase or adapt the candidate budget; inspect ranking and deduplication |
| Correct candidate demoted by reranker | Inspect truncation, domain mismatch and relevance labels |
| Duplicate versions dominate context | Reconcile versions and deduplicate using source metadata |
| Dense service unavailable | Consider an approved lexical-only fallback if quality and authorization requirements permit |
| Reranker timeout | Consider an approved fused-ranking fallback with explicit monitoring |
| Unauthorized result | Fail closed, investigate the access boundary and block unsafe rollout |
| Both branches lack evidence | Clarify, abstain or escalate instead of inventing an answer |
Degraded retrieval modes must be explicitly evaluated and approved. A fallback must never bypass permissions or present unverified evidence as authoritative.
Monitor p50/p95/p99 stage and end-to-end latency, candidate counts, branch overlap, empty retrievals, fallback frequency, source freshness, error rates, reranker throughput and cost per successful task. Investigate regressions with representative query slices rather than relying only on aggregate metrics.
FDE interview follow-ups#
Why not just use a vector database? Dense retrieval can miss exact lexical details. A hybrid stack captures complementary signals, and a vector database is infrastructure rather than a guarantee of relevance.
Why not rerank the entire corpus? Joint query-passage scoring is usually too expensive at scale. Retrieve a bounded candidate set first, then spend computation where it is most useful.
Why use RRF instead of adding scores? Rank fusion avoids assuming unrelated score scales are comparable. Score fusion can work if calibrated and evaluated.
What if BM25 and dense retrieval already perform well? Measure the reranker's incremental quality improvement against its latency and cost. Do not add a stage solely because it is fashionable.
How do you know whether hybrid retrieval is better? Use paired evaluation on the same labeled customer queries and authorization scope. Measure unique evidence rescued by each branch, final ranking quality and the customer task outcome.
What is the biggest mistake? Optimizing the reranker while missing relevant evidence upstream, or treating similarity and relevance scores as proof of authorization or factual correctness.
References
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models