โ† Back to Blog
RAGAI EngineeringLLMs

Evaluating RAG Retrieval Before the LLM: Golden Sets, Recall@k, MRR, and nDCG

Most teams judge RAG by reading final answers. That hides the real failure: the right chunk never reached the prompt. Here is how to build a golden set and measure retrieval on its own, with runnable code.

By Joinloopยท4 October 2026ยท8 min read
ShareLinkedInXReddit
๐Ÿ“

A RAG system gives a wrong answer. Is the retriever at fault, or the generator? Most teams cannot say, because they only evaluate the final answer. They change the chunk size, swap the embedding model, add a reranker, and judge the result by eyeballing ten outputs. Two weeks later nobody remembers which change helped.

The fix is to evaluate retrieval separately from generation. Retrieval is the cheaper stage to measure: no LLM judge, no subjective grading, just "did the right chunk come back, and how high?" If the right chunk is not in the context window, no prompt will rescue the answer. If it is, any remaining failure is a generation problem and you debug it differently.

Step 1: Build a golden set

A golden set is a list of (query, relevant_chunk_ids) pairs. Aim for 100โ€“200 queries to start. Fewer than 50 and your metrics will jitter too much to compare two configurations.

Three sources, in order of value:

  1. Real user queries from logs, labelled by someone who knows the corpus. Best signal, slowest to build.
  2. Synthetic queries generated by an LLM from each chunk ("write a question this passage answers"). Fast and cheap, but they are biased toward lexical overlap with the chunk, which flatters keyword search.
  3. Hand-written hard cases: acronyms, multi-hop questions, queries with negation, queries whose answer spans two chunks.

A pragmatic mix: 60% synthetic, 40% real or hand-written. Never evaluate only on synthetic data.

import json, random
from anthropic import Anthropic

client = Anthropic()  # reads ANTHROPIC_API_KEY
MODEL = "claude-haiku-4-5-20251001"  # check the docs for current model ids

PROMPT = """Here is a passage from our documentation.
Write ONE realistic question a user might type into a search box whose answer
is contained in this passage. Do not copy phrases verbatim from the passage.
Return only the question.

Passage:
{chunk}"""

def make_golden_set(chunks: dict[str, str], n: int = 150, seed: int = 7):
    random.seed(seed)
    ids = random.sample(list(chunks), min(n, len(chunks)))
    golden = []
    for cid in ids:
        resp = client.messages.create(
            model=MODEL,
            max_tokens=100,
            messages=[{"role": "user", "content": PROMPT.format(chunk=chunks[cid])}],
        )
        golden.append({"query": resp.content[0].text.strip(), "relevant": [cid]})
    return golden

# json.dump(make_golden_set(chunks), open("golden.json", "w"), indent=2)

Read at least 20 of the generated questions yourself. Throw out any that are ambiguous or answerable by several chunks, otherwise your metrics will punish correct retrievals.

Step 2: Pick the metrics

All of these take a ranked list of retrieved chunk ids and the set of relevant ids.

Metric Question it answers Use it when
Hit rate / Recall@k Is a relevant chunk anywhere in the top k? You stuff top-k into the prompt and order doesn't matter much
MRR (mean reciprocal rank) How high is the first relevant chunk? One right answer per query; position matters
nDCG@k How good is the whole ranking, with graded relevance? Multiple relevant chunks, some better than others
Precision@k How much of the top k is noise? Context budget is tight or noise confuses the model

Choose k to match what you actually send to the model. If your prompt takes 5 chunks, Recall@5 is the number that matters, and Recall@50 only tells you whether a reranker has something to work with.

import math

def recall_at_k(ranked: list[str], relevant: set[str], k: int) -> float:
    return len(set(ranked[:k]) & relevant) / len(relevant)

def hit_at_k(ranked, relevant, k) -> float:
    return 1.0 if set(ranked[:k]) & relevant else 0.0

def reciprocal_rank(ranked, relevant) -> float:
    for i, cid in enumerate(ranked, start=1):
        if cid in relevant:
            return 1.0 / i
    return 0.0

def ndcg_at_k(ranked, relevant, k) -> float:
    # binary relevance; pass a dict of grades if you have them
    dcg = sum(1.0 / math.log2(i + 1)
              for i, cid in enumerate(ranked[:k], start=1) if cid in relevant)
    ideal = sum(1.0 / math.log2(i + 1)
                for i in range(1, min(len(relevant), k) + 1))
    return dcg / ideal if ideal else 0.0

Step 3: Run it as a harness, not a notebook

The point is to compare configurations on identical data. Make the retriever a plain function so any variant plugs in.

import json, statistics
from typing import Callable

