LearnTopic guide

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.

Applied LLM · Research · ML engineering8 key concepts20 questions

Start: Key concepts 6 lessons · about 18 min
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.

Next: Worked examples Lesson 3 of 6 · about 4 min

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

From question to cited answerThe flow runs left to right: a user question is rewritten into a standalone question, sent to BM25 and dense retrieval side by side, fused with reciprocal rank fusion, optionally reranked by a cross-encoder, then used for grounded generation that cites sources or abstains. The reranker toggle controls whether fused candidates pass through the cross-encoder or go straight to generation.User questionfollow-up or standaloneQuery rewritestandalone questionBM25term matches, IDFDense bi-encoderparaphraseReciprocal rank fusionk = 60Cross-encoder rerankertens to low hundredsGrounded generationcites sources or abstainsCited answeror abstention12345InputRetrievalRankingGeneration
  1. Rewrite Rewrite the follow-up into a standalone question using the chat history.
  2. Retrieve Run BM25 and dense bi-encoder retrieval side by side.
  3. Fuse Fuse the two lists with reciprocal rank fusion.
  4. Rerank Rerank the fused candidates with a cross-encoder.
  5. Generate Generate an answer that cites its sources or abstains.

A question is rewritten, retrieved by BM25 and dense search, fused, reranked and used to generate a cited answer or an abstention.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happensRuns when
1RewriteRewrite the follow-up into a standalone question using the chat history.always
2RetrieveRun BM25 and dense bi-encoder retrieval side by side.always
3FuseFuse the two lists with reciprocal rank fusion.always
4RerankRerank the fused candidates with a cross-encoder.Cross-encoder reranker on
5GenerateGenerate an answer that cites its sources or abstains.always

Source: This page's text

Boxes
BoxGroupDetail
User questionInputfollow-up or standalone
Query rewriteInputstandalone question
BM25Retrievalterm matches, IDF
Dense bi-encoderRetrievalparaphrase
Reciprocal rank fusionRankingk = 60
Cross-encoder rerankerRankingtens to low hundreds
Grounded generationGenerationcites sources or abstains
Cited answerGenerationor abstention

Source: This page's text

Switches
SwitchWhat it changesStarts
Cross-encoder rerankerThe 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 = Chunks × Dimensions × Bytes per value ÷ 1000

HNSW links = Chunks × 2 × HNSW M × 4 ÷ 1000

PQ, 64 B/vector = Chunks × 64 ÷ 1000

Raw + HNSW = Raw vectors + HNSW links

Worked cases
CaseChunks (million)DimensionsBytes per value (B)HNSW MRaw vectorsHNSW linksPQ, 64 B/vectorRaw + HNSW
float32 raw + HNSW1001,024432409.6 GB25.6 GB6.4 GB435.2 GB
int81001,024132102.4 GB25.6 GB6.4 GB128 GB
float16 at 256 dims10025623251.2 GB25.6 GB6.4 GB76.8 GB
Raw vectors, HNSW links, PQ and the combined float32 + HNSW total for 100 million chunks.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Next: What changed Lesson 4 of 6 · about 3 min

What changed recently

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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?
Next: Quiz Lesson 6 of 6 · about 3 min

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.

  1. Question 1 of 3 · Applied LLM · Technical · Easy

    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?

  2. Question 2 of 3 · Applied LLM · Technical · Easy

    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?

  3. Question 3 of 3 · Applied LLM · Technical · Medium

    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?

Reading

Practise this topic

  1. 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?Applied LLM · Technical · Easy
  2. 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?Applied LLM · Technical · Easy
  3. 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?Applied LLM · Technical · Medium
  4. 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?Applied LLM · Technical · Medium
  5. 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?Applied LLM · Technical · Medium
  6. 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?Applied LLM · Technical · Medium
  7. Design retrieval for an enterprise assistant where documents carry per-user and per-group permissions that change daily. Where can data leak?Applied LLM · Technical · Medium
  8. 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?Applied LLM · Technical · Medium
  9. 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?Applied LLM · Technical · Medium
  10. Users show answers citing real documents that don’t say what the answer claims. Diagnose.Applied LLM · Technical · Medium
  11. 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?Applied LLM · Technical · Medium
  12. 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?Applied LLM · Technical · Easy
  13. How do you keep the index fresh and honour deletions — for example a UK GDPR erasure request — across the vector store, caches and logs?Applied LLM · Technical · Medium
  14. 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?Applied LLM · Technical · Hard
  15. 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.Applied LLM · Coding · Medium
  16. 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.Applied LLM · Coding · Easy
  17. 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?Applied LLM · Technical · Medium
  18. 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?Applied LLM · System design · Hard
  19. 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.ML engineering · Technical · Medium
  20. 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.Research · Technical · Hard

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.