Build a Hybrid Keyword + Vector Search Engine with RRF Fusion


databases performance scalability

AI System Design Deep Dive

Hybrid Keyword + Vector Search

Two retrievers disagree on three quarters of the candidate set. The merge decides the ranking.

⏱ 14 min read 📐 Advanced 🗃️ Vector Search

Two search parties are looking for the same missing hiker. One follows footprints, which is exact and unarguable and useless the moment the trail crosses rock. The other reasons about where a tired person would plausibly head at dusk, which covers ground the first party never visits and is confidently wrong about a third of the time. Sending out both parties is the easy decision. The hard one is what to do when they radio back disagreeing, given that one reports GPS coordinates and the other reports hunches, and the two are not on the same scale.

That is the whole problem of hybrid search. We have 180 million product and support documents, 4,000 queries per second at peak, and a 45ms p99 budget from HTTP request to rendered page. A BM25 inverted index finds the document containing X1C-21-SSD-1TB and nothing else will. A dense HNSW index over 1024-dimensional embeddings finds the document about “laptop storage upgrade that does not void warranty” and no amount of term matching will. Run both lanes at retrieval depth 500 and they return 1,000 candidate slots holding 738 unique documents, which means only 262 documents were found by both. Seventy-three percent of the candidate set came from exactly one retriever.

That overlap number is the argument for hybrid search and also the reason the merge step is the hardest part of the system. If the two lanes agreed you would not need both. Because they disagree on three quarters of the set, the function that combines them determines the final ranking far more than either index’s own tuning does. And the two lanes produce numbers that cannot be compared: BM25 is unbounded and scales with inverse document frequency, so a three-term rare query yields scores between 40 and 60 while a single common term yields 4 to 8, whereas cosine similarity is pinned to a narrow band where 0.82 is excellent and 0.71 is garbage and the gap between them is smaller than BM25 measurement noise.

Reciprocal Rank Fusion resolves this by refusing to look at the scores at all. It uses only each document’s position in each lane, 1 / (k + rank), summed across lanes. Throwing away the scores is what makes it robust, and it is also what makes it expensive in ways that do not show up until you try to paginate: a ranking built from positions has no absolute meaning, so you cannot threshold it, you cannot tell a great result from a mediocre one, and the score of any document depends on how deep you looked. We need to solve for calibration across incomparable scorers, stable ordering under pagination, and candidate sufficiency under filters, simultaneously, at 4,000 QPS.

Requirements and Constraints

Functional Requirements

  • Accept a free-text query plus structured filters (category, price_cents range, in_stock, acl_groups) and a page cursor
  • Retrieve from a lexical index and a dense vector index over the same 180M document corpus
  • Fuse the two ranked lists into one ordering with RRF, weighted by detected query intent
  • Rerank the fused head with a cross-encoder when the query intent warrants it
  • Return 25 hydrated results plus an opaque cursor that yields a consistent next page
  • Collapse product variants to a parent document so a single shirt in nine colours occupies one slot
  • Enforce document-level ACLs as part of retrieval, never as a post-filter
  • Expose per-lane diagnostics (lane_sizes, overlap_count, degraded_lane) on every response

Non-Functional Requirements

  • Latency: 45ms p99 end to end for page 1, 20ms p99 hard deadline for the retrieval fan-out, 4.3ms p50 for fusion
  • Throughput: 4,000 QPS peak, 1,200 QPS average, retrieval depth D = 500 per lane
  • Quality: nDCG@10 above 0.69 on an 18,400-query golden set, recall@100 above 0.94, and no per-intent bucket regressing more than 1.5 nDCG points between deploys
  • Cost: under $7 per million queries all-in, including GPU inference for query embedding and reranking
  • Capacity: 214 GB of compressed postings, 37.6 GB of resident dense index, both fitting a fixed fleet with 40 percent headroom
  • Freshness: a document edited at 10:00:00 appears with correct ranking in both lanes by 10:00:30
  • Determinism: identical query plus identical cursor plus identical index epoch returns byte-identical ordering

