Contents
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?
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.
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.
Flow · 5 stepsFrom question to cited answer
- Rewrite Rewrite the follow-up into a standalone question using the chat history.
- Retrieve Run BM25 and dense bi-encoder retrieval side by side.
- Fuse Fuse the two lists with reciprocal rank fusion.
- Rerank Rerank the fused candidates with a cross-encoder.
- Generate Generate an answer that cites its sources or abstains.
Data
| Step | Title | What happens | Runs when |
|---|---|---|---|
| 1 | Rewrite | Rewrite the follow-up into a standalone question using the chat history. | always |
| 2 | Retrieve | Run BM25 and dense bi-encoder retrieval side by side. | always |
| 3 | Fuse | Fuse the two lists with reciprocal rank fusion. | always |
| 4 | Rerank | Rerank the fused candidates with a cross-encoder. | Cross-encoder reranker on |
| 5 | Generate | Generate an answer that cites its sources or abstains. | always |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| User question | Input | follow-up or standalone |
| Query rewrite | Input | standalone question |
| BM25 | Retrieval | term matches, IDF |
| Dense bi-encoder | Retrieval | paraphrase |
| Reciprocal rank fusion | Ranking | k = 60 |
| Cross-encoder reranker | Ranking | tens to low hundreds |
| Grounded generation | Generation | cites sources or abstains |
| Cited answer | Generation | or abstention |
Source: This page's text
| Switch | What it changes | Starts |
|---|---|---|
| Cross-encoder reranker | The reranker is on by default; switch it off to send fused candidates straight to generation. | on |
Source: This page's text
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).
- 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.
CalculatorMemory of a vector index
- Raw vectors
- 409.6 GB
- HNSW links
- 25.6 GB
- PQ, 64 B/vector
- 6.4 GB
- Raw + HNSW
- 435.2 GB
Raw vectors = Chunks × Dimensions × Bytes per value ÷ 1000 = 409.6 GB
HNSW links = Chunks × 2 × HNSW M × 4 ÷ 1000 = 25.6 GB
PQ, 64 B/vector = Chunks × 64 ÷ 1000 = 6.4 GB
Raw + HNSW = Raw vectors + HNSW links = 435.2 GB
| Case | Chunks (million) | Dimensions | Bytes per value (B) | HNSW M | Raw vectors | HNSW links | PQ, 64 B/vector | Raw + HNSW |
|---|---|---|---|---|---|---|---|---|
| float32 raw + HNSW | 100 | 1,024 | 4 | 32 | 409.6 GB | 25.6 GB | 6.4 GB | 435.2 GB |
| int8 | 100 | 1,024 | 1 | 32 | 102.4 GB | 25.6 GB | 6.4 GB | 128 GB |
| float16 at 256 dims | 100 | 256 | 2 | 32 | 51.2 GB | 25.6 GB | 6.4 GB | 76.8 GB |
What changed recently
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.
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.
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.
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.
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.
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?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
A product team wants the assistant to “know” 20,000 internal policy documents. How do you choose between prompting, retrieval, long-context stuffing and fine-tuning — and when would you not use retrieval at all?
Model answer, written in a candidate's voice
- Start with requirements: corpus size/churn, citations, access control, latency/cost, error tolerance
- Prompting is the baseline; long context only for small bounded corpora that fit budget
- Retrieval for large, changing, permissioned knowledge that needs citations and freshness
- Fine-tuning changes behaviour/format/tone/latency, not a reliable way to inject facts
- Do not use retrieval when no external knowledge is needed, corpus is tiny/static, data is structured for SQL/tools, or retrieval quality cannot be made good enough
- Combine approaches: tuned retriever/reranker plus generator trained to use context
- Build and run an eval before choosing, then revisit as corpus and traffic change
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?
Model answer, written in a candidate's voice
- Split by structure: headings/sections for PDFs and wikis, functions/classes for code, turns/threads for chat; keep tables intact or render as text with repeated headers.
- Small chunks retrieve precisely but lose context; large chunks add context but dilute embeddings and cost tokens; overlap protects boundaries but duplicates storage.
- Attach metadata (title, section path, date, ACL, URL) and prepend document/section context before embedding.
- Use parent-child retrieval: match small units, return the enclosing section/parent.
- Tune chunk size and overlap empirically on a labelled query set using recall@k and downstream answer quality.
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?
Model answer, written in a candidate's voice
- Dense embeddings are weak on rare tokens and exact strings; lexical search (BM25) is strong there
- Fusion with reciprocal rank fusion (Σ 1/(k + rank)) or normalised weighted scores, tuned on an eval set
- Query understanding: detect identifiers and route to exact match or metadata filters
- Rerank after fusion; report recall@k per query segment (identifier-heavy vs semantic)
- Operational cost: two indexes to keep consistent; latency budget
You have finished this topic.
Reading
- Introducing Contextual RetrievalA practical pipeline (contextual chunks, BM25, reranking) with measured failure-rate reductions.
- Retrieval-Augmented Generation for Knowledge-Intensive NLP TasksThe paper that named RAG; useful for the original retriever–generator framing.
- Dense Passage Retrieval for Open-Domain Question AnsweringHow 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 ModelsEvidence that BM25 is a robust out-of-domain baseline and rerankers are strong but costly.
- Effective context engineering for AI agentsFrames retrieval as context curation: just-in-time tool retrieval versus pre-computed embeddings, compaction and sub-agents.
- On the Theoretical Limitations of Embedding-Based RetrievalProves 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 BERTLate interaction as the middle ground between bi-encoders and cross-encoders.
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphsThe 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 fine-tuning — and when would you not use retrieval at all?
- 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?
- 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?
- 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 decide?
- 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?
- 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?
- Design retrieval for an enterprise assistant where documents carry per-user and per-group permissions that change daily. Where can data leak?
- 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 database?
- 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?
- Users show answers citing real documents that don’t say what the answer claims. Diagnose.
- 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 would you watch for?
- How are text-embedding models trained, and which decisions matter when you use them for search — similarity metric, normalisation, dimensionality, domain shift and multilingual content?
- How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?
- 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 chunk-and-embed get wrong, and what would you build instead?
- 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 review a messy pull request to the same service and give feedback.
- 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 lists. Then discuss complexity and scaling.
- 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 single-needle versus multi-needle retrieval at 1M tokens, how would you make the call and what would you measure?
- Design an agentic RAG system for enterprise questions that span several corpora (HR policy, contracts, ticket history). How does the agent decide it has retrieved enough, how do you bound cost and latency, and how do you evaluate it against a single-pass RAG baseline?
- 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 ColPali-style vision-language retriever: quality, index size, latency and how you would evaluate the choice.
- 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 LIMIT experiments showed for dense models, BM25, multi-vector models and rerankers, and what you would change in a production retrieval stack because of it.