Ranking and Reranking in LLM Systems

  • Home
  • Ranking and Reranking in LLM Systems
image

Ranking and Reranking in LLM Systems

  • CategoryIT & Software
  • AuthorArmen Melkumyan
  • Views0
  • PublishedAugust 9, 2026
11 min read

A practical and mathematical explanation for Retrieval-Augmented Generation, enterprise search, and modern AI applications.

Core Idea

Ranking finds a broad set of plausible documents quickly.

Reranking then spends more computation on that smaller set to choose the best evidence for the LLM.

1. Executive Summary

Ranking is the process of ordering candidate items by estimated relevance to a user query.

In a search system, those items are usually documents, passages, database rows, code snippets, or tool results. In an LLM system, ranking decides which evidence is likely useful enough to show the model.

Reranking is a more expensive second pass. It takes the top candidates from the first ranking stage and reorders them with a stronger model that can compare the query and each candidate more deeply.

This matters because LLM answers are highly sensitive to the quality of the context they receive.

A practical retrieval pipeline is therefore not just one search operation. It is usually a multi-stage funnel:

User question → candidate retrieval → first-stage ranking → reranking of top-N candidates → context assembly → LLM answer grounded in selected evidence

2. Why Ranking Matters for LLMs

LLMs have limited context windows and limited attention quality.

Even very long-context models should not be treated as if they can reliably inspect an entire enterprise knowledge base on every request. Ranking acts as the gatekeeper that decides what information enters the prompt.

For example, if a user asks:

“Which leave policy applies to contractors in Armenia?”

An enterprise assistant may have access to thousands or millions of chunks from HR policies, legal contracts, onboarding docs, emails, and support tickets.

The LLM should not receive all of them.

A ranker assigns a relevance score to each plausible candidate and sorts them.

Score idea:

score(query, document) = relevance number

Example ranking:

doc_17 → 0.91 → contractor leave policy for Armenia doc_204 → 0.86 → international contractor benefits doc_31 → 0.79 → employee leave policy overview doc_88 → 0.42 → office holiday schedule

Practical Consequence

Bad ranking produces bad context.

Bad context often produces confident but wrong answers, even when the LLM itself is strong.

3. Ranking: The First-Stage Relevance Problem

A ranking function estimates how relevant a candidate document D is for a query Q.

The system then sorts candidates by this score.

Given:

Query Q and candidates D1, D2, ..., Dn

Compute:

score(Q, Di) for each candidate

Return:

Candidates sorted by descending score

First-stage ranking must be fast and scalable.

It is often designed for high recall: the goal is to include the right answer somewhere in the top-N candidates, even if the exact order is imperfect.

Reranking can then improve precision later.

4. Sparse, Dense, and Hybrid Ranking

4.1 Sparse Lexical Ranking

Sparse ranking, also called lexical ranking, scores documents based on word overlap with the query.

The most famous classical method is BM25.

It rewards documents that contain important query terms, especially rare terms, while controlling for document length.

BM25 formula:

BM25(D, Q) = Σ[t in Q] IDF(t) × { f(t,D) × (k₁ + 1) } / { f(t,D) + k₁ × [1 − b + b × |D| / avgdl] }

Where:

f(t,D) = frequency of term t in document D

IDF(t) = inverse document frequency of term t

|D| = document length

avgdl = average document length

k₁ and b = tuning parameters

Sparse ranking is excellent for exact terms:

Names, error codes, legal clauses, SKUs, API methods, product IDs, compliance labels, and rare terminology.

Its weakness is vocabulary mismatch.

It may miss that “expense claim” and “travel reimbursement” can mean the same thing.

4.2 Dense Semantic Ranking

Dense ranking uses embeddings.

An encoder converts the query and each document into vectors. Relevance is then estimated using a similarity function, most commonly dot product or cosine similarity.

Vector creation:

q = Encoder(query)

d = Encoder(document)

Cosine similarity formula:

cosine_similarity(q, d) = (q · d) / (||q|| × ||d||)

Higher similarity means the document is semantically closer to the query.

Dense ranking is useful when the user and the document use different words for the same concept.

For example, a query about:

“how to get reimbursed for work travel”

can match a document saying:

“employees may submit expense claims for business trips.”

4.3 Hybrid Ranking

Hybrid ranking combines sparse and dense signals.

Sparse ranking protects exact-match precision; dense ranking adds semantic recall.

In practice, hybrid search often retrieves top candidates from BM25 and from embeddings, merges them, deduplicates them, and then applies score fusion or rank fusion.

Candidate set formula:

Candidate set = top_k_sparse(Q) ∪ top_k_dense(Q)

Hybrid score example:

score = α × normalized_dense_score + (1 − α) × normalized_sparse_score

