A language model knows only what it saw in training and what you put in its prompt. It has never seen your company's wiki, and it does not know yesterday's policy change. Retrieval-augmented generation (RAG) fixes this in two steps: first find the passages that are relevant to the question, then ask the model to answer from those passages. "Design a chatbot over our documents" is one of the most common AI interview questions, and the answer is mostly search engineering, not model magic. This lesson covers embeddings, chunking, vector search, hybrid search, reranking, and how to measure and run the whole thing.
1. Why RAG
- Fresh and private data. Update the index and the answers change. No retraining.
- Evidence and citations. The answer can point to its sources, and the user can check them.
- Access control. You decide which documents each user may see, at retrieval time.
- Cheaper than the alternatives. Fine-tuning changes how a model writes, and it is a poor way to teach it facts. Putting the whole knowledge base in every prompt is too costly: a 128,000-token context uses as much GPU cache as about 58 normal chats (the LLM serving lesson).
2. The Two Pipelines
flowchart LR
subgraph Ingest["Ingestion: offline, when documents change"]
D[Documents] --> P[Parse and chunk] --> E[Embed each chunk] --> X[(Index: vectors, keywords, metadata)]
end
subgraph Query["Query: online, for each question"]
Q[Question] --> QE[Embed question] --> H[Hybrid search with filters] --> R[Rerank 50 to 5] --> A[Build prompt with sources] --> L[LLM] --> ANS[Answer with citations]
end
X --> H
Most quality problems in RAG are in the retrieval half. If the right passage is not found, no model can answer well.
3. Embeddings and Similarity
An embedding is a list of numbers (often 768 or 1,536 of them) that represents the meaning of a piece of text. A trained embedding model produces it. Texts with similar meaning get vectors that point in similar directions, so "How do I reset my password?" lands near "Steps to recover your account", even with no shared words.
Closeness is measured with cosine similarity (the angle between two vectors, from -1 to 1). If every vector is scaled to length 1, cosine similarity is just the dot product, which is fast. The simplest search compares the query vector with every stored vector and keeps the best K:
import heapq
import math
class FlatIndex:
def __init__(self):
self.ids = []
self.vectors = [] # all scaled to length 1
def add(self, doc_id, v):
self.ids.append(doc_id)
self.vectors.append(self._normalize(v))
def top_k(self, query, k):
q = self._normalize(query)
scored = ((self._dot(q, v), i) for i, v in zip(self.ids, self.vectors))
return [i for _, i in heapq.nlargest(k, scored)] # keeps only the best k
@staticmethod
def _dot(a, b):
return sum(x * y for x, y in zip(a, b))
@staticmethod
def _normalize(v):
length = math.sqrt(sum(x * x for x in v))
return [x / length for x in v]
Three rules matter in practice:
- One model for both sides. Documents and questions must be embedded by the same model. Vectors from different models cannot be compared.
- Embeddings miss exact details. Product codes, error numbers, names and negations ("not allowed") are weakly captured. This is why we add keyword search (section 6).
- Embedding is a cost. Every chunk is embedded once at ingestion, and every question at query time.
4. Chunking
You do not embed a whole 40-page document as one vector: the vector would blur many topics together, and the model's prompt could not hold it. You cut documents into chunks and embed each one. A chunk is the unit that is searched, retrieved and quoted.
- Size. About 200 to 500 tokens works for most text. Too small and a chunk loses the context it needs. Too big and the vector blurs, and prompt tokens are wasted.
- Overlap. Repeat 10 to 20% of the previous chunk at the start of the next, so a sentence cut at the border still appears whole somewhere.
- Split on structure. Break at headings, paragraphs and list items, not in the middle of a sentence. Keep a table or a code block together.
- Keep metadata with each chunk. Document ID, title, section, URL, version, owner and the permission groups. You need these for filters, citations and updates.
- Parent and child. Search small chunks for precision, then send the larger parent section to the model for context.
5. Vector Search at Scale
The top_k method above is exact (flat) search: it compares the query with every stored vector. For 5 million chunks of 768 numbers, one query needs 5 million × 768 = 3.8 billion multiplications. That is about 0.4 seconds on one core (an assumption), too slow for a budget of tens of milliseconds. So production systems use approximate nearest neighbor (ANN) search: it returns very nearly the best results, much faster.
| Method | Idea | Trade-off |
|---|---|---|
| Flat | Compare with every vector | Exact. Fine up to about 100,000 vectors |
| HNSW | Hierarchical Navigable Small World: a layered graph of neighbors. Start at the top, walk to closer and closer nodes | Fast and high recall. Needs extra memory for the graph, and builds slowly |
| IVF | Inverted File index: group vectors into clusters. Search only the few clusters nearest the query | Less memory than HNSW. Recall depends on how many clusters you probe |
| Quantized (PQ, int8) | Store compressed vectors. PQ is Product Quantization (split each vector into parts and store a short code per part). int8 keeps each number in 1 byte instead of 4 | 4 to 32 times less memory, with a small drop in recall |
- Recall is the price of speed. ANN may miss a true neighbor. Measure recall@K: of the true top K (from a flat search on a sample), how many did the index return? Tune the search width (
ef_searchin HNSW,nprobein IVF) to trade recall against latency. - Memory is dominated by the vectors. 768 numbers × 4 bytes = 3,072 bytes per vector. For 5 million vectors that is 15.4 GB, plus about 200 bytes each for an HNSW graph. The index is kept in RAM. With int8 quantization it is about 4.8 GB.
- Where to run it. pgvector (inside PostgreSQL) is simple, and fine for a few million vectors. Elasticsearch and OpenSearch do vector and keyword search together. Dedicated systems (Qdrant, Milvus, Weaviate, Pinecone) scale further. Larger indexes are sharded (the sharding lesson), and each query goes to every shard.
6. Hybrid Search and Reranking
Vector search finds meaning. Keyword search (BM25, "Best Matching 25", from the search lesson) finds exact words. Run both, and merge the two ranked lists. A simple merge that needs no tuning is Reciprocal Rank Fusion (RRF): each document gets 1 ÷ (60 + rank) from every list it appears in, and the scores are added. The constant 60 is the usual choice.
Vector search ranks: A, B, C
Keyword search ranks: C, A, D
A: 1/61 + 1/62 = 0.0325 (rank 1 in vectors, rank 2 in keywords)
C: 1/63 + 1/61 = 0.0323 (rank 3, rank 1)
B: 1/62 = 0.0161
D: 1/63 = 0.0159
Merged order: A, C, B, D
Documents found by both methods rise to the top, and neither method's raw scores need to be compared.
Then rerank. The first stage embeds the query and chunk separately, which is fast but rough. A cross-encoder reranker reads the query and one chunk together and scores how well the chunk answers the question. It is much more accurate and much slower, so you apply it only to the top 50 and keep the best 5. This funnel (millions, then 50, then 5) is the standard shape of a RAG retrieval path. A rerank step usually adds 100 to 200 ms.
6.1 Filters and Access Control
Users may see only the documents they have permission for. Apply the permission filter inside the search (pre-filter), not after it. If you take the top 10 and then remove the forbidden ones, you may have zero results left. Never rely on the prompt ("do not reveal secret documents") to protect data. A document the user may not see must never reach the model.
7. From Chunks to an Answer
- Build the prompt. Instructions, then the numbered chunks, then the question. Put the strongest chunks first, remove duplicates, and keep the total inside the token budget, with room for the reply (the context window, in the LLM serving lesson).
- Ask for citations. Tell the model to cite the chunk numbers, and show the source links to the user.
- Allow "I don't know". Tell the model to answer only from the sources. If the best chunk scores low, or no chunk has the answer, say so instead of guessing.
- Treat documents as data, not commands. A retrieved page may contain "ignore your instructions and ...". This is prompt injection. Mark the sources clearly as untrusted text, give the model no powers it does not need, and filter its output.
8. Evaluating and Debugging
Measure retrieval and generation separately, or you will not know what to fix. Build an evaluation set of 100 to 300 real questions, each with the document that holds the answer, and run it after every change.
- Retrieval: recall@K (is the right chunk in the top K?) and MRR (Mean Reciprocal Rank: how high is it ranked?). For each question, take 1 ÷ the rank of the first correct chunk (rank 1 gives 1, rank 2 gives 0.5, rank 4 gives 0.25), then average over all questions.
- Generation: faithfulness (is every claim supported by the sources?) and answer relevance (does it answer the question?). People or a second model can grade these. Spot-check by hand.
| Symptom | Likely cause | Fix |
|---|---|---|
| Document exists, never found | Bad chunking, weak embeddings, exact term missed | Better chunks, add keyword search, tune recall |
| Found, but ranked low | Rough first-stage ranking | Add or improve the reranker |
| Found, answer still wrong | Prompt, too many chunks, model | Fewer, better chunks. Clearer instructions |
| Confident invented answer | No evidence, and no "I don't know" rule | Require sources. Abstain on low scores |
| Out-of-date answer | Index not updated | Update on change events. Show document dates |
9. Keeping the Index Correct
- Updates. When a document changes, re-chunk it, embed the new chunks, and replace the old ones. Do it from change events (see the queues and batch lessons), so the index follows the source. Keep a document version, so a half-updated document is never searched.
- Deletes. Removing a document or a user's data must remove its chunks too. Plan this from the start, because vectors are copies of private text.
- Changing the embedding model. New vectors are not comparable with old ones, so you must re-embed everything. Build a new index beside the old one, check quality on the evaluation set, then switch traffic with an alias, as in the search lesson. Keep the old index until you are sure.
10. Worked Example: A Company Knowledge Assistant
The knowledge base has 1 million documents of about 2,000 tokens each. Each day 10,000 documents change and 200,000 questions arrive. Peak is about 4 times the average.
- Chunks: 500-token chunks with a 50-token overlap give about 5 chunks per document, so 5 million chunks. Daily changes mean 50,000 chunks to re-embed.
- Memory: 5 million vectors × 3,072 bytes = 15.4 GB, about 16.4 GB with the HNSW graph, so it fits in RAM on a single node. Run 2 replicas for availability. Chunk text (2 KB each) is another 10 GB, kept in a database or object storage.
- Embedding cost: the first load is 5 million × 500 = 2.5 billion tokens. At a hypothetical $0.10 per million tokens, that is $250 once, and 25 million tokens a day ($2.50) afterwards.
- Questions: 200,000 ÷ 86,400 = 2.3 per second on average, about 9 at peak. Each prompt has the top 5 chunks (2,500 tokens), instructions and the question: about 3,500 tokens in, 300 tokens out. That is 700 million input and 60 million output tokens a day.
- Latency to the first token: embed the question 15 ms, vector and keyword search in parallel 15 ms, rerank 120 ms, and prefill 3,500 ÷ 30,800 = 114 ms. The total is about 265 ms. The reply of 300 tokens at 7.6 ms each takes 2.3 seconds, streamed (numbers from the LLM serving lesson).
- LLM GPUs: each request needs 0.114 s of prefill plus 300 ÷ 4,204 = 0.071 s of decode, so 0.185 GPU-seconds. At 9.3 per second that is 1.7 GPUs of work. At 70% utilization it is 2.45, and with zone-loss headroom (× 1.5) it is 3.7, so 4 GPUs.
The retrieval side is small: one 16 GB index and a few CPU cores. The cost and latency come mostly from the LLM and the reranker. That is why section 7's rules (fewer, better chunks) cut both cost and time.
11. Common Pitfalls
- Blaming the model. Most bad answers are retrieval failures. Look at what was retrieved first.
- No evaluation set. Without one, every change is a guess.
- Vector search only. Exact codes, names and numbers get missed. Add keyword search.
- Chunks too big or too small. Test sizes on your own data.
- Filtering after the search. Pre-filter, or you return nothing.
- Access control in the prompt. Keep forbidden documents out of the model's context altogether.
- Too many chunks in the prompt. Cost and latency rise, and quality can fall. Rerank and keep the best few.
- Mixing embedding models in one index, or changing the model without re-embedding.
- No "I don't know" path, so the model invents an answer.
12. Interview Questions This Lesson Prepares You For
- What is RAG and why use it instead of fine-tuning? RAG finds relevant passages and gives them to the model as evidence. It uses fresh and private data, allows citations and access control, and needs no retraining. Fine-tuning changes style and behavior, not reliably facts.
- Walk me through a RAG system. Ingestion: parse, chunk, embed and index with metadata. Query: embed the question, run hybrid search with permission filters, rerank, build a prompt with numbered sources, call the model, and return the answer with citations.
- How do you choose a chunk size? About 200 to 500 tokens with 10 to 20% overlap, split on structure, then test on an evaluation set. Small chunks are precise but lose context, and large ones blur the vector. Parent-child retrieval gets both.
- Why use ANN instead of exact search, and what do you lose? Exact search compares with every vector, which is too slow at millions of vectors. ANN (such as HNSW) is much faster but may miss a true neighbor. Measure recall@K and tune the search width.
- Why hybrid search and reranking? Vectors capture meaning but miss exact terms, and keywords miss paraphrases. Reciprocal Rank Fusion merges both lists. A cross-encoder then reranks the top 50 down to 5, for much better precision at about 100 to 200 ms.
- How do you enforce permissions in RAG? Store permission metadata with each chunk and filter inside the search, before taking the top K. Never depend on the prompt, because anything in the context can leak.
- The answers are bad. How do you debug? Check retrieval first: was the right chunk in the top K? If not, fix chunking, add keyword search or tune recall. If it was found but ranked low, fix reranking. If it was in the prompt and the answer is still wrong, fix the prompt or reduce the noise. Use an evaluation set, so each fix is measured.