RAG Fundamentals
Retrieval-augmented generation (RAG) answers a question by first searching a body of documents for relevant passages, then giving those passages to an LLM along with the question. The model writes an answer grounded in what was retrieved, ideally with citations. It's the most common pattern in applied LLM systems: support bots over help-center articles, assistants over company wikis, legal research over case files, chat over a user's own PDFs.
RAG exists because LLMs alone have three problems for these tasks. They don't know your private data. Their knowledge stops at a training cutoff. And when they don't know, they often make something up with confidence. Retrieval fixes the first two directly, and it makes the third checkable, because every claim can be traced to a passage. It's also usually cheaper and faster to update than fine-tuning: adding a document to an index takes seconds, while retraining a model takes hours and doesn't reliably teach new facts.
RAG looks simple in a demo and turns out to be hard in production. Most of the difficulty is in retrieval, not generation: if the right passage isn't in the context, the best model in the world can't use it. This post covers the building blocks, in pipeline order:
- The two pipelines: indexing and querying.
- Chunking: how to split documents.
- Embeddings: what they capture and what they miss.
- Hybrid search: combining lexical and vector retrieval.
- Reranking: precision after recall.
- Query transformation and generation with citations.
- Evaluation: measuring retrieval and answers separately.
The full system around these pieces (ingestion at scale, permissions, freshness, multi-tenant indexes) is designed in Design a RAG System.
The Two Pipelines
Every RAG system has an offline indexing pipeline and an online query pipeline:
Indexing, run when documents are added or changed:
- Parse each document into clean text with structure: headings, paragraphs, tables, page numbers. PDFs, slides and HTML each need their own handling, and parsing errors (merged columns, lost tables) are a top cause of bad answers.
- Chunk the text into passages.
- Embed each chunk into a vector, and also index its text for keyword search.
- Store vectors, text and metadata (document ID, title, section, date, permissions) in a search index.
Querying, run per request:
- Transform the question: rewrite it as a standalone query, extract filters.
- Retrieve candidates with keyword and vector search.
- Rerank them with a more accurate model and keep the best few.
- Generate an answer from the question and the top passages, with citations.
Let's size a concrete corpus, since the numbers shape several choices. Take 1 million documents averaging 5 pages, at about 650 tokens per page: 1M × 5 × 650 ≈ 3.25 billion tokens. We'll come back to it.
Chunking
Why Chunk at All?
Three reasons:
- Embedding models have input limits, often 512 tokens for older BERT-style models and up to around 8,000 for newer ones.
- One vector for a long text is a blurry average. A 30-page contract embedded as one vector sits somewhere between all its topics and matches none of them well. Retrieval works best when each unit is about one thing.
- The LLM's context is a budget. We want to give it the five paragraphs that answer the question, not five whole documents.
The tension is that chunks that are too small lose context ("it shall terminate after 30 days": what shall?), while chunks that are too big dilute the embedding and waste the context budget. Common sizes are 200-800 tokens, with some overlap (often 10-20%) so a sentence that straddles a boundary appears whole in at least one chunk.
Strategies
Fixed-size chunking splits every N tokens with overlap. It's simple and predictable, and it ignores structure, so it cuts tables in half and splits sentences mid-way.
Recursive, structure-aware chunking is the practical default. Split on the strongest boundary first (sections), and only split further on weaker boundaries (paragraphs, then sentences) when a piece is still too long:
SEPARATORS = ["\n## ", "\n### ", "\n\n", "\n", ". ", " "]
def chunk(text, max_tokens=512, seps=SEPARATORS):
if count_tokens(text) <= max_tokens or not seps:
return [text]
sep, weaker = seps[0], seps[1:]
out, buf = [], ""
for piece in text.split(sep):
if count_tokens(piece) > max_tokens: # too big alone: split on a weaker boundary
if buf:
out.append(buf)
buf = ""
out.extend(chunk(piece, max_tokens, weaker))
elif not buf or count_tokens(buf + sep + piece) <= max_tokens:
buf = buf + sep + piece if buf else piece # pack small pieces together
else:
out.append(buf)
buf = piece
if buf:
out.append(buf)
return out # add overlap between neighbors afterwards
Content-specific chunking respects what the document is. Keep a table, with its header row, in one chunk (or turn each row into a sentence that repeats the column names). Split code by function or class, not by line count. Split transcripts by speaker turn. Split FAQ pages by question.
Semantic chunking embeds each sentence and starts a new chunk where the similarity between consecutive sentences drops. It can help on unstructured text with no headings, at the cost of embedding every sentence during indexing.
Keep the Context the Chunk Lost
Two techniques recover the context that chunking removes, and both are cheap wins:
- Contextual headers. Prepend the document title and section path to each chunk before embedding and indexing it:
Employee Handbook > Leave > Parental leave: Employees are eligible after 90 days.... Now "how long until I get parental leave" matches, even though the chunk itself never says "parental leave." - Small-to-big retrieval (parent-child chunks). Index small chunks (say, 128-256 tokens) for precise matching, but when one is retrieved, give the LLM its larger parent (the whole section, or the chunk plus its neighbors). Small units retrieve sharply; big units answer completely.
A stronger variant has an LLM write a sentence or two of context for every chunk ("This section of Acme's 2023 MSA covers termination for convenience..."). It helps retrieval noticeably on documents where chunks are ambiguous out of context, but it means an LLM call per chunk at indexing time, so it's worth doing only where the gain justifies the cost (prompt caching of the shared document text makes it much cheaper).
For our corpus: 3.25B tokens in 512-token chunks with 64 tokens of overlap means a new chunk every 448 tokens, so 3.25 × 10^9 ÷ 448 ≈ 7.3 million chunks.
Chunking is the most under-discussed part of RAG in interviews, and one of the most impactful in practice. Say what your chunk size is and why, how you handle tables and headings, and how a retrieved chunk keeps its document context. Those three sentences show you've built one.
Embeddings
What an Embedding Model Does
A text embedding model maps a piece of text to a vector, typically 384 to 3,072 numbers, such that texts with similar meaning land close together. Similarity is measured with cosine similarity or, for normalized vectors, the dot product. For retrieval, these are bi-encoders: the query and each document are embedded independently, which is what makes it possible to embed millions of chunks ahead of time and search them in milliseconds.
They're trained with contrastive learning: pairs of (query, relevant passage) are pulled together, and other passages in the batch, ideally hard negatives that look relevant but aren't, are pushed apart. Many models are trained for asymmetric search and expect a prefix or instruction to say which side is which (some use query: and passage: prefixes). Using the wrong prefix, or none, quietly hurts recall.
Common choices include hosted models (OpenAI's text-embedding-3 family, Cohere, Voyage, Google) and open-weights models (BGE, E5, GTE, Nomic and others). Pick from benchmark leaderboards as a starting point, then evaluate on your own queries, because rankings shift by domain and language.
What Embeddings Miss
Embeddings capture topic and paraphrase well: "how do I get my money back" matches "refund policy." They're weak at:
- Exact identifiers: error codes, SKUs, invoice numbers, function names, section numbers.
E1234andE1243look nearly identical to an embedding model. - Rare names and jargon the model didn't see much in training.
- Negation and small details: "flights that are not refundable" can land right next to "refundable flights."
- Numbers and dates: "contracts signed after 2021" is a filter, not a similarity.
These are exactly the cases where keyword search shines, which is why hybrid search exists.
Practical Details
- Never mix models in one index. Vectors from two different embedding models (or two versions of one) live in different spaces. Changing the model means re-embedding the corpus into a new index and switching over once it's built. Version the index with the model name.
- Storage. 7.3M chunks × 1,024 dimensions × 4 bytes (FP32) ≈ 30 GB. INT8 quantization brings that to ~7.5 GB, and binary (1 bit per dimension, 128 bytes per vector) to under 1 GB, usually with a rescoring step on full-precision vectors to recover accuracy. Some models are trained so a prefix of the vector (say, the first 256 dimensions) still works well (Matryoshka embeddings), trading a little quality for 4× less memory.
- Indexing cost. With overlap, we embed 7.3M × 512 ≈ 3.7B tokens. A ~335M-parameter embedding model costs about 2 × 335M = 0.67 GFLOPs per token, so 3.7 × 10^9 × 0.67 × 10^9 ≈ 2.5 × 10^18 FLOPs. At ~400 TFLOP/s on an H100, that's about 6,200 s, under 2 GPU-hours. Re-embedding is affordable for this corpus, but it's a planned migration, not a hot fix.
- Fine-tuning. For specialized domains (legal, medical, internal jargon), fine-tuning an open embedding model on a few thousand (query, relevant passage) pairs, with hard negatives mined from your own index, often gives a large recall gain.
Vector Search
At millions of vectors, exact nearest-neighbor search (compare the query with every vector) is too slow, so vector indexes use approximate nearest neighbor (ANN) algorithms: HNSW graphs, IVF clustering, and product quantization to compress vectors. They trade a little recall for orders-of-magnitude speed. The details, and the choice between Pinecone, Milvus, Weaviate, Qdrant, pgvector, OpenSearch and others, are in Vector Databases.
One RAG-specific detail matters here: metadata filters. Questions often carry hard constraints, like a document type, a date range, a customer or the user's permissions. If you run ANN search first and filter afterwards (post-filtering), a selective filter can leave you with almost nothing: if only 1% of chunks match and you retrieved the top 100, you expect about one survivor. Indexes that apply the filter during the search (pre-filtering, or filtered HNSW) or partition the index by the filter key (one partition per tenant) avoid this.
Hybrid Search
Lexical Search Still Matters
BM25, the standard keyword ranking function in Elasticsearch, OpenSearch and Lucene, scores a document by how often it contains the query's terms, weighted by how rare each term is across the corpus, with diminishing returns for repeats and a penalty for long documents:
BM25(q, d) = Σ over terms t in q: IDF(t) × tf(t,d) × (k1 + 1) / (tf(t,d) + k1 × (1 − b + b × |d| / avg_len))
with typical defaults k1 ≈ 1.2 and b ≈ 0.75. It needs no training, handles identifiers and rare words perfectly, and is fully explainable. It fails on paraphrase: "can't log in" won't match "authentication failure."
Take the query "error E1234 when exporting invoices." Vector search returns passages about export errors in general. BM25 returns the one troubleshooting article that mentions E1234. Now take "why can't customers download their bills?" BM25 struggles, because the article says "export invoices," while vector search finds it. Real query traffic has both kinds, and you can't tell them apart reliably in advance. So run both.
Fusing the Results
The two retrievers produce scores on incomparable scales: BM25 scores are unbounded and corpus-dependent, while cosine similarities sit in a narrow band. Adding them directly lets one dominate. The simple, robust fix is Reciprocal Rank Fusion (RRF), which uses only ranks:
def rrf(result_lists, k=60):
"""result_lists: ranked lists of chunk IDs, one per retriever."""
scores = {}
for results in result_lists:
for rank, chunk_id in enumerate(results, start=1):
scores[chunk_id] = scores.get(chunk_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
fused = rrf([bm25_top100, vector_top100])
A chunk ranked highly by both retrievers wins; a chunk ranked first by one and absent from the other still scores well. The constant k = 60 softens the advantage of the very top ranks and is a common default. The alternative, weighted score fusion (normalize each retriever's scores to 0-1, then take a weighted sum), can be better when tuned on labeled data, but it's more fragile when the score distributions change.
A middle option is learned sparse retrieval (SPLADE-style models), which produces keyword-like sparse vectors with learned term weights and expansions. It captures some paraphrase while staying good at exact terms, and runs on an inverted index.
When you draw a RAG system, draw two retrievers. Saying "vector search alone misses exact identifiers like error codes and SKUs, so I run BM25 in parallel and fuse with reciprocal rank fusion" is one of the clearest signals that you've seen RAG fail in practice.
Reranking
Retrieval is tuned for recall: get the right passage somewhere in the top 50-200, cheaply. The LLM needs precision: the right passages in the top 5-10. A reranker bridges the two.
A cross-encoder reranker reads the query and one candidate passage together in a single transformer pass and outputs a relevance score. Because every query token can attend to every passage token, it understands relevance far better than comparing two independently computed vectors. It can't be precomputed, though, so it only runs on the candidates the retrievers found.
Rerankers commonly lift answer quality more than any other single change to a basic pipeline. The cost is latency and compute. Say we rerank 50 candidates, each truncated with the query to 256 tokens, with a 300M-parameter cross-encoder: 50 × 256 = 12,800 tokens × 2 × 300M ≈ 7.7 × 10^12 FLOPs per query. On an H100 at ~400 TFLOP/s effective, that's about 19 ms; on an L4 at ~36 TFLOP/s, about 210 ms. A smaller reranker of ~30M parameters is 10× cheaper with some quality loss. So the knobs are: how many candidates, how long each one is, and which model.
Other options:
- Hosted reranking APIs (Cohere, Voyage, Jina and others) avoid running GPUs, at a per-query price.
- LLM rerankers ask an LLM to score or order the candidates. They're strong but slow and expensive, so they fit low-volume, high-value queries.
- Late interaction (ColBERT-style) stores a vector per token and scores with token-level matching. It sits between bi-encoders and cross-encoders in quality and cost, at the price of a much larger index.
After reranking, two cleanups help: deduplicate near-identical chunks (five copies of the same boilerplate waste five context slots), and consider diversity (maximal marginal relevance) when a question needs several different passages, not the same fact five times.
Query Transformation
The user's message is often a poor search query. A few techniques fix that before retrieval:
- Conversational rewrite. In chat, "what about for contractors?" means nothing alone. A small LLM call rewrites it using the conversation into "What is the parental leave policy for contractors?" This is the single most important query transformation for chat-based RAG.
- Filter extraction. "Q3 2024 board decks about pricing" becomes a query ("pricing") plus filters (
doc_type = board_deck,date in Q3 2024). - Multi-query. Generate a few paraphrases and retrieve for each, then fuse. It improves recall on ambiguous questions, at the cost of several retrievals.
- HyDE (hypothetical document embeddings). Have the LLM write a plausible answer and embed that instead of the question, since an answer looks more like the passages than a question does. It helps when queries are short and documents are long, and hurts when the fake answer is confidently wrong.
- Decomposition. Split a multi-part question ("compare our 2023 and 2024 refund policies") into sub-queries, retrieve for each, and answer from the combined context.
- Routing. Not every message needs retrieval. "Thanks!" or "rewrite that shorter" can skip it. A classifier or the LLM itself decides when, and which index to search.
Each of these adds an LLM call or a retrieval round, so add them where evaluation shows they help, not by default.
Generation With Citations
The prompt puts the retrieved passages in front of the model, each with an identifier, and tells it how to use them:
You answer questions using only the sources below.
Cite sources inline like [2]. If the sources don't contain the answer, say you don't know.
[1] Employee Handbook > Leave > Parental leave (updated 2024-03-01)
Employees are eligible for 16 weeks of paid parental leave after 90 days of employment...
[2] Contractor Policy > Benefits
Contractors are not eligible for company leave programs. Leave is governed by...
Question: What is the parental leave policy for contractors?
A few practices make a real difference:
- Number the sources and require citations. Citations let users verify answers and let you measure faithfulness automatically. Map each citation back to the document and position so the UI can link to it.
- Give an explicit way out. "If the sources don't contain the answer, say so" reduces confident made-up answers when retrieval failed.
- Include metadata like titles and dates, so the model can prefer the newer policy and say which document it used.
- Mind the order. Models tend to use information at the start and end of a long context more reliably than in the middle. Put the strongest passages first, and don't pad the context with weak ones.
- Keep the context tight. Eight 512-token chunks is about 4,000 tokens. More context isn't free: it costs money and latency, and irrelevant passages measurably distract the model.
Why Not Just Use a Long Context?
Models with 1M-token context windows invite the question: why retrieve at all? For small corpora, a few hundred pages that fit in the window, stuffing everything in can work well, especially with prompt caching. But it doesn't scale to our corpus. 3.25B tokens is thousands of times larger than any context window. And even when it fits, cost is per token: a 1M-token prompt at an illustrative $3 per million input tokens costs $3 per question, against about $0.015 for a 5,000-token RAG prompt, 200× less. Prefill latency grows with the prompt too. On a 70B model, 1M tokens is 1M × 140 GFLOPs = 1.4 × 10^17 FLOPs before attention, which is around 90 seconds on four H100s at 40% utilization. Long context and RAG work together: retrieval narrows millions of documents to the relevant few, and a long window lets you include whole sections instead of fragments.
Evaluation
RAG has two stages that fail in different ways, so evaluate them separately. If an answer is wrong, you need to know whether retrieval missed the passage or the model ignored it, because the fixes are completely different.
Building an Evaluation Set
You need a set of questions with known answers and, for retrieval, known relevant passages. Ways to get one:
- Real queries from logs or a pilot, labeled by domain experts with the correct passages and a reference answer. This is the gold standard. A few hundred well-chosen questions go a long way.
- Synthetic questions generated by an LLM from sampled chunks ("write a question this passage answers"). Cheap and scalable, but they tend to reuse the passage's wording, which flatters lexical and embedding search. Mix them with real queries, and have humans review a sample.
- Hard cases on purpose: questions with no answer in the corpus, questions that need two documents, questions about outdated versus current policies, identifier lookups.
Version the evaluation set and run it on every change to chunking, embeddings, retrieval settings, reranker or prompt.
Retrieval Metrics
Given the labeled relevant chunks for each question:
- Recall@k: the fraction of relevant chunks found in the top k. The most important retrieval metric for RAG, because the LLM can only use what's in its context.
- Precision@k: the fraction of the top k that are relevant. It matters for context budget and distraction.
- MRR (mean reciprocal rank): 1 ÷ the rank of the first relevant result, averaged over questions. Good when one passage is enough.
- nDCG@k: rewards relevant results more the higher they appear, with a logarithmic discount by position, normalized by the best possible ordering.
A worked example. The relevant chunks are A and C, and retrieval returns [B, A, D, C, E]:
- Recall@3 = 1 of 2 relevant found = 0.5; recall@5 = 1.0.
- Precision@5 = 2 of 5 = 0.4.
- Reciprocal rank = 1 ÷ 2 = 0.5 (first relevant result at rank 2).
- DCG@5 = 1/log₂(2 + 1) + 1/log₂(4 + 1) ≈ 0.631 + 0.431 = 1.062. The ideal ordering puts A and C first: 1/log₂(2) + 1/log₂(3) = 1 + 0.631 = 1.631. So nDCG@5 ≈ 1.062 ÷ 1.631 ≈ 0.65.
Measure recall both after retrieval (say, recall@100) and after reranking (recall@8). The first tells you whether the retrievers find the passage at all; the second whether the reranker promotes it.
Answer Metrics
For the generated answer:
- Faithfulness (groundedness): is every claim in the answer supported by the retrieved passages? Usually measured by an LLM judge that splits the answer into claims and checks each against the context.
- Answer relevance: does it actually address the question?
- Correctness: does it match the reference answer? Judged by an LLM against the reference, or by exact match for short factual answers.
- Citation quality: do the cited passages support the sentences that cite them (citation precision), and is every claim cited (citation recall)?
- Abstention: on unanswerable questions, does the system say it doesn't know?
Open-source libraries such as Ragas implement versions of these metrics. Whatever you use, calibrate LLM judges against human labels on a sample before trusting them, and re-check when you change the judge model. The broader evaluation infrastructure (tracing, online scoring, regression alerts) is designed in Design an LLM Evaluation and Observability System.
Online Signals
Offline sets don't cover everything users ask. In production, watch thumbs up and down, whether users click citations, follow-up rephrasings (a sign the first answer missed), escalations to a human agent in support use cases, and the rate of "I don't know" answers. Sample live traffic for judge-based faithfulness scoring, and feed failures back into the evaluation set.
Diagnosing Failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Right document exists, never retrieved | identifier or jargon query on vectors only; bad parsing; chunk lost its context | hybrid search; fix the parser; contextual headers |
| Retrieved at rank 40, not in the context | weak ranking | reranker; retrieve more candidates |
| Correct passage in context, wrong answer | too much noise in context; passage cut mid-thought | fewer, better chunks; small-to-big; better prompt |
| Answer mixes old and new policy | stale or duplicate documents | metadata (dates, versions) and filters; dedupe; delete superseded docs |
| Confident answer to an unanswerable question | no way out in the prompt; model ignoring context | explicit abstention instruction; faithfulness checks |
| Follow-up questions fail | no conversational rewrite | rewrite the query with chat history |
RAG in an Interview
Which Tool When
- Recursive, structure-aware chunking of a few hundred tokens with overlap as the default, with contextual headers and small-to-big when chunks lose meaning out of context.
- Hybrid retrieval with RRF as the default retriever; vector-only only when queries are purely semantic and you've measured it.
- A cross-encoder reranker over the top 50-100 candidates whenever answer quality matters, which is almost always.
- Metadata filters applied during search for permissions, dates and document types.
- Conversational query rewriting for any chat interface.
- Evaluation from day one: recall@k on a labeled set, faithfulness and correctness on answers.
Common Follow-ups
- "RAG or fine-tuning?" RAG for knowledge that changes, must be cited, or is too large to memorize. Fine-tuning for behavior: tone, format, a narrow task, domain vocabulary. They combine well, for instance a model fine-tuned to answer from sources and cite them.
- "How do you handle permissions?" Store access control lists as chunk metadata and filter during retrieval, so the model never sees passages the user can't read. Never filter only after generation.
- "How do you keep the index fresh, and handle deletes?" Incremental indexing from change events, versioned chunks, and a fast path for deletions. See Design a RAG System.
- "How would you improve a RAG system that gives wrong answers?" First split retrieval failures from generation failures with your evaluation set, then fix the stage that's failing using the table above.
- "Why not just use a 1M-token context?" Cost, latency and scale: it's about 200× the cost per question of a tight RAG prompt and can't hold a large corpus, though it's great for including whole sections once retrieval has found them.
Summary
RAG grounds an LLM in your documents by retrieving relevant passages and putting them in the prompt. Its quality is set mostly by retrieval. Chunk documents along their structure, a few hundred tokens at a time with overlap, and keep each chunk's context with headers or by returning its parent section. Embed chunks with a bi-encoder for semantic matching, but remember that embeddings miss identifiers, rare names and negation, so run BM25 alongside and fuse the two with reciprocal rank fusion. Then rerank the top candidates with a cross-encoder to turn high recall into high precision, and apply metadata filters inside the search.
On the query side, rewrite conversational questions into standalone queries and extract filters. On the generation side, number the sources, require citations, keep the context tight and give the model a way to say it doesn't know. Evaluate retrieval (recall@k, MRR, nDCG) and answers (faithfulness, correctness, citation quality) separately, on a versioned set of real and hard questions, so that when something goes wrong you know which stage to fix.