Retriever = Callable[[str, int], list[str]]  # (query, k) -> ranked chunk ids

def evaluate(retrieve: Retriever, golden: list[dict], k: int = 5) -> dict:
    rows = []
    for ex in golden:
        ranked = retrieve(ex["query"], 50)
        rel = set(ex["relevant"])
        rows.append({
            "hit@k": hit_at_k(ranked, rel, k),
            "recall@50": recall_at_k(ranked, rel, 50),
            "mrr": reciprocal_rank(ranked, rel),
            "ndcg@k": ndcg_at_k(ranked, rel, k),
        })
    return {m: round(statistics.mean(r[m] for r in rows), 3) for m in rows[0]}

golden = json.load(open("golden.json"))
print("dense      ", evaluate(dense_retrieve, golden))
print("bm25       ", evaluate(bm25_retrieve, golden))
print("hybrid     ", evaluate(hybrid_retrieve, golden))
print("hybrid+rerank", evaluate(rerank_retrieve, golden))

Fetch 50 once and slice, so Recall@50 (the ceiling for a reranker) and Hit@5 (what the LLM sees) come from the same run. Log the per-query results too. The average tells you whether you improved; the per-query diff tells you why.

Reading the numbers

The pattern of metrics diagnoses the problem:

Symptom Likely cause Fix to try
Recall@50 low Chunks never indexed well: bad parsing, chunks too large, wrong embedding model for the domain Fix parsing and chunking, add BM25 for hybrid, fine-tune embeddings
Recall@50 high, Hit@5 low Right chunk is retrieved but ranked low Add a cross-encoder reranker
Hit@5 high, MRR low Answer is in the set but buried at rank 4โ€“5 Reranker, or reorder context
Hit@5 high but answers still wrong Retrieval is fine, generation is the problem Switch to answer-level evals and prompt work
Great on synthetic, poor on real queries Golden set leaks lexical overlap Add real and hand-written queries

Statistical honesty

With 150 queries, a 2-point difference in Hit@5 is noise. Two cheap guards:

  • Paired comparison. Compare per-query outcomes between two configs rather than two averages. A bootstrap over the per-query difference gives a confidence interval in a few lines.
  • Slice by query type. An average that rose 3 points may hide a 15-point regression on acronym queries. Tag each golden example (factual, multi-hop, acronym, negation) and report per slice.
import random

def bootstrap_diff(a: list[float], b: list[float], n: int = 5000) -> tuple[float, float]:
    diffs = [x - y for x, y in zip(a, b)]
    means = sorted(
        statistics.mean(random.choices(diffs, k=len(diffs))) for _ in range(n)
    )
    return means[int(0.025 * n)], means[int(0.975 * n)]

If the interval spans zero, you have not shown an improvement.

Common pitfalls

  • Evaluating on chunks you generated queries from, with the same chunking. When you change chunking, chunk ids change and your labels become invalid. Label against stable source spans (document id plus character range) and map to chunks at eval time.
  • Single relevant chunk assumption. If the answer genuinely appears in three places, marking only one as relevant punishes correct retrievals. Allow multiple relevant ids.
  • Tuning on the golden set until it overfits. Hold out 30% you only look at before a release.
  • Ignoring latency and cost. A reranker that adds 8 points of Hit@5 but 400 ms p95 may not be worth it. Report both.
  • Stale labels. The corpus changes. Re-run chunk-id validation in CI and fail if golden ids no longer exist.
  • Never testing "no answer" queries. Include queries the corpus cannot answer. Measure whether your system retrieves confidently irrelevant chunks, which feeds hallucination.

A checklist you can apply tomorrow

  1. Export 100+ real queries from logs; label relevant chunks.
  2. Add synthetic queries to reach 150โ€“200; read a sample.
  3. Tag each query with a type for slicing.
  4. Write the harness so a retriever is a function (query, k) -> ids.
  5. Record Hit@k, MRR, nDCG@k, Recall@50, and latency for every config.
  6. Gate changes in CI: no merge if Hit@k drops beyond the bootstrap interval.
  7. Only then move to LLM-judged answer evals, knowing retrieval is sound.

Library support exists if you'd rather not hand-roll metrics (for example ranx, pytrec_eval, or the retrieval evaluators in RAGAS and LlamaIndex), but the hand-rolled version above is ~30 lines and makes the definitions explicit. Check each library's docs for how it defines relevance and ties.

Next steps

Once retrieval is measured, improvements become experiments instead of opinions: try hybrid search, add a reranker, tune chunk size, and let the numbers decide. If you want to build this end to end with feedback from instructors and peers, our hands-on AI Engineering cohort covers RAG evaluation as a core module. Product managers defining quality bars for these systems may prefer the PM cohort.

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.