Home / AI Architecture & System Design / RAG & Retrieval

RAG & RetrievalMidQuestion 3 of 12

Why use hybrid search instead of only vector search?

30-second answer

Dense embeddings capture meaning and paraphrase but are weak on exact tokens such as error codes, SKUs, names and rare jargon. BM25 excels at exact matches. Combining them (often with Reciprocal Rank Fusion) improves recall across both query types at little cost.

Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.

New to these terms? 13 terms on this page are explained in the glossary

0–5 min Functional requirements

This sounds like a "why" question, but the strongest answers show why with concrete failures, then design the retrieval service. Start by agreeing on what the service does.

You Before designing, can I check what kinds of queries we get? Hybrid search is only worth it if both kinds exist.

Interviewer It's the retrieval layer for our developer-docs assistant. Users ask natural questions like "how do I rotate my keys?" but also paste error codes like ERR_4012 or CLI flags like --no-verify.

You That's the classic case. Vector search handles "rotate my keys" ≈ "regenerate credentials" well, but often misses ERR_4012: the embedding model has never seen that token, so the vector lands near generic error pages. BM25 nails the exact code but misses paraphrases. What does a caller need back?

Interviewer Top results with scores and a snippet, fast, with filters for product and version.

# Functional requirement Why it matters
F1 Given a query and filters, return the top-k chunks with scores and highlighted snippets The contract for the RAG layer above
F2 Handle both exact-term queries (codes, flags, names) and natural-language questions Each retrieval method fails on one kind
F3 Filters: product, version, language, document type Avoid answers for the wrong version
F4 Incremental index updates: add, update and delete documents Docs change daily
F5 Explain results: which retriever found each hit and why Debugging relevance problems

Out of scope: the answer-generation step, query autocomplete, personalization.

5–10 min Non-functional requirements and estimates

You What's the latency budget for retrieval inside the whole assistant?

Interviewer About 250 ms including reranking.

You Then the two retrievers must run in parallel, each with a timeout, and reranking gets about 100 ms of that budget.

Requirement Target What it forces in the design
Latency Retrieval + fusion ≤ 150 ms p95; with reranking ≤ 250 ms Parallel fan-out, per-retriever timeouts
Quality Recall@10 ≥ 90% overall and ≥ 85% for every query type Evaluation segmented by query type
Throughput 300 queries/s at peak Replicated indexes, batched reranking
Freshness Updates searchable ≤ 1 min Near-real-time index refresh
Consistency Both indexes see the same document version Shared document versioning
Degradation If one retriever fails, return results from the other Partial results instead of errors

Back-of-envelope estimates:

  • Corpus: 50M chunks (docs across many products and versions, plus community Q&A).
  • Vector index: 50M × 768 dimensions × 4 bytes ≈ 154 GB in float32. Use int8 scalar quantization (~38 GB) with full-precision re-scoring of the top candidates, sharded across nodes.
  • BM25 index: usually around 30–50% of the raw text size; with ~20 GB of chunk text, roughly 6–10 GB. Small compared with vectors.
  • Rerank load: 300 queries/s × 50 candidates = 15,000 query–document pairs/s. At ~256 tokens per pair, a small cross-encoder needs a few GPUs with batching.
  • Query embedding: 300 embeddings/s, a few milliseconds each on a small embedding model.

10–18 min High-level design

You The query path fans out to both retrievers at once, merges their rankings, then reranks. The write path keeps both indexes in sync from one event stream.

Scroll sideways to see the whole diagram.

