RAG — Vector Search

Re-Ranking Strategies After Vector Retrieval

Direct answer

Re-ranking is a second pass after vector search: retrieve a wide candidate set quickly (often 50–150 chunks from vector plus keyword search), then score each candidate against the question with a more accurate but slower model — usually a cross-encoder — and keep only the top 5–20 for the LLM. It is typically the single cheapest accuracy gain in a RAG pipeline, at the cost of tens to a few hundred milliseconds per query.

Vector search is built for speed: questions and documents are embedded separately, so millions of chunks can be compared in milliseconds. That separation is also its weakness — the model never looks at the question and the chunk together. Re-ranking fixes this by spending more compute on a short list. This guide covers the main re-ranking strategies, how to combine them, what they cost in latency, and how to prove they improved your answers.

Vector search Keyword (BM25) Fuse (RRF)~100 candidates Cross-encoderquestion + chunk together Top 5–20to the LLM Stage 1 optimises recall · Stage 2 optimises precision

Key facts, with sources

  • Sentence-Transformers documents the retrieve-and-re-rank pattern: a fast retriever returns about 100 candidates, then a cross-encoder — which reads query and passage together — re-scores them for higher accuracy. (Sentence-Transformers docs)
  • In Anthropic's retrieval tests, adding re-ranking on top of contextual embeddings and BM25 cut top-20 retrieval failures from 2.9% to 1.9%; they retrieved 150 chunks and re-ranked down to 20. (Anthropic)
  • Elasticsearch's reciprocal rank fusion scores each document as the sum of 1 / (k + rank) across result lists, with a default rank constant k of 60. (Elastic docs)

Why vector search alone ranks badly

Embedding models are bi-encoders: the question becomes one vector, each chunk becomes another, and similarity is a single number computed between them. Everything the model knows about the chunk has to be squeezed into that vector before it ever sees the question. That works well for broad topical matches and poorly for the details that decide relevance — negation ('which plans do NOT include support'), exact identifiers, or which of five near-identical policy versions applies.

A cross-encoder reads the question and the chunk as one input, so attention can connect 'NOT include' to the specific plan row. It is far more accurate per pair, and far too slow to run against a whole corpus. Hence two stages: cheap recall first, expensive precision on a short list.

The main re-ranking strategies compared

There is no single best re-ranker; there is a best fit for your latency budget, data sensitivity and scale. Most production systems combine two of these: rank fusion to merge vector and keyword results, then a cross-encoder for the final ordering.

StrategyHow it worksAdded latencyBest for
Reciprocal rank fusionMerges ranked lists by 1/(k + rank); no model~0 msCombining vector + keyword results
Self-hosted cross-encoderSmall transformer scores each (question, chunk) pair~20–200 ms for 50–100 pairs on GPU; more on CPUData that can't leave your infrastructure
Hosted re-rank APIProvider's cross-encoder behind an API~100–400 ms incl. networkFast setup, multilingual, no GPU to run
LLM as re-rankerLLM scores or orders candidates in a promptSeconds; highest costSmall candidate sets, complex relevance rules
Metadata / business boostsAdjust scores for recency, source, popularity~0 msFreshness and trust rules on top of any re-ranker
Latencies are indicative and depend heavily on hardware, model size and chunk length. Measure on your own stack.

Step 1: fuse vector and keyword results

Vector and BM25 scores live on different scales, so adding them directly is meaningless. Reciprocal rank fusion sidesteps that by using only rank positions: a chunk ranked highly in either list floats to the top, and a chunk ranked well in both wins. It needs no training and no tuning beyond the constant k.

rrf.py — reciprocal rank fusion
from collections import defaultdict


def rrf(result_lists: list[list[str]], k: int = 60, top_n: int = 100) -> list[str]:
    """Merge ranked lists of chunk IDs. Rank starts at 1."""
    scores: dict[str, float] = defaultdict(float)
    for results in result_lists:
        for rank, chunk_id in enumerate(results, start=1):
            scores[chunk_id] += 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)[:top_n]


if __name__ == "__main__":
    vector = ["a", "b", "c"]
    keyword = ["c", "d", "a"]
    assert rrf([vector, keyword])[:2] == ["a", "c"]  # in both lists -> top

Step 2: re-rank with a cross-encoder

Sentence-Transformers makes a self-hosted cross-encoder a few lines of code. Load the model once at startup, score every (question, chunk) pair from the fused list, and keep the top results. Batch the pairs in one call — scoring them one at a time multiplies latency.

Two practical details: truncate chunks to the model's maximum input length deliberately (otherwise the tail is silently dropped), and keep the original retrieval rank as a tie-breaker.

rerank.py — cross-encoder re-ranking
from sentence_transformers import CrossEncoder

# Load once at startup; pick a re-ranker model that fits your language + latency budget
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")


def rerank(question: str, chunks: list[dict], keep: int = 8) -> list[dict]:
    pairs = [(question, c["text"]) for c in chunks]
    scores = reranker.predict(pairs, batch_size=32)  # one batched call
    ranked = sorted(zip(chunks, scores), key=lambda x: x[1], reverse=True)
    return [c | {"rerank_score": float(s)} for c, s in ranked[:keep]]

Choosing the numbers: candidates, keep, and threshold

100 candidates (recall) re-ranked · score ≥ threshold top 8 to LLM

Three knobs matter. Candidate count sets recall: if the right chunk isn't in the candidates, no re-ranker can save it. Keep count sets how much context the LLM gets. A score threshold lets the system say 'nothing relevant found' instead of passing weak chunks to the model.

