---
title: Retrieval-augmented generation
url: https://gurkanozkan.ai/learn/topics/rag/
markdown: https://gurkanozkan.ai/learn/topics/rag.md
kind: topic
tracks:
  - Applied LLM
  - Research
  - ML engineering
json: https://gurkanozkan.ai/api/learn/topics/rag.json
---

# Retrieval-augmented generation

RAG grounds a model's answer in documents fetched at query time: parse and chunk the corpus, index it lexically and with embeddings, retrieve candidates, rerank them, and generate an answer that cites its sources or abstains. It is the most common applied LLM system design question in London interviews because it touches information retrieval, evaluation, latency budgets, permissions, freshness and data protection. Interviewers expect you to separate retrieval failures from generation failures with metrics, to know when hybrid search and reranking pay off, and to reason about index memory at scale. Since 2025 the question has widened to agentic retrieval and context engineering: reasoning models that decide when and what to search, and systems that keep the context small and relevant even when million-token windows are available.

## Key concepts

### When RAG, and when not

Use RAG for knowledge that is large, changing, permissioned or must be cited. Prompting alone suits small static context; long-context stuffing suits bounded one-off analyses; fine-tuning changes behaviour and format but is a poor way to add facts that change. Aggregate or numeric questions over tables ('which suppliers had more than three incidents') need structured extraction plus SQL, not top-k chunks. Million-token windows (Claude Opus 4.6 in beta from February 2026, for example) widen the long-context option but do not remove the case for selection: Chroma's 2025 'context rot' study of 18 models found accuracy falling as input grew even on trivial tasks, and every model family did better on focused prompts of about 300 tokens than on full prompts of about 113k tokens.

### Parsing and chunking

Most quality problems start at ingestion: tables flattened into nonsense, headers lost, scanned PDFs without OCR. Chunk along structure (sections, headings, messages, functions) with a size that fits the question type, typically a few hundred tokens with modest overlap, and attach metadata (title, section path, date, permissions). Contextual chunk headers or LLM-written chunk context help: Anthropic reported top-20 retrieval failures falling from 5.7% to 2.9% with contextual embeddings plus contextual BM25. For visually rich PDFs (slides, charts, forms), embedding page images with a vision-language retriever is now a real alternative to OCR and chunking: the ViDoRe V3 benchmark (2026) found visual retrievers ahead of text-only ones, and visual or hybrid page context improved generated answers.

### Lexical, dense and hybrid retrieval

BM25 scores term matches with IDF weighting, saturating term frequency (k1 ≈ 1.2–2) and length normalisation (b ≈ 0.75); it excels on rare tokens, codes, IDs and names. Dense bi-encoders embed queries and passages separately and capture paraphrase but blur exact strings. BEIR showed BM25 is a strong zero-shot baseline that many dense models fail to beat out of domain. Hybrid search runs both and fuses the lists, usually with reciprocal rank fusion.

### Reciprocal rank fusion