Hybrid retrieval with rank fusionComponents: Query; BM25 (exact terms · IDs); Vector ANN (semantic similarity); RRF fusion (Σ 1 / (60 + rank)); Cross-encoder (rerank top 50); Top 5 chunks (sent to the LLM). Flow: Query to BM25; Query to Vector ANN; BM25 to RRF fusion (top 50); Vector ANN to RRF fusion (top 50); RRF fusion to Cross-encoder; Cross-encoder to Top 5 chunks.QueryBM25exact terms · IDsVector ANNsemantic similarityRRF fusionΣ 1 / (60 + rank)Cross-encoderrerank top 50Top 5 chunkssent to the LLMtop 50top 50
Hybrid retrieval with rank fusion. BM25 and vector search run in parallel, Reciprocal Rank Fusion merges their rankings, and a cross-encoder picks the final few chunks.

Components:

  • Query service: normalizes the query, embeds it, runs both retrievers in parallel, fuses results, calls the reranker and returns the top-k.
  • BM25 index: a search-engine index with analyzers suited to technical text.
  • Vector (ANN) index: HNSW over quantized embeddings, sharded, with filter support.
  • Fusion: Reciprocal Rank Fusion of the two candidate lists.
  • Reranker: a cross-encoder that scores the top 50 query–chunk pairs.
  • Indexer: consumes document change events and writes to both indexes with the same version.

Query sequence, including a timeout:

Scroll sideways to see the whole diagram.

Hybrid query with parallel retrieversCaller → Query service: search(q, filters); Query service → BM25 index: BM25 top 50; Query service → Embedder: embed query; Embedder → Query service: query vector; Query service → Vector index: ANN top 50 + filters; Note: BM25 and ANN run in parallel, 80 ms timeout each; BM25 index → Query service: 50 hits; Vector index → Query service: 50 hits; [if one retriever times out]; Query service: use the other; degraded; [then]; Query service: RRF merge; Query service → Reranker: rerank 50 pairs; Reranker → Query service: scores; Query service → Caller: top 10 + explain.CallerRAG layerQuery serviceEmbedderBM25 indexVector indexHNSW · int8Rerankersearch(q, filters)BM25 top 50embed queryquery vectorANN top 50 + filtersBM25 and ANN run in parallel, 80 ms timeout each50 hits50 hitsIF ONE RETRIEVER TIMES OUTuse the other; degradedTHENRRF mergererank 50 pairsscorestop 10 + explain
Hybrid query with parallel retrievers. BM25 starts immediately; the vector search starts once the query is embedded. Each retriever has a timeout, and if one misses it, the other's results are used and the response is marked degraded. Results are fused with RRF and reranked.

API sketch:

POST /v1/search
{ query, k: 10, filters: { product, version, lang }, rerank: true, explain: false }
→ { results: [{ chunk_id, doc_id, score, snippet,
                sources: { bm25_rank, vector_rank }, rerank_score }],
    degraded: false }

degraded: true tells the caller that one retriever timed out, which is useful for monitoring and for showing a hint in the UI.

How it works: a worked example

A study aid: one developer query traced through both retrievers, fusion and reranking, with real ranks and scores, so you can see why hybrid beats either alone.

The query: "ERR_CONN_RESET when calling upload API v3 behind a proxy" with filters product=storage, version=3.x, lang=en.

1. Fan-out (in parallel, 80 ms timeout each):

Rank BM25 (keyword) Vector (semantic)
1 err-codes#ERR_CONN_RESET (exact error code) troubleshoot#proxy-timeouts
2 release-notes-3.2#fixes (mentions the code) upload-guide#large-files
3 troubleshoot#proxy-timeouts network#corporate-proxies
4 forum#88123 err-codes#ERR_CONN_RESET
… 50 results 50 results

BM25 nails the exact error code; vectors find the conceptually related proxy-timeout page even though it never says "ERR_CONN_RESET".

2. Reciprocal Rank Fusion (k = 60): score = 1/(60 + rank_bm25) + 1/(60 + rank_vector).

troubleshoot#proxy-timeouts   1/63 + 1/61 = 0.0323   ← in both lists near the top
err-codes#ERR_CONN_RESET      1/61 + 1/64 = 0.0320
upload-guide#large-files      (not in BM25 top 50) + 1/62 = 0.0161
release-notes-3.2#fixes       1/62 + (not in vector top 50) = 0.0161