Start with the values below, then tune on your question set. Raise candidates if hit rate at 100 is low; lower keep if answers get confused by near-duplicates.

KnobStarting valueRaise it whenLower it when
Candidates retrieved50–150Right chunk often missing from candidatesRe-rank latency too high
Chunks kept for the LLM5–20Answers miss related detailsAnswers mix up similar documents
Minimum re-rank scoreTune per modelWeak chunks cause wrong answersToo many 'I don't know' replies

Measuring whether re-ranking helped

Re-ranking should be justified with numbers, not vibes. Build a labelled set: for each of 50–200 real questions, record which chunk or document contains the answer. Then compare pipelines on two retrieval metrics — hit rate at k (is a correct chunk in the top k?) and MRR (how high is the first correct chunk?) — and on end-to-end answer correctness.

Run the comparison with and without re-ranking at the same keep count. If hit rate at 8 barely moves, your candidates are the problem, not the ordering — fix chunking or add keyword search first. Also track p95 latency: a re-ranker that adds 600 ms to a mobile chat may cost more in abandonment than it gains in accuracy.

Hit rate @k and MRR
def hit_rate_and_mrr(runs: list[tuple[list[str], set[str]]], k: int = 8):
    """runs: (ranked chunk IDs, set of correct chunk IDs) per question."""
    hits, rr = 0, 0.0
    for ranked, gold in runs:
        for i, cid in enumerate(ranked[:k], start=1):
            if cid in gold:
                hits += 1
                rr += 1 / i
                break
    n = len(runs)
    return hits / n, rr / n

When re-ranking isn't worth it

Skip it, for now, when the corpus is small enough that you can send most relevant documents anyway, when questions are simple lookups that keyword search already nails, or when your latency budget is already spent (voice assistants, type-ahead search). In those cases, better chunking, metadata filters and hybrid search get most of the benefit at zero added latency. Add re-ranking when your measured hit rate at k plateaus and the misses are 'right document, wrong order' rather than 'never found'.

When to hire senior help

Vector search is easy to start and hard to run well at scale, so bring in senior help when recall problems, filtered-query slowdowns, or index rebuild windows start affecting production, since these usually trace to index and schema decisions made early. An experienced engineer can also prevent the expensive mistake of migrating databases when the real problem is chunking or embedding quality. If your stack includes React Native + Python + AI, a senior engineer who owns the full product beats coordinating multiple juniors.

Bottom line

Dhairya Senjaliya ships RAG — Vector Search projects worldwide — book a scoping call to discuss your specific situation.

Common pitfalls to avoid

  • ✕Adopting a dedicated vector database before checking whether pgvector on the Postgres already in your stack meets scale needs at a fraction of the operational cost.
  • ✕Benchmarking only latency and ignoring recall, then shipping an ANN index tuned so aggressively it silently misses relevant documents.
  • ✕Discovering metadata filtering requirements late, since filtered vector search behaves very differently across engines and can collapse recall or throughput.
  • ✕Upgrading embedding models without budgeting a full re-embed, or worse, mixing embeddings from different models in the same index.

Frequently asked questions

What is re-ranking in RAG?

A second retrieval stage that re-scores a short list of candidates from vector or keyword search using a more accurate model, usually a cross-encoder that reads the question and each chunk together. Only the best few chunks are then sent to the LLM.

What's the difference between a bi-encoder and a cross-encoder?

A bi-encoder embeds the question and documents separately, so document vectors can be precomputed and searched at scale. A cross-encoder processes the question and a document together, which is more accurate but must run at query time for every pair — so it's used only on a short candidate list.

How many results should I re-rank?

Commonly 50–150 candidates, keeping 5–20 for the LLM. Tune on a labelled question set: increase candidates if correct chunks are missing, decrease if re-rank latency is too high.

Does re-ranking add a lot of latency?

Usually tens to a few hundred milliseconds when pairs are batched, depending on model size, hardware, and chunk length; LLM-based re-ranking can take seconds. Measure p95 latency on your own stack before and after.

Can I use an LLM as the re-ranker?

Yes, and it can follow nuanced relevance rules, but it is the slowest and most expensive option. It fits small candidate sets or offline batch work; for interactive search, a cross-encoder is usually the better trade-off.

Do we need a dedicated vector database or is pgvector enough?

Published benchmarks show Postgres with pgvector and pgvectorscale matching or beating dedicated services at 50-million-vector scale at roughly a quarter of the cost, and it keeps vectors next to your relational data. Dedicated databases earn their place at billions of vectors, strict multi-tenant isolation, or when your team lacks Postgres operations capacity.

What does vector search cost at our scale?

Embedding a million average-sized chunks costs only a few dollars with current embedding APIs; the real cost is serving, where managed vector databases commonly run hundreds to thousands of dollars per month at tens of millions of vectors. Self-hosted Postgres benchmarked around 75% cheaper than a managed alternative at the 50-million-vector mark.

How do we choose HNSW parameters?

Higher m and ef_construction improve recall at the cost of build time and memory, and higher ef_search trades queries per second for recall at query time. Tune against a ground-truth set built from your own data, targeting 95% to 99% recall, rather than copying defaults from a benchmark run on different data.

Bottom line: Dhairya Senjaliya ships RAG — Vector Search projects worldwide. Book a scoping call at https://dhairyasenjaliya.com/#book-call.

Sources

Related guides

Keep up with new guides

New deep-dive guides on React Native, Python, and AI ship regularly. Subscribe via RSS or follow on LinkedIn.

Want help implementing this?

30-minute scoping call · Clear milestones · Senior engineer ownership