Katkat

Hybrid Search and Reranking

By the Katkat team · Updated · 9 min read

Quick overview

Learn how hybrid search combines BM25 and vector retrieval, how reciprocal rank fusion merges rankings, and what cross-encoder rerankers cost in latency.

Lesson 20 of 88 · AI Engineering Interview Course

After this lesson you should be able to explain why production RAG systems often combine keyword search (BM25) with vector search, and how reciprocal rank fusion merges the two result lists without comparing incompatible scores. You should also be able to describe how a cross-encoder reranker improves precision, and estimate what it costs in compute and latency. These are common follow-ups when an interviewer asks "how would you improve retrieval quality?"

Why one retriever is not enough

Vector search and keyword search fail in opposite ways.

  • Dense (vector) retrieval matches meaning. "How do I cancel my plan?" can find a page titled "Ending your subscription". It is weak on exact strings: product codes, error numbers like ERR_4012, function names, rare surnames. An embedding model may never have seen these tokens often enough to place them well. See Embeddings: Representing Text as Vectors.
  • Lexical retrieval (BM25) matches words. It is excellent for exact identifiers and rare terms. It is blind to paraphrase: a query saying "car" will not find a document that only says "automobile".

Real queries mix both kinds of need, and you rarely know in advance which kind a query is. Hybrid search runs both retrievers and merges the results. A reranker then re-scores the merged candidates with a more accurate (and more expensive) model. This gives a two-stage design: a cheap first stage that is good at recall, and an expensive second stage that is good at precision.

BM25 in one section

BM25 scores a document against a query by summing a contribution per query term. For a term t in document d:

contribution = IDF(t) × tf × (k1 + 1) / (tf + k1 × (1 − b + b × |d| / avgdl))

The pieces:

  • IDF (inverse document frequency): rare terms count more. A common form is ln(1 + (N − n + 0.5) / (n + 0.5)), where N is the number of documents and n is how many contain the term. "the" has near-zero weight; ERR_4012 has a high one.
  • tf (term frequency): more occurrences raise the score, but with saturation controlled by k1 (often set somewhere around 1.2 to 2). The tenth occurrence adds much less than the second.
  • Length normalisation: b (commonly 0.75) penalises long documents, relative to the average length avgdl, so a long page is not favoured just for containing more words.

BM25 uses an inverted index, so it is fast and needs no GPU. Its scores are unbounded and depend on the corpus and query length. A score of 14.2 means little on its own. This matters in the next section.

Fusing two rankings

You now have two ranked lists, one from BM25 and one from vector search. The score scales are unrelated: BM25 might produce 12.4, cosine similarity might produce 0.82. There are two common ways to merge them.

ApproachHow it worksStrengthsWeaknesses
Weighted score sumNormalise each score (e.g. min-max), then α × dense + (1 − α) × bm25Uses score magnitudes; one tunable knobNormalisation is fragile; a single outlier distorts min-max; α needs labelled data
Reciprocal rank fusion (RRF)Ignore scores; sum 1 / (k + rank) across listsNo normalisation; robust; works with any number of retrieversThrows away score gaps (a near-tie and a landslide look the same)

RRF is a popular default because it needs almost no tuning. For each document, add up 1 / (k + rank) over every list it appears in, where rank starts at 1. The constant k is commonly 60. A larger k flattens the difference between rank 1 and rank 10; a smaller k rewards top positions more.

Worked example

Take k = 60 and four documents:

DocBM25 rankVector rankRRF score
A131/61 + 1/63 = 0.01639 + 0.01587 = 0.03227
B211/62 + 1/61 = 0.01613 + 0.01639 = 0.03252
C5not returned1/65 = 0.01538
Dnot returned21/62 = 0.01613

Final order: B, A, D, C. B wins even though A was BM25's top hit, because B scored well in both lists. D (vector only) edges out C (BM25 only, ranked fifth). A document missing from a list simply contributes nothing for that list.

Cross-encoder rerankers

The first stage typically uses a bi-encoder: query and document are embedded separately, and similarity is a dot product or cosine. Document vectors are precomputed, so searching millions of items is cheap. The cost is that the model never sees the query and document together, so it cannot model fine-grained interaction.

A cross-encoder feeds the query and one candidate document into the transformer as a single input and outputs a relevance score. Every query token can attend to every document token. This is usually noticeably more accurate at ordering a small candidate set. See The Transformer, Explained for Engineers for the attention mechanism that makes this possible.

PropertyBi-encoderCross-encoder
InputQuery or document aloneQuery and document together
Precompute document side?YesNo, each pair needs a forward pass
Cost per queryOne query embedding plus an index lookupOne forward pass per candidate
Scales to millions of docs?Yes (with ANN indexes)No, only to tens or hundreds of candidates
Typical roleRetrievalReranking

Because a cross-encoder cannot be precomputed, it only works as a second stage. The first stage narrows the corpus to, say, 50 candidates; the cross-encoder reorders those; you keep the top 5 for the prompt. Many cross-encoders have a limited maximum input length, so chunks that are too long get truncated. This ties reranking to your chunking choices.

The cost of reranking

Rerankers add latency and compute to every query. A back-of-the-envelope estimate shows how much.