Documents found by both retrievers rise to the top; the fused list keeps the best 50.

3. Reranking. A cross-encoder reads the query with each of the 50 chunks (batched, ~90 ms on a GPU) and reorders:

1. troubleshoot#proxy-timeouts     0.94   "Uploads over 100 MB through proxies may reset…"
2. err-codes#ERR_CONN_RESET        0.88
3. upload-guide#large-files        0.71   "use multipart upload for files > 100 MB"

4. Response (~210 ms total) to the caller, with explain data for debugging:

{ "results": [ { "chunk_id": "troubleshoot#proxy-timeouts", "rerank_score": 0.94,
                 "sources": { "bm25_rank": 3, "vector_rank": 1 } }, … ],
  "degraded": false }

A degraded case. If the vector shard times out at 80 ms, the service returns BM25-only results with "degraded": true rather than an error; the dashboard counts degraded responses per hour.

Where each piece runs:

Component Runs as Example technology Sizing (300 queries/s, 50M chunks) If it fails
Query service Stateless service Go/Python/Java Low CPU; fan-out and fusion Retries go to another replica
BM25 index Search cluster Elasticsearch/OpenSearch ~6–10 GB index, replicated Vector-only results, degraded: true
Vector index Sharded ANN cluster OpenSearch k-NN, Vespa, Milvus, pgvector at small scale ~38 GB int8 + re-scoring BM25-only results
Query embedder Small model on CPU/GPU Self-hosted embedding model 300 embeddings/s BM25-only results
Reranker GPU inference with batching Cross-encoder on Triton 15,000 pairs/s → a few GPUs Return fused order without reranking
Indexer Event consumer Kafka → indexer writing both indexes with one version Near-real-time refresh ≤ 1 min Lag alert; reads still served

18–32 min Deep dive

You I'd like to cover how fusion works, how to build each index so it doesn't fail on technical text, and how to prove hybrid actually helps.

Interviewer Start with fusion. Why not just add the scores?

Deep dive 1 · Fusing two rankings

BM25 scores are unbounded and depend on the query; cosine similarities sit in a narrow band like 0.7–0.9. Adding them means one scale silently dominates. Reciprocal Rank Fusion avoids that by using ranks only:

RRF(d) = Σ over retrievers  1 / (k + rank_r(d)),   k = 60

A worked example:

Chunk BM25 rank Vector rank RRF score
C: "ERR_4012 when rotating keys" 2 2 1/62 + 1/62 = 0.0323
A: "Error code reference" 1 8 1/61 + 1/68 = 0.0311
B: "Regenerating credentials" — 3 1/63 = 0.0159
D: "Changelog mentioning ERR_4012" 3 — 1/63 = 0.0159

Chunks that both retrievers rank well rise to the top. Chunks found by only one retriever still survive, so the reranker can promote them.

Interviewer When would you use weighted score fusion instead?

When you have a labelled evaluation set and stable score distributions. Normalize each retriever's scores (for example min-max per query), then combine them with a weight α tuned on the evaluation set. It can beat RRF, but needs re-tuning when either model changes. I'd start with RRF and only switch if evaluation shows a gain.

Deep dive 2 · Building the two indexes

BM25 analyzers for technical text. Default analyzers split ERR_4012 into err and 4012, and --no-verify into no and verify, which destroys exact matching. Index each field twice:

  • a standard analyzed field (lowercased, stemmed) for prose,
  • a "code" field that keeps identifiers, flags and paths whole, with a higher boost.

Vector index.

  • Embed chunks with a title prefix (Product > Page > Section) so short chunks carry context.
  • HNSW with M ≈ 32 and efSearch ≈ 100–200, tuned on recall versus latency.
  • int8 quantization with re-scoring of the top 200 candidates at full precision.
  • Filtered search on product and version must be filter-aware. Post-filtering 50 results down to one version can leave almost nothing.