Constraints

  • Embedding model is bge-large-en-v1.5, 1024 dimensions, fixed for the life of an index epoch
  • Cross-encoder is ms-marco-MiniLM-L6-v2 on A10G GPUs, 256-token truncation
  • Lexical scoring is BM25 with k1 = 1.2, b = 0.75, on a custom analyzer that preserves alphanumeric identifiers
  • Dense index is HNSW with M = 16, maxM0 = 32, efSearch = 256, product quantization to 64 bytes
  • Out of scope: learning-to-rank with gradient-boosted trees over hundreds of features, personalization, and multilingual analysis. All three are real and all three are separate systems.

High-Level Architecture

Six components, and the interesting one is fourth.

Hybrid search architecture with a query understanding tier, parallel sparse and dense retrieval lanes, an RRF fusion layer, and a cross-encoder reranker

A query arrives at the Search API, which validates filters, resolves the ACL group set for the caller, and decodes the cursor if one was supplied. It then fans out three ways at once. The Text Analyzer stems, splits, and expands the query into scored terms, taking 0.4ms. The Intent Classifier, a logistic regression over 22 cheap features, labels the query exact, natural, or mixed in 0.2ms, and that label selects the fusion weights and the retrieval depth. The Query Embedder batches the raw text onto an L4 GPU and returns a 1024-dimensional vector in 3.1ms, which is the single longest step in the query understanding tier and the reason it runs in parallel with the other two rather than after them.

The two retrieval lanes then run concurrently against the same corpus under a shared 20ms deadline. The Sparse Index is a block-max WAND implementation over 12 shards holding 214 GB of compressed postings. The Dense Index is 8 HNSW shards holding 180M quantized vectors, 37.6 GB resident and mlocked. Each lane returns exactly D document ids in rank order. Notably, each lane returns ids and ranks, not scores. The scores are computed, used for the lane’s internal ordering, and then dropped on the floor before the lane hands anything to the next stage.

The RRF Fusion Layer consumes the two rank lists, unions them, collapses variants to parents, assigns w_s / (k + rank_s) + w_d / (k + rank_d) to each unique document, and sorts with a deterministic three-part key. It emits a fused head of 50 ids. The Cross-Encoder Reranker scores the head as 50 query-document pairs on an A10G and reorders it, but only for queries the intent classifier labelled natural or mixed, which is 89 percent of traffic. The Doc Store, Postgres fronted by Redis, hydrates the final 25 into titles, prices, images, and facet counts.

One query flowing through parallel sparse and dense lanes into RRF fusion and reranking with a per-stage latency budget

The critical path is 3.1ms of embedding, 11.2ms of dense retrieval, 4.3ms of fusion, 18ms of reranking, and 3ms of hydration, which is 39.6ms, and the sparse lane’s 9.6ms disappears entirely into the dense lane’s shadow. That asymmetry is worth sitting with. The lexical index costs three times the RAM and three times the CPU of the dense index and contributes nothing to the latency budget, because it is faster than the thing it runs beside.

Key Insight

The lanes must emit ranks, not scores, and they must emit global ranks rather than shard-local ranks. Every design mistake in hybrid search traces back to letting a raw score or a shard-local position leak into the fusion step.

The Query Understanding Layer

Its job is to decide, in under 4ms, how much to trust each retriever for this specific query.

The non-obvious part is that a single global weighting is actively harmful. Uniform RRF weights score 0.689 nDCG@10 overall on our golden set, which looks like a clean win over dense-only at 0.612. Break it down by intent and the average is hiding a regression. On the 11 percent of queries containing an exact identifier, a part number, a SKU, an error code like ORA-01555, lexical-only scores 0.831 and dense-only scores 0.412. Uniform RRF scores 0.744. Fusion made those queries worse than not fusing, because the dense lane confidently supplied nine plausible neighbours of X1C-21-SSD-1TB at ranks 1 through 9, and RRF has no way to know that a high rank from a lane that cannot possibly be right is worth less than a high rank from a lane that can.

So the classifier exists to answer one question with three answers.

# Query intent classifier: picks RRF weights and retrieval depth per query.
import re
import numpy as np
from dataclasses import dataclass

IDENTIFIER = re.compile(r"[A-Za-z]*\d[A-Za-z0-9]*[-_/][A-Za-z0-9-_/]*|\b[A-Z]{2,}-\d{3,}\b")
STOPWORDS = {"the", "a", "of", "for", "how", "what", "why", "to", "is", "do", "does", "with"}