Sparse / BM25

Main signal: Exact or lexical term overlap.

Strength: Great for names, codes, IDs, rare terms, and exact phrases.

Weakness: Can miss paraphrases and semantic matches.

Dense / Vector

Main signal: Embedding similarity.

Strength: Great for semantic matching and wording variation.

Weakness: Can miss exact constraints and may retrieve plausible but wrong neighbors.

Hybrid

Main signal: Sparse plus dense signals.

Strength: Better recall and robustness across query types.

Weakness: Needs score calibration, deduplication, and tuning.

5. Reranking: The Second-Stage Precision Layer

Reranking starts after retrieval has produced a smaller candidate set.

The reranker evaluates each query-document pair more carefully and reorders the candidates.

The key idea is to spend expensive computation only where it matters.

First-stage search:

1,000,000 chunks → top 100 candidates

Reranker:

top 100 candidates → best 5 to 15 chunks

LLM:

reads only the best selected context

A first-stage dense retriever often uses a bi-encoder.

It embeds the query and document independently. This is fast because document vectors can be precomputed and stored in a vector database.

Bi-encoder scoring:

q = Encoder(query)

d = Encoder(document)

score = q · d

A reranker often uses a cross-encoder.

It reads the query and document together, allowing token-level interactions between them.

This is slower, but usually more accurate because the model can compare exact phrases, entities, dates, constraints, and reasoning relations directly.

Cross-encoder reranking:

score = Model(query + document)

Training target example:

P(relevant = 1 | query, document)

A common reranker training objective is binary cross-entropy over relevant and non-relevant query-document pairs.

Loss formula:

Loss = −Σ[positive pairs] log(sⱼ) − Σ[negative pairs] log(1 − sⱼ)

Where:

sⱼ = model score interpreted as relevance probability

First-Stage Ranker vs. Reranker

Goal:

First-stage ranker: High recall Reranker: High precision Why it matters: Find candidates first, choose best later Typical scale: Millions → hundreds

Speed:

First-stage ranker: Very fast Reranker: Slower Why it matters: Reranking is applied only to top-N Typical scale: 50 to 200 candidates

Model type:

First-stage ranker: BM25 or bi-encoder Reranker: Cross-encoder or LLM scorer Why it matters: Joint query-document reasoning improves quality Typical scale: Top 5 to 20 final chunks

Precompute:

First-stage ranker: Usually yes Reranker: Usually no Why it matters: Cross-encoding depends on the query Typical scale: Per request

Failure mode:

First-stage ranker: Misses correct item Reranker: Cannot recover missing item Why it matters: Recall before reranking is critical Typical scale: Tune top-N

6. How Ranking and Reranking Are Used in LLM Applications

6.1 Retrieval-Augmented Generation

In RAG, the LLM is not expected to know or memorize every fact.

Instead, a retrieval system finds relevant evidence from external sources and injects that evidence into the prompt.

Ranking decides which chunks are candidates.

Reranking decides which candidates are most worth showing to the model.

RAG answer flow:

Question:

“What is the refund policy for enterprise annual contracts?”

Ranker returns:

refund docs, billing docs, cancellation docs, contract docs

Reranker promotes:

exact enterprise annual contract refund clause

LLM answers:

grounded in the selected clause

6.2 Enterprise Search and Assistants

Enterprise assistants rank and rerank across internal documents, PDFs, emails, tickets, Slack or Teams messages, source code, wikis, and database records.

Reranking is particularly valuable when many documents contain similar language but only one document matches the user-specific constraints.

6.3 Code Assistants

Code assistants retrieve files, functions, stack traces, pull requests, issues, package documentation, and implementation examples.

Ranking finds potentially useful snippets.

Reranking selects the snippets most relevant to the current task, such as the exact class or method where a bug occurs.

6.4 External Memory and Personalization

Some LLM systems maintain external memory: saved facts, previous conversation snippets, preferences, or long-term project notes.

Ranking retrieves possibly relevant memories.

Reranking helps avoid injecting stale, irrelevant, or conflicting memories into the prompt.

6.5 Tool Use and Answer Selection

Ranking is not limited to documents.

Agentic LLM systems may rank tools, API results, SQL rows, web pages, or candidate plans.

A model may also rank candidate answers or citations before producing the final response.

6.6 Next-Token Ranking Inside the LLM

There is also a narrower internal meaning: at generation time, an LLM ranks possible next tokens by probability.

This is not document reranking, but it is still a ranking process.

At each generation step:

P(tokenᵢ | context) is computed for vocabulary tokens.

Decoding chooses from the ranked distribution.

Common decoding methods include:

greedy decoding, beam search, top-k sampling, and top-p sampling.