Keeping them consistent. One indexer writes both with the same doc_version. At query time, results whose versions disagree, for example during an update, are deduplicated by keeping the newer version. Deletes go to both indexes first.

Scroll sideways to see the whole diagram.

Keeping both indexes in syncComponents: Doc change event (upsert · delete); Indexer (same doc_version for both); Analyzers (prose + identifier fields); BM25 index; Embedder (title-prefixed chunks); Vector index (HNSW · int8); Query service (dedupe by doc_version). Flow: Doc change event to Indexer; Indexer to Analyzers; Indexer to Embedder; Analyzers to BM25 index; Embedder to Vector index; BM25 index to Query service (read); Vector index to Query service (read).Doc change eventupsert · deleteIndexersame doc_versionfor bothAnalyzersprose +identifier fieldsBM25 indexEmbeddertitle-prefixed chunksVector indexHNSW · int8Query servicededupe by doc_versionreadread
Keeping both indexes in sync. One indexer writes both indexes with the same document version. BM25 gets a standard field and an identifier field that keeps codes and flags whole; the vector index gets title-prefixed chunk embeddings. Queries deduplicate by version.

Deep dive 3 · Proving it helps

Interviewer How would you convince me hybrid is worth the extra complexity?

  • Build an evaluation set of ~500 real queries with labelled relevant chunks, tagged by query type: exact identifier, natural question, mixed, multi-concept.
  • Compare recall@10 and MRR for BM25 alone, vectors alone, hybrid, and hybrid with reranking, per segment.
  • Typical pattern: vectors win on natural questions, BM25 wins on identifiers, and hybrid matches or beats the best of both in every segment. If a segment regresses, look at analyzers or the k value in RRF.
  • Online: track click-through on cited sources and "no good answer" feedback by query type.

32–37 min Trade-offs

Decision Chosen Alternative Why
Retrieval Hybrid (BM25 + vectors) Vectors only Exact identifiers fail with vectors alone
Fusion RRF Weighted score fusion No score calibration needed; robust to model changes
Execution Parallel with timeouts Sequential Latency; partial results beat errors
Analyzers Separate field that keeps identifiers whole Default analyzer Codes and flags must match exactly
Vector memory int8 + re-scoring float32 ~4× less memory, little recall loss
Reranking Cross-encoder on top 50 No reranker Better top results; fewer chunks sent to the LLM
Learned sparse models Not at first SPLADE-style expansion Extra complexity; revisit if vocabulary mismatch remains

Build first: BM25 with the identifier field and vector search, fused with RRF, plus the segmented evaluation set. Add the reranker and quantization once recall is good.

37–40 min Wrap-up and likely follow-ups

Close with: "Vector search and BM25 fail on different queries: paraphrases versus exact identifiers. I'd run both in parallel with timeouts, fuse with Reciprocal Rank Fusion, rerank the top 50 with a cross-encoder, and prove the gain with an evaluation set segmented by query type."

Likely follow-ups:

  • What k in RRF and why 60? It's a smoothing constant that limits how much the very top ranks dominate. 60 works well in practice; tune it on your evaluation set.
  • Does hybrid replace the reranker? No. Hybrid improves recall of the candidate set; the reranker improves precision at the top.
  • How do you handle multiple languages? Language-specific analyzers for BM25, a multilingual embedding model, and a language filter.
  • What about learned sparse retrieval? Models like SPLADE expand terms and can capture some of both worlds; they're an option if vocabulary mismatch persists.

What interviewers listen for

  • Concrete failure examples for each retrieval method.
  • Why raw scores can't simply be added, and how RRF works.
  • Practical index details: analyzers for identifiers, filtered ANN, consistency.
  • Evaluation segmented by query type.

Red flags

  • "Vector search understands meaning, so it's always better."
  • Adding raw BM25 and cosine scores.
  • No evaluation of whether hybrid actually helped.

Discussion

Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.