Retrieval-Augmented Generation
Giving a model the right knowledge at answer time — chunking, retrieval, ranking, production.
Sections
Interview questions answered at staff level
RAG Fundamentals
Why RAG exists, when not to build it, and what happens inside a query.
10 questions02Chunking & Embeddings
The least glamorous section and the one that decides your ceiling.
10 questions03Retrieval & Ranking
Dense vs sparse, hybrid, rerankers, top-k and the vocabulary interviewers check for.
10 questions04Production RAG Systems
Multi-tenancy, security, caching, monitoring and incidents — judgment under constraint.
10 questionsRead first
Blog posts for this volume, easiest first
RAG in plain English: letting the AI look it up
Why a model that sounds like it knows everything still needs to check, and how retrieval-augmented generation makes it read before it answers.
Your first RAG pipeline in pure Python
Chunk, vectorise, rank and build a cited prompt in ~150 lines of standard-library Python, test it with pytest, then swap in a real Embedding model and LLM without touching the rest.
Hybrid search and reranking: a field guide
Dense and sparse retrieval fail in opposite ways. How Reciprocal Rank Fusion combines them in 15 lines, where ColBERT and SPLADE fit, and what a Cross-encoder costs per 100 candidates on CPU and GPU.
Talking a team out of RAG (when it is the wrong tool)
RAG is a default, not a requirement. When long context with prompt caching or text-to-SQL is the better design, what it costs and how fast it is with numbers, how per-document permissions change the answer, and the written threshold that flips the decision.
From toy RAG to a real one: embeddings, a vector store and an LLM
Take the stdlib pipeline from the first RAG post and swap in a real Embedding model, a persistent vector store and an LLM, with pinned versions, timeouts, retries, batching and tests.
Anatomy of a production RAG system
Every box between the user's question and a cited answer, with a latency and cost budget per stage, who owns it, and the one metric that tells you it is broken.
Choose your chunk size by measurement, not folklore
A reproducible method: build a small golden set on a public corpus, sweep chunk sizes, and read recall@k, evidence coverage and context cost off one table.
Key terms
58 pages with diagrams and quizzes
A list of numbers that stands for the meaning of a piece of text, arranged so that similar meanings land close together.
The space embeddings live in, where 'close together' means 'similar in meaning'.
A model that reads text and turns it into meaning-numbers, instead of writing a reply.
Turns the question and each document into vectors separately, then compares them. Fast enough to search millions.
Reads the question and one document together and scores the match. Much sharper than comparing vectors, far too slow to run over everything.
A score from −1 to 1 for how closely two embeddings point the same way: the usual way to ask 'are these two texts about the same thing?'
Multiply two lists of numbers position by position and add it all up. The cheapest way to ask 'do these two texts mean the same thing?'
How many numbers are in each embedding — 384, 768, 1024, 3072. Storage, speed and cost grow with it in a straight line. Quality does not.
Symmetric search matches like with like (ticket to ticket). Asymmetric search matches a short question to the long passage that answers it.
A tiny label such as 'query: ' or 'passage: ' stuck in front of text before embedding it, telling the model which role this text is playing.
Embeddings trained so the first few hundred numbers work on their own: cut 3072 down to 256 and keep most of the quality.
The big public scoreboard for embedding models. Perfect for picking three to try; your own test set decides the winner.
Training an embedding model a bit further on your own question-and-passage pairs, so your field's jargon finally lands near its meaning.
Cutting documents into passages small enough to search and hand to a model. Usually a few hundred tokens, cut where the document itself breaks.
Repeating the tail of one chunk at the start of the next, so an idea cut in half still appears whole somewhere.
Cutting where the topic changes rather than every N words, spotted by a drop in similarity between neighbouring sentences.
Search small chunks so the match is precise, then hand the model the bigger section around them. Retrieve small, return big.
Adding a short model-written note to each chunk saying where it came from, before it is stored. Anthropic measured 35–67% fewer retrieval misses.
Pulling text out of PDFs and scans with reading order, headings, tables and figures intact — so everything downstream has structure to work with.
Turning pictures of text — scans, photos, faxes — into text a computer can actually read. Mistakes here spread into everything downstream.
The machinery that collects your documents, parses, chunks, embeds and indexes them — and keeps the index honest as sources change and vanish.
The record book for ingestion: one row per source document — where it came from, its version, its status, who may see it, which chunks it made.
A fingerprint of a document's text. Same text, same fingerprint — so you can skip unchanged files, spot duplicates and retry safely.
Change data capture: reading a database's own change log so your search index follows every insert, update and delete within seconds.
A little note saying 'this was deleted', travelling through the system so every copy and index learns to drop it.
Rebuilding the whole index the new way — new model, new chunker, new fields — beside the live one, then switching over once it checks out.
The labels stored next to each chunk — customer, permissions, source, date, page — used for filtering, access control and citations.
Good old keyword search: find the documents containing the words you typed. Fast, easy to explain, and still unbeatable for IDs, codes and names.
The keyword scoring formula behind most search engines: rare words count more, repeats count less and less, long documents don't win by being long.
Keyword search with a brain: a model writes the weighted word list, and adds related words the text never used.
Search by meaning: turn the question and every passage into number-lists, and return the passages whose numbers sit closest.
Run keyword search and meaning search side by side, then merge the two lists — each one covers what the other misses.
Search that goes after what you meant rather than the words you typed. Usually embeddings, plus a reranker to tidy up the top.
Approximate nearest neighbour search: find vectors close to your query without checking them all. Give up a sliver of accuracy, gain huge speed.
The most common way to index vectors in memory: a layered map of 'who is near whom', walked greedily from the top down.
Sort the vectors into buckets, then only search the buckets nearest your question. Cheap to build, easy to split across machines.
Squash each vector into a handful of bytes by describing it with 'standard pieces' from a learned catalogue. 3,072 bytes become 64.
Storing each number in an embedding with fewer bits — 16-bit, 8-bit, even 1-bit — to cut memory 2–32×, with a re-check pass to win the accuracy back.
How many of the genuinely closest vectors your fast index actually returned. Measured against slow exact search, not against human opinion.
Restricting a search to items whose fields match conditions — this customer, this language, after 2024 — without quietly wrecking recall.
The cheap first pass that cuts millions of items down to a few hundred, so something slower and smarter can order them properly.
How many results a stage returns. Early stages want lots (100+); the few you hand the model want to be few (5–10).
Turning the user's messy message into a proper search query: resolving 'it', expanding jargon, dropping the small talk.
Breaking a question that is really three questions into parts, searching for each, then answering from all the evidence together.
Have the model write a pretend answer first, then search with that instead of the question — because answers look like documents, and questions don't.
Working out what kind of request just arrived, so it can be sent down the right path: document search, database query, tool call, or a polite 'no'.
A store built to search embeddings quickly, with filters, updates, deletes and backups. Often Postgres with pgvector is already enough.
Splitting an index across machines so each holds a slice. Buys you size and write throughput — not a faster single query.
Keeping copies of each shard on several machines, so you survive a failure and can answer more queries at once.
A slower, sharper model that re-scores the top 50–200 candidates, so only the best 5–10 ever reach the model writing the answer.
A merge trick for two result lists: score each document by its position in each list, not by the raw numbers. No calibration needed.
Combining retriever scores rather than ranks: rescale each list to a common range, then blend them with a weight you tune.
Turning ranked chunks into an actual prompt: drop duplicates, fit the token budget, order them, label them so they can be cited.
Models used to overlook facts buried in the middle of a long prompt. Finding one fact is largely fixed; joining several across a long text still isn't.
Making the model answer from the sources you handed it rather than from memory — and then checking that it actually did.
Linking each claim in an answer to the exact passage that backs it — and measuring whether those citations are right and complete.
Letting the system say 'I don't know' on purpose when the evidence isn't there, instead of guessing beautifully.
Reusing a stored answer when a new question means roughly the same as an old one. Cheap and fast, with a real risk attached.