Setup (assumptions for illustration): a cross-encoder with about 110 million parameters, 50 candidates, each chunk about 300 tokens plus a 20-token query, so about 320 tokens per pair.

  • Tokens processed: 50 × 320 = 16,000.
  • Forward-pass FLOPs are roughly 2 × parameters × tokens = 2 × 110,000,000 × 16,000 ≈ 3.5 × 10¹² (3.5 TFLOPs).
  • If the GPU sustains about 20 TFLOP/s on this workload (a fraction of peak; real figures depend on hardware, batching and precision), that is 3.5 / 20 ≈ 0.18 s, so roughly 180 ms.

The cost scales linearly with the number of candidates: 100 candidates is about twice the latency, 25 about half. Candidate count is your main knob.

Why you cannot rerank everything: scoring a 1,000,000-chunk corpus this way means 1,000,000 × 320 = 3.2 × 10⁸ tokens, or about 7 × 10¹⁶ FLOPs. At 20 TFLOP/s that is around 3,500 seconds, close to an hour per query. This is exactly why the cheap first stage exists.

The offsetting saving: reranking lets you send fewer chunks to the LLM. Passing the top 5 instead of the top 20 chunks of 300 tokens cuts input from 6,000 to 1,500 tokens, saving 4,500 input tokens per request. Depending on your generation model's price and speed, the reranker can partly or fully pay for itself, and shorter prompts also help time to first token. Measure it rather than assuming.

Other cost considerations:

  • Hosted reranking APIs charge per request or per document scored; pricing varies by vendor, so check the current rate card.
  • Self-hosting needs a GPU (or a small model on CPU if latency budgets allow) and batching.
  • Run BM25 and vector search in parallel, so first-stage latency is the slower of the two, not the sum.

Putting the pipeline together

A typical flow:

  1. Take the user query (optionally rewritten).
  2. In parallel, fetch the top 50 from BM25 and the top 50 from an ANN index (Vector Search: HNSW, IVF and Approximate Nearest Neighbours), applying the same metadata filters to both.
  3. Deduplicate by chunk ID and fuse with RRF. This gives up to 100 unique candidates.
  4. Optionally truncate to the top 30 to 50 fused candidates to bound reranker cost.
  5. Rerank with a cross-encoder and keep the top 5.
  6. Build the prompt and generate. The whole system is covered in Retrieval-Augmented Generation, End to End.

Trade-offs to be ready to discuss:

  • Complexity: you now run and monitor two indexes and a model. If the corpus is small or the queries are purely conceptual, plain vector search may be enough.
  • Recall versus precision: fusion and larger candidate pools raise recall; the reranker raises precision. A reranker cannot recover a document the first stage never returned.
  • Thresholding: reranker scores can help decide when to say "I don't know" if nothing is relevant, but scores are not always comparable across queries, so tune any cutoff on labelled data.
  • Domain fit: an off-the-shelf reranker may underperform on specialised text (legal, code, medical). Test it, and consider fine-tuning if the gap is large.
  • Evaluation: measure first-stage recall@k separately from post-rerank metrics such as MRR or nDCG, so you know which stage is the bottleneck. See Evaluating a RAG System.

How does this come up in interviews?

1. Why would you add BM25 to a system that already uses embeddings? Embeddings capture meaning but can miss exact tokens such as IDs, error codes and rare names, while BM25 handles those well and is cheap. Their failure modes are complementary, so merging them improves recall across mixed query types. I would confirm it on a labelled query set by comparing recall@k for dense only, BM25 only and hybrid.

2. BM25 scores and cosine similarities are on different scales. How do you combine them? Either normalise and take a weighted sum, which needs a tuned weight and careful normalisation, or use reciprocal rank fusion, which uses only ranks: sum 1/(k+rank) per list with k around 60. RRF is robust and nearly tuning-free, but it discards score margins. I would start with RRF and move to weighted fusion only if evaluation shows a clear gain.

3. Why not just use a cross-encoder for all retrieval? A cross-encoder needs a full forward pass per query-document pair, so nothing can be precomputed. Over a million chunks that is hours of compute per query, whereas a bi-encoder plus ANN index answers in milliseconds. So the cross-encoder runs only over a short candidate list from the first stage.

4. Your reranker adds 200 ms. How do you decide whether it is worth it? Measure answer quality with and without it on an evaluation set, and measure end-to-end latency and cost. Account for savings from sending fewer chunks to the LLM. If the gain is real, reduce cost by lowering candidate count, using a smaller reranker, batching, or truncating chunks, rather than dropping the stage.

5. Retrieval returns the right document at rank 30, but the answer is wrong. What do you change? The prompt only sees the top few chunks, so this is a precision problem, not a recall problem. Add or improve a reranker over the top 30 to 50 candidates, and check chunk sizes so the relevant passage is not diluted. The wider debugging approach is in Your RAG System Gives Wrong Answers: How Do You Debug It?.

Common mistakes

  • Adding raw BM25 and cosine scores together without normalisation, so one retriever silently dominates.
  • Reranking too many candidates, or the whole corpus, and blowing the latency budget.
  • Reranking too few candidates, so the right document never reaches the reranker.
  • Applying metadata filters to only one of the two retrievers, producing inconsistent candidate sets.
  • Forgetting to deduplicate chunks that appear in both lists before reranking.
  • Ignoring the reranker's maximum input length and letting long chunks be truncated silently.
  • Evaluating only end-to-end answers, so you cannot tell whether retrieval, fusion or reranking is at fault.
  • Claiming hybrid search or reranking always helps, instead of testing on your own data.