@dataclass(frozen=True)
class FusionPlan:
    intent: str
    w_sparse: float
    w_dense: float
    depth: int
    rerank: bool


def features(query: str, term_idfs: list[float]) -> np.ndarray:
    tokens = query.split()
    n = max(len(tokens), 1)
    return np.array([
        1.0 if IDENTIFIER.search(query) else 0.0,
        sum(c.isdigit() for c in query) / max(len(query), 1),
        sum(t.lower() in STOPWORDS for t in tokens) / n,
        min(n, 16) / 16.0,
        float(np.mean(term_idfs)) / 12.0 if term_idfs else 0.0,
        float(np.max(term_idfs)) / 16.0 if term_idfs else 0.0,
        1.0 if query.endswith("?") else 0.0,
        sum(c.isupper() for c in query) / max(len(query), 1),
    ], dtype=np.float32)


# Coefficients fitted on 18,400 labelled queries, 3-class multinomial logistic regression.
W = np.array([
    [4.81, 3.20, -2.94, -1.77, 1.62, 2.05, -1.40, 1.11],   # exact
    [-2.10, -1.85, 3.41, 2.22, -1.04, -0.81, 2.60, -0.55],  # natural
    [0.33, 0.12, 0.40, 0.18, 0.21, -0.09, 0.05, 0.07],      # mixed
], dtype=np.float32)
B = np.array([-1.22, -0.64, 0.51], dtype=np.float32)
LABELS = ("exact", "natural", "mixed")

PLANS = {
    "exact":   FusionPlan("exact", 1.6, 0.6, 300, False),
    "natural": FusionPlan("natural", 0.7, 1.3, 600, True),
    "mixed":   FusionPlan("mixed", 1.0, 1.0, 500, True),
}


def plan(query: str, term_idfs: list[float], margin: float = 0.35) -> FusionPlan:
    logits = W @ features(query, term_idfs) + B
    order = np.argsort(logits)[::-1]
    # Low confidence falls back to symmetric fusion rather than guessing.
    if logits[order[0]] - logits[order[1]] < margin:
        return PLANS["mixed"]
    return PLANS[LABELS[order[0]]]

The margin check matters more than the coefficients. A misclassified natural query sent down the exact path loses 6.2 nDCG points; a correctly hedged one sent to mixed loses 1.1. Being uncertain is cheap, being wrong is not, so the classifier is deliberately tuned to abstain into the symmetric plan whenever the top two logits are close. It abstains on 24 percent of queries.

Analyzer configuration is where identifier queries are usually lost before they reach any index. The default behaviour of most tokenizers is to shatter X1C-21-SSD-1TB into x1c, 21, ssd, 1tb, at which point the exact document has no advantage over every document mentioning ssd.

# Analyzer that keeps alphanumeric identifiers intact while still indexing their parts.
analyzer:
  name: hybrid_product_analyzer
  char_filters:
    - type: mapping
      mappings: ["\\u2013 => -", "\\u2014 => -"]
  tokenizer:
    type: pattern
    pattern: "[\\s,;()\\[\\]{}]+"
  token_filters:
    - type: word_delimiter_graph
      catenate_all: true
      preserve_original: true
      split_on_numerics: false
      generate_word_parts: true
    - type: lowercase
    - type: kstem
    - type: synonym_graph
      expand: false
      synonyms_path: /etc/search/synonyms.txt
    - type: unique
      only_on_same_position: true

preserve_original: true with catenate_all: true means the posting list gains x1c-21-ssd-1tb, x1c21ssd1tb, and the individual parts. The intact form carries an idf around 15.8 because it occurs in one document, so BM25 ranks the exact match first by a margin no amount of partial matching can close. Setting split_on_numerics: false is what keeps 1tb from becoming 1 and tb.

Watch Out

Using `expand: true` on the synonym graph grows the query term set, and every added term changes the `BM25` score distribution without changing the dense lane at all. On a two-term query, expanding to seven terms moved 31 percent of the sparse top-50 and therefore moved the fused ranking, even though nothing about the corpus or the embedding changed. Use unidirectional synonyms at index time instead.

Premium Content

Unlock the full article along with everything else in the archive — all in one place.

In-depth analysis Expert insights Full archive access
Unlock Full Article