RRF scores each document by Σ 1 / (k + rankᵢ) over the lists it appears in, with k = 60 the usual default (Elasticsearch's default too). It needs no score normalisation and rewards documents that several retrievers agree on. Weighted score fusion can do better when scores are calibrated, but needs tuning on an eval set.

### Bi-encoders, cross-encoders and late interaction

Bi-encoders allow precomputed document vectors and ANN search over millions of items. Cross-encoders read query and passage together and score far more accurately but cost one forward pass per pair, so they rerank tens to low hundreds of candidates. ColBERT-style late interaction keeps per-token vectors and sums max similarities: better than a single vector, cheaper than a cross-encoder, but heavier to store; ColPali-style models apply late interaction to multi-vector embeddings of page images. Google DeepMind's LIMIT paper (ICLR 2026) proved that embedding dimension bounds which top-k sets a single vector can return: on its simple queries the best single-vector models stayed under 20% recall@100, a ColBERT model reached about 55% and a long-context reranker solved the small version outright.

### Approximate nearest neighbour indexes

HNSW builds a layered proximity graph: excellent recall and latency, but memory-hungry and slower to build; tune M, efConstruction and efSearch. IVF partitions vectors into clusters and probes a few; combined with product quantisation it compresses vectors to tens of bytes at some recall cost, usually recovered by reranking with full vectors. Flat search is exact and fine up to about a million vectors or for small filtered subsets.

### Query understanding, conversational and agentic retrieval

Follow-ups like 'and for contractors?' fail because the query lacks context: rewrite it into a standalone question using the chat history, generate multiple query variants, route identifiers to exact match or metadata filters, or use HyDE (embed a hypothetical answer). Each rewrite adds latency and its own failure modes, so measure retrieval on rewritten versus raw queries. Agentic retrieval hands these decisions to a reasoning model that calls search as a tool, decomposes the question, searches again and checks whether the evidence suffices before answering (Search-R1 learns this with RL; coding agents such as Claude Code fetch files just in time with grep and glob). It helps multi-hop questions at the cost of more calls, higher and more variable latency, and harder evaluation.

### Evaluation, attribution and operations

Build a labelled set from real queries with gold passages and reference answers, including unanswerable ones; score retrieval with recall@k, MRR and nDCG, and generation with faithfulness, correctness, citation accuracy and correct abstention, judged by humans plus validated LLM judges. If the gold passage was not retrieved, it is a retrieval failure; if it was and the answer is wrong, it is generation; confirm with an oracle-context ablation. For agentic search, score end to end on questions that are hard to find but easy to verify (OpenAI's BrowseComp: GPT-4o with browsing 1.9%, Deep Research 51.5%) and track calls, tokens and latency per answered question. In production, filter by permissions at retrieval time, propagate deletes to every index and cache, and run embedding-model upgrades as a parallel index with cut-over.

## Worked examples

### Retrieval metrics on a small eval set

Five queries each have one gold passage. The rank of the gold passage in the retrieved top 10 is: q1 → 1, q2 → 3, q3 → not retrieved, q4 → 2, q5 → 7. Compute hit rate (recall) at 5 and at 10, MRR@10 and nDCG@10. You pass the top 5 to the LLM; what do the numbers tell you?

**Solution**

**Recall@5** (one gold each, so recall = hit rate): q1, q2, q4 → 3/5 = **0.60**
**Recall@10**: q1, q2, q4, q5 → 4/5 = **0.80**

**MRR@10** = mean of 1/rank (0 if missing):
(1 + 1/3 + 0 + 1/2 + 1/7) / 5 = (1 + 0.333 + 0 + 0.5 + 0.143) / 5 = **0.395**

**nDCG@10** with one relevant passage: DCG = 1 / log₂(rank + 1), ideal DCG = 1.
- q1: 1.000; q2: 1/log₂4 = 0.500; q3: 0; q4: 1/log₂3 = 0.631; q5: 1/log₂8 = 0.333
- mean = 2.464 / 5 = **0.493**

Reading: q5's gold sits at rank 7, retrieved but never shown to the LLM, so a reranker could add
up to 20 points of recall@5 at no extra retrieval cost. q3 is a pure retrieval miss: inspect it
(an identifier? a paraphrase? a parsing problem?) before tuning anything. Report these per query
segment, not only on average.


### Fusing BM25 and dense results with RRF

BM25 returns [D7, D2, D9, D4] and the dense retriever returns [D2, D5, D7, D1]. Fuse with RRF, k = 60.

**Solution**

Score = Σ 1 / (60 + rank)

| doc | BM25 rank | dense rank | score |
|---|---|---|---|
| D2 | 2 | 1 | 1/62 + 1/61 = 0.01613 + 0.01639 = **0.03252** |
| D7 | 1 | 3 | 1/61 + 1/63 = 0.01639 + 0.01587 = **0.03227** |
| D5 | — | 2 | 1/62 = 0.01613 |
| D9 | 3 | — | 1/63 = 0.01587 |
| D4 | 4 | — | 1/64 = 0.01563 |
| D1 | — | 4 | 1/64 = 0.01563 |

Fused order: **D2, D7, D5, D9, D4/D1**. Documents found by both retrievers rise to the top.
Larger k flattens differences between ranks; smaller k (say 1) makes the top rank dominate:
with k = 1, D2 scores 1/3 + 1/2 = 0.833 and D7 1/2 + 1/4 = 0.75. Tune k, or switch to weighted
fusion, against recall@k on your own eval set, sliced into identifier-heavy and semantic queries.


### Memory for 100 million chunks

You must index 100 million chunks with 1,024-dimensional embeddings. Estimate memory for raw float32 vectors, an HNSW graph with M = 32, int8 scalar quantisation, product quantisation to 64 bytes per vector, and float16 vectors truncated to 256 dimensions (a Matryoshka-trained model).

**Solution**

- **float32 raw**: 100M × 1,024 × 4 B = **409.6 GB**
- **HNSW links**: the base layer stores up to 2M = 64 neighbour IDs × 4 B = 256 B per vector
  → 100M × 256 B ≈ **25.6 GB** extra (upper layers add little)
- **int8**: 100M × 1,024 × 1 B = **102.4 GB**
- **PQ, 64 B/vector**: 100M × 64 B = **6.4 GB**
- **float16 at 256 dims**: 100M × 256 × 2 B = **51.2 GB**

Design choice: an IVF-PQ index (about 6.4 GB in memory) for the first pass, then rerank the top few
hundred candidates with full-precision vectors read from SSD, keeps recall near flat search. Pure
HNSW on float32 needs over 435 GB of RAM across shards. If you already run Postgres or Elasticsearch
and the corpus is a few million chunks, pgvector or the engine's vector support avoids a new system.


## What changed recently

- **Jun 2026: Multi-agent RAG with a sufficient-context check.** Google Research and Google Cloud described an agentic RAG framework in which planner, query-rewriter, search and synthesis agents are joined by a 'sufficient context' agent that inspects the snippets and a draft answer, names what is missing and triggers another search round. Google reports up to 34% higher accuracy than standard RAG on factuality datasets and 90.1% on FramesQA when the planner chooses among four corpora. Interviewers now ask how you decide that retrieval is done, and what the extra loop costs. [Source](https://research.google/blog/unlocking-dependable-responses-with-gemini-enterprise-agent-platforms-agentic-rag/)
- **Jan 2026: ViDoRe V3 benchmarks RAG over visually rich enterprise documents.** ViDoRe V3 covers about 26,000 pages and 3,099 human-verified queries in six languages, with labels for retrieval, bounding-box grounding and reference answers. It found visual retrievers ahead of text-only ones, late interaction and reranking giving large gains, and fine-grained visual grounding still weak. It is the reference point when an interviewer asks whether to OCR and chunk PDFs or retrieve page images. [Source](https://arxiv.org/abs/2601.08620)
- **Sep 2025: Context engineering and just-in-time retrieval.** Anthropic's engineering post recast prompt and retrieval design as curating the smallest set of high-signal tokens, contrasting embedding-based retrieval before inference with agents that keep light references and load data with tools at run time, as Claude Code does with grep and glob. Expect to be asked when a hybrid of up-front retrieval and agentic exploration beats a classic vector pipeline. [Source](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents)
- **Aug 2025: LIMIT: a theoretical ceiling for single-vector embeddings.** Google DeepMind proved that the embedding dimension bounds how many distinct top-k document sets a single vector can return, and built the LIMIT dataset on which leading embedders stay under 20% recall@100 while BM25 (about 94%), a multi-vector model (about 55%) and a long-context reranker do far better. The paper, accepted at ICLR 2026, is now a standard prompt for discussing hybrid retrieval, late interaction and reranking. [Source](https://arxiv.org/abs/2508.21038)
- **Mar 2025: Search-R1 trains models to search with reinforcement learning.** Search-R1 teaches an LLM to issue its own search queries mid-reasoning, trained only with RL on an outcome reward and with retrieved tokens masked out of the loss; it reported 41% (Qwen2.5-7B) and 20% (Qwen2.5-3B) relative gains over RAG baselines on seven QA datasets. It marks the shift from fixed retrieve-then-read pipelines to retrieval as a learned tool inside reasoning models. [Source](https://arxiv.org/abs/2503.09516)

## Pitfalls

- Tuning prompts when the gold passage was never retrieved; always split retrieval from generation errors.
- Dense-only retrieval for corpora full of product codes, error IDs and names, or for queries whose relevant set a single vector cannot represent (the LIMIT result).
- One chunk size for every document type, and chunking that drops table structure and headings.
- Applying document permissions after generation, or caching answers across users with different access.
- Evaluating only answerable questions, so the system is never tested on when to say 'I don't know'.
- Re-embedding the corpus in place on a model upgrade instead of building a parallel index and cutting over.

## How interviewers probe it

- Design an assistant over 20,000 policy documents; justify RAG versus a 1M-token context, an agentic search loop and fine-tuning, and say how you would bound the loop's cost.
- Dense retrieval misses identifiers; what do you change and how do you merge result lists?
- With a 1.5 s budget, how many candidates do you retrieve and rerank, and how do you decide?
- Evaluate end to end and attribute a bad answer to retrieval or generation.
- Per-user permissions that change daily, and UK GDPR erasure across indexes, caches and logs.
- Choose between HNSW, IVF-PQ and flat search at 100M vectors; when is Postgres enough?

## Reading

- [Introducing Contextual Retrieval](https://www.anthropic.com/news/contextual-retrieval) (Blog, 20 min, Intro): A practical pipeline (contextual chunks, BM25, reranking) with measured failure-rate reductions.
- [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) (Paper, 45 min, Core): The paper that named RAG; useful for the original retriever–generator framing.
- [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906) (Paper, 40 min, Core): How bi-encoder retrievers are trained with in-batch negatives and how they compare with BM25.
- [BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models](https://arxiv.org/abs/2104.08663) (Paper, 40 min, Core): Evidence that BM25 is a robust out-of-domain baseline and rerankers are strong but costly.
- [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) (Blog, 25 min, Core): Frames retrieval as context curation: just-in-time tool retrieval versus pre-computed embeddings, compaction and sub-agents.
- [On the Theoretical Limitations of Embedding-Based Retrieval](https://arxiv.org/abs/2508.21038) (Paper, 40 min, Deep): Proves a dimension-bound ceiling for single-vector retrieval and shows where BM25, multi-vector and rerankers win.
- [ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT](https://arxiv.org/abs/2004.12832) (Paper, 45 min, Deep): Late interaction as the middle ground between bi-encoders and cross-encoders.
- [Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs](https://arxiv.org/abs/1603.09320) (Paper, 50 min, Deep): The HNSW algorithm and its parameters, which most vector databases expose.

## Practise this topic

- [A product team wants the assistant to "know" 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and…](https://gurkanozkan.ai/learn/questions/applied-llm-rag-01.md)
- [How would you chunk a mixed corpus of policy PDFs with tables, wiki pages, chat threads and code? What do you trade off when picking chunk size and overlap?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-02.md)
- [Dense-only retrieval misses queries that contain product codes, error IDs and people's names. What would you change, and how would you merge result lists?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-03.md)
- [Explain bi-encoders versus cross-encoder rerankers. With a 1.5-second end-to-end budget, how many candidates would you retrieve and rerank, and how would you…](https://gurkanozkan.ai/learn/questions/applied-llm-rag-04.md)
- [How would you evaluate a retrieval-augmented assistant end to end, and how would you tell whether a bad answer came from retrieval or from generation?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-05.md)
- [In a multi-turn chat the user asks "and what about for contractors?" and retrieval returns nothing useful. What techniques fix this, and what do they cost?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-06.md)
- [Design retrieval for an enterprise assistant where documents carry per-user and per-group permissions that change daily. Where can data leak?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-07.md)
- [Compare HNSW, IVF-PQ and flat search for 100 million chunks. When would you use Postgres or a search engine you already run instead of a dedicated vector…](https://gurkanozkan.ai/learn/questions/applied-llm-rag-09.md)
- [Legal users require every claim to cite a source passage, and the system must say it doesn't know when the corpus is silent. How do you build and verify that?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-10.md)
- [Users show answers citing real documents that don't say what the answer claims. Diagnose.](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-05.md)
- [Models now accept hundreds of thousands of tokens. When would you put everything in the context window instead of building retrieval, and what failure modes…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-11.md)
- [How are text-embedding models trained, and which decisions matter when you use them for search — similarity metric, normalisation, dimensionality, domain shift…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-12.md)
- [How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?](https://gurkanozkan.ai/learn/questions/applied-llm-rag-08.md)
- [The corpus is scanned PDFs with tables, and users ask aggregate questions such as which suppliers had more than three incidents last year. What does plain…](https://gurkanozkan.ai/learn/questions/applied-llm-rag-11.md)
- [You get a small RAG-service repository with failing tests and a bug report saying answers ignore the newest documents. Find and fix it while narrating — or…](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-09.md)
- [Without a vector database, implement top-k retrieval: cosine similarity over an embedding matrix, a simple BM25 scorer, and reciprocal rank fusion of the two…](https://gurkanozkan.ai/learn/questions/applied-llm-cod-03.md)
- [A vendor advertises a 1M-token window and your team wants to drop retrieval for a 600k-token contract corpus. Using what GPT-4.1 and DeepSeek-V4 report about…](https://gurkanozkan.ai/learn/questions/recent-b-long-context-01.md)
- [Design an agentic RAG system for enterprise questions that span several corpora (HR policy, contracts, ticket history). How does the agent decide it has…](https://gurkanozkan.ai/learn/questions/recent-b-rag-02.md)
- [Your corpus is 2 million pages of scanned reports full of charts and tables. Compare an OCR-and-chunk text pipeline with retrieving page images using a…](https://gurkanozkan.ai/learn/questions/recent-b-rag-03.md)
- [A 2025 Google DeepMind paper (LIMIT) argues that single-vector embedding retrieval has a ceiling set by the embedding dimension. Explain the claim, what the…](https://gurkanozkan.ai/learn/questions/recent-b-rag-01.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