7. Evaluation Metrics and Practical Tuning

Ranking systems should be evaluated separately from final LLM answer quality.

If retrieval is poor, the model may never see the evidence needed to answer correctly.

Recall@k

Whether a relevant document appears in the top k results.

This is crucial for first-stage retrieval.

Precision@k

How many of the top k results are actually relevant.

This is important for the final context window.

MRR — Mean Reciprocal Rank

How high the first relevant result appears.

NDCG — Normalized Discounted Cumulative Gain

Rewards placing highly relevant items near the top.

Answer Faithfulness

Whether the generated answer is supported by retrieved evidence.

Citation Accuracy

Whether cited chunks actually support the claims made by the LLM.

A strong practical tuning loop measures both retrieval metrics and answer metrics.

For example, increasing the number of candidates before reranking may improve recall, but it can increase latency and cost.

Reducing the final number of chunks may reduce noise, but it can remove necessary evidence.

Practical Tuning Levers

Increase First-Stage Top-N

Improves: Recall before reranking

Tradeoff: More reranker cost and latency

Common starting point: 50 to 200 candidates

Use Hybrid Search

Improves: Robustness across exact and semantic queries

Tradeoff: More tuning complexity

Common starting point: BM25 plus vector search

Use Stronger Reranker

Improves: Precision of final chunks

Tradeoff: Higher compute cost

Common starting point: Cross-encoder or small LLM scorer

Reduce Final Chunks

Improves: Less context noise

Tradeoff: May lose evidence

Common starting point: 5 to 15 chunks

Improve Chunking

Improves: Better candidate quality

Tradeoff: Indexing complexity

Common starting point: Semantic sections with overlap

8. Common Failure Modes and Mitigations

Correct Document Never Retrieved

The reranker cannot fix a missing candidate.

Mitigation:

Increase first-stage top-N, improve chunking, add hybrid search, and evaluate Recall@k.

Wrong Version Selected

Rankers may retrieve outdated policies or duplicated documents.

Mitigation:

Add metadata filters, freshness signals, document versioning, and source authority rules.

Semantic False Positive

Dense retrieval may retrieve text that sounds related but is not actually applicable.

Mitigation:

Use hybrid ranking, reranking, and evidence-aware answer validation.

Context Stuffing

Too many chunks can confuse the LLM.

Mitigation:

Rerank, deduplicate, compress, and pass only the best evidence.

Over-Optimization to Benchmark Queries

A system can perform well on a test set but fail on real user queries.

Mitigation:

Evaluate on production-like data and monitor drift.

Latency and Cost Blowup

Reranking too many candidates with too large a model can be expensive.

Mitigation:

Use cascaded ranking: cheap first, stronger second, strongest only when needed.

9. Recommended Production Pattern

For most serious LLM applications, especially enterprise RAG systems, the recommended pattern is a multi-stage retrieval funnel rather than a single vector search call.

  1. Chunk documents by meaningful semantic units, not only by fixed token counts. Preserve titles, section headings, dates, owners, and permissions as metadata.
  2. Build both sparse and dense indexes when exact terms and semantic matches are both important.
  3. Retrieve a generous candidate set using hybrid search. Optimize first-stage retrieval for recall.
  4. Rerank the candidate set using a cross-encoder, specialized reranker, or carefully prompted small LLM scorer.
  5. Deduplicate and diversify the final context to avoid repeated near-identical chunks.
  6. Assemble the final prompt with source names, dates, and clear evidence boundaries.
  7. Require the answer to cite only evidence actually present in the context.
  8. Measure retrieval quality and answer quality separately, then monitor both in production.

Design Rule

Do not rely on the LLM to rescue poor retrieval.

The retrieval and reranking layers are part of the intelligence of the overall system.

10. References

Stanford NLP Group. Introduction to Information Retrieval, section on Okapi BM25. https://nlp.stanford.edu/IR-book/html/htmledition/okapi-bm25-a-non-binary-model-1.html

OpenAI. Embeddings guide. https://platform.openai.com/docs/guides/embeddings

OpenAI. Retrieval and File Search documentation. https://platform.openai.com/docs/guides/retrieval

Anthropic. Contextual Retrieval. https://www.anthropic.com/news/contextual-retrieval

Nogueira, R. and Cho, K. Passage Re-ranking with BERT. arXiv:1901.04085. https://arxiv.org/abs/1901.04085

Lewis, P. et al. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. arXiv:2005.11401. https://arxiv.org/abs/2005.11401

Craswell, N. et al. MS MARCO: A Human Generated Machine Reading Comprehension Dataset. https://arxiv.org/abs/1611.09268

Author Armen Melkumyan

Armen Melkumyan

Armen Melkumyan