# How Do You Pick Top-K in RAG?

> How many chunks a RAG system should pass to the model, how to test that number, and the trade-off behind top-k, explained for your AI interview.

**In short:** In RAG (retrieval-augmented generation), top-k is how many retrieved chunks the system pastes into the prompt for one question. Pick it by measuring: search wide, rerank, then take the smallest k that finds the right text in your own test questions.

AI and LLM interview question Q146, Retrieval-augmented generation (RAG). Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-pick-top-k

## Say it in 30 seconds

Top-k is how many chunks my RAG system hands to the model for each question. Too few and it misses the clause that answers the question. Too many and the right text gets buried and costs more. So I measure it. I search wide, rerank for the question, then test on a labelled set of real questions and keep the smallest k that finds the right text. Then I read the answers too.

## Say it in 2 minutes

Retrieval-augmented generation, or RAG, means the system searches your documents first and pastes the best pieces into the prompt. Top-k is how many pieces it keeps. It looks like one number in a tutorial, but it is a trade-off, so I treat it as a measured choice.

Too few and the answer is never in the prompt. On a bank's fee assistant, a clause about late-fee waivers was ranked ninth, so a k of three left it out and the model guessed. Too many and the prompt fills with near-misses. Research on long inputs found that models often do best with text at the start or end, and that accuracy drops in the middle. Each extra chunk also adds tokens, cost and time.

So I search wide, about 50 candidates, rerank them for this exact question, and keep a few. Then I build a test set of real questions, each marked with the chunks that hold its answer. I measure how often those chunks land inside the top k, and I take the smallest k that reaches my target. Anthropic's own tests found 20 chunks did best among 5, 10 and 20, but that was their data, so I test mine.

Vector search in Azure returns k results whenever at least k documents exist, even when the matches are weak, so I add a score cut-off and a no-answer path. Finally I check the answers, because a chunk can be found and still ignored, and I run the test again whenever the documents change.

## What is top-k, in plain words?

In RAG (retrieval-augmented generation), the system searches your documents for pieces of text that might answer a question, then pastes the best pieces into the prompt before the model writes. Top-k is how many pieces it pastes. With k = 5, the model reads five chunks.

Don't mix it up with top-k sampling. That is a setting that limits which words a model may pick while it writes. Same name, different knob.

Picture a claims adjuster at an insurer. She pulls the policy clauses that might apply from a binder. Pull too few and she misses the exclusion that kills the claim. Pull too many and the key line gets lost among pages that don't matter. A bank's fee assistant faces the same choice with 40,000 pages of fee schedules, and top-k is that choice for the model.

- **Chunk:** A piece of a document, small enough to paste into a prompt.
- **Top-k:** How many chunks the search keeps for one question. You choose k.
- **Recall:** The share of the needed chunks that made it into the top k.
- **Reranker:** A second model that scores the candidates again, for this exact question.
- **Context window:** How much text a model can read in one go.

## Why is k a trade-off?

A bigger k finds more of the right text, but it brings more noise and more cost. Three things push back on a big k:

- **Noise:** More chunks means more near-misses for the model to weigh, and a wrong one can win.
- **Position:** Models often do best with text at the start or end of a long input, and worse in the middle.
- **Cost and time:** Every chunk is paid for in tokens, the small pieces of text a model counts and charges for, and each extra token adds time to the reply.

> "Adding more chunks into the context window increases the chances that you include the relevant information. However, more information can be distracting for models so there's a limit to this." (Anthropic)
>
> "performance is often highest when relevant information occurs at the beginning or end of the input context, and significantly degrades when models must access relevant information in the middle of long contexts" (Liu and colleagues, Lost in the Middle (2023))
>
> "Vector queries always return k results, assuming at least k documents exist, even if some documents have poor similarity." (Microsoft Azure AI Search)

*Diagram, Too few chunks or too many: Too few and the fact never reaches the model. Too many and it gets buried or costs more. Testing tells the two apart, and the smallest k that passes is the answer.*
1. Too few chunks, and the right one is left out.
2. Too many chunks, and the right one gets buried.
3. A missed fact shows up in the recall test.
4. Muddled answers show up when you check the answers.

Anthropic tested 5, 10 and 20 chunks, and 20 came out best of the three. That is one team's result. Your documents decide.

## How do you find the right k?

Use a funnel: search wide, rerank for the question, keep a few, then test.

1. **Search wide:** Fetch about 50 candidates by vector search, which finds text by meaning, using numbers that stand for the words. Azure's docs say to set k to 50 when vector search feeds its semantic ranker, a second scorer that re-scores only the top 50 results.
2. **Rerank for this question:** A reranker scores each candidate against the question. Anthropic's test pipeline took the top 150 candidates and kept 20, a bigger funnel than the 50 above.
3. **Measure on real questions:** Write a labelled set of real questions, each marked with the chunks that hold its answer. Recall at k is the share of those chunks found in the top k. Pick the smallest k that reaches your target.
4. **Check the answers too:** A chunk can be found and still ignored by the model. So read the final answers, not only the search scores. Anthropic's advice is to test settings on your own use case.

*Diagram, Search wide, then keep a few: Search pulls 50 candidates, the reranker sorts them for this question, and only the top k reach the model. The numbers are a starting point; your test set picks the final k.*
1. Search hands its 50 best guesses to the reranker.
2. The reranker scores them again for this exact question.
3. Only the top k are pasted into the prompt.

## What does a k sweep look like?

Here is a small made-up test of the kind a team runs before it ships. Eight questions from a bank's fee assistant, each with the rank where the reranker put its needed chunks. Each chunk counts as 350 tokens. We try four values of k and keep the smallest one that reaches 95 percent recall.

```python
# Made-up test set for a bank's fee assistant: 8 questions. Each list holds the rank (1 = best)
# where the reranker put each chunk that answers the question.
RANKS = {
    "Overseas card fee?": [2],
    "Late fee waiver?": [4, 9],
    "Dispute window?": [7],
    "Joint account owner?": [1, 3],
    "Card replacement cost?": [6],
    "Closed account refund?": [5],
    "Wire cut-off time?": [8],
    "Lost card liability?": [3, 12],
}
CHUNK_TOKENS = 350  # made-up size of one chunk

def recall_at(k):
    # Share of the needed chunks found in the top k, averaged over the questions.
    found = [sum(r <= k for r in ranks) / len(ranks) for ranks in RANKS.values()]
    return sum(found) / len(found)

print(f"{'k':<4}{'recall':>8}{'tokens':>9}")
for k in (3, 5, 10, 20):
    print(f"{k:<4}{recall_at(k):>8.0%}{k * CHUNK_TOKENS:>9}")
chosen = min(k for k in (3, 5, 10, 20) if recall_at(k) >= 0.95)
print(f"Smallest k at 95 percent recall: {chosen}")
```

Output:

```text
k     recall   tokens
3        31%     1050
5        50%     1750
10       94%     3500
20      100%     7000
Smallest k at 95 percent recall: 20
```

k = 10 found 94 percent on average across the eight questions. The one it missed was the second chunk for the lost-card answer, ranked 12th. k = 20 found all of them, at about 7,000 tokens a question instead of 3,500. The team keeps 20, then reads the answers before it ships.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Top-k is the number of chunks kept for the prompt, and you choose it.
- [ ] Search wide, rerank for the question, then cut down to k.
- [ ] Measure recall at k on real labelled questions, and take the smallest k that passes.
- [ ] Too few misses facts; too many buries them and adds cost and delay.
- [ ] Vector search returns k results even when the matches are weak, so add a score cut-off or a no-answer path.
- [ ] Re-test when the documents or the embedding model (the part that turns text into numbers) change.

**Common traps**

- Trap: "Use 5, it is the standard." Better: No single k fits every system. Measure it on your own questions and keep the smallest k that passes.
- Trap: "Just use the biggest k the model can read." Better: A bigger window does not mean better answers. Models lose accuracy in the middle, and cost rises.
- Trap: "Top-k and top-k sampling are the same thing." Better: Same name, different knobs. One picks chunks for retrieval; the other limits words while the model writes.

## Can you spot the risky setting?

**Spot the risky setting:** Which tuning note would you flag in review?

A. Recall at k = 10 is 96 percent on 200 labelled questions, and we read 20 final answers before shipping.
B. We set k to 40 because the model's context window can hold 40 chunks.
C. We fetch 50 candidates, rerank them, and keep the top 6, after a recall test on 200 labelled questions showed 6 reached 95 percent.
D. We re-run the test set whenever the documents change.

**Answer:** B. Fitting 40 chunks in the window does not make them useful. More chunks add noise, and accuracy drops for text in the middle. The fix is a measured k, not the largest one that fits.

**Quick check:** Your fee bot misses clauses at k = 5. What do you do first?

A. Raise k to the largest number the model can read.
B. Search wide, rerank, and measure recall at several k values on labelled questions.
C. Switch to a bigger model.
D. Lower the randomness setting.

**Answer:** B. Recall shows whether the right chunks get in at each k. A bigger model or less randomness does not change which chunks the search finds.

## Can you answer these from memory?

**Flash cards**

- **What is top-k in RAG?** How many retrieved chunks are pasted into the prompt for one question.
- **Why not always use a big k?** More noise, weaker use of the middle, and more tokens and time per reply.
- **How do you pick k?** Search wide, rerank, measure recall on labelled questions, take the smallest k that passes.
- **What does recall at k measure?** The share of needed chunks that appear in the top k results.
- **Does Azure vector search return fewer than k?** No, if at least k documents exist. It returns k results even when the matches are weak, so add a cut-off.
- **Is top-k sampling the same thing?** No. Top-k sampling limits the words a model picks while it writes. Top-k in RAG picks the chunks.

## Likely follow-up questions

- Q113 What is chunking, and why does size matter? https://designervenkat.online/interview/ai/what-is-chunking-in-rag
- Q123 What is hybrid search (BM25 + vectors)? https://designervenkat.online/interview/ai/what-is-hybrid-search
- Q141 What is contextual retrieval? (full answer coming)
- Q151 "The answer was in the docs, but the bot missed it." How do you debug? https://designervenkat.online/interview/ai/debug-a-rag-bot-that-missed-the-answer
- Q150 How would you design RAG for 10 million documents? https://designervenkat.online/interview/ai/how-would-you-design-rag-for-10-million-documents
