What if your AI assistant could answer questions from your own documents, not just what it memorized during training? That is the promise of retrieval-augmented generation, or RAG. The idea sounds simple: search a knowledge base, paste the best passages into the prompt, and let the model write an answer. In practice, most first attempts disappoint. The answers are vague, the wrong documents surface, and nobody can tell whether the system improved or just got more confident.
This guide walks through the architecture, the decisions that matter most, and the mistakes that quietly sink projects. It is written for teams who have read the hype and now need something that holds up in production.
What RAG Actually Is, in Plain Terms
RAG pairs two systems. A retriever finds relevant text from an external store. A generator (a large language model) writes an answer using that text as context. The approach was formalized in a 2020 paper that combined a pretrained sequence-to-sequence model with a dense retriever over a Wikipedia index. If you want the original framing, the retrieval-augmented generation paper by Lewis and colleagues explains the retriever–generator design directly.
The appeal is practical. Instead of retraining a model whenever facts change, you update the index. Instead of hoping the model remembers a policy, you hand it the policy. For a neutral overview of the terminology and how the pieces fit together, the encyclopedia entry on retrieval-augmented generation is a reasonable starting point.
But here is the catch that the marketing rarely mentions: retrieval quality caps answer quality. If the right passage never reaches the prompt, no amount of prompt engineering saves you.
The Core Pipeline, Stage by Stage

Every RAG system, from a weekend prototype to a enterprise deployment, follows roughly the same path.
- Ingest source documents: PDFs, wikis, tickets, database rows.
- Clean and parse them, stripping headers, footers, and navigation junk.
- Chunk the text into passages small enough to retrieve precisely.
- Embed each chunk into a vector and store it alongside metadata.
- Retrieve candidate chunks for an incoming query.
- Rerank those candidates with a more expensive scoring model.
- Assemble a prompt with the best passages and the user’s question.
- Generate an answer, ideally with citations.
- Evaluate the whole chain, not just the final text.
Most teams spend 80 percent of their effort on steps 3 through 6, and that is roughly the right allocation. The generation step gets the attention, but retrieval is where the leverage lives.
Chunking: The Decision Nobody Agrees On
Chunking is splitting documents into retrievable units. It sounds clerical. It is actually the highest-leverage choice in the pipeline.
Chunks that are too small lose context. A sentence saying “the limit is 30 days” is useless if the reader cannot tell which limit applies to what. Chunks that are too large dilute the embedding, so a passage about five topics matches queries about none of them well. (News)
Practical guidance that holds up across projects:
- Start with chunks of roughly 200 to 500 tokens and test from there.
- Add overlap of 10 to 20 percent between consecutive chunks so sentences at boundaries survive.
- Respect document structure. Split at headings and paragraph breaks before splitting at character counts.
- Attach metadata to every chunk: source, section, date, and any access restrictions.
There is no standard for chunk size, overlap, or how many chunks to retrieve. Recommendations differ by source, and the honest answer is that you have to measure on your own corpus. The dense retrieval work that popularized passage-level encoding used fixed-length passages, which is a reasonable default but not a law of nature.
A common mistake: teams chunk a PDF by character count and end up with chunks that start mid-table and end mid-sentence. The fix is boring and effective. Parse to structured text first, then chunk along semantic boundaries.
Choosing a Retrieval Method
Two families dominate. Lexical retrieval matches keywords, usually with BM25 scoring. Dense retrieval embeds queries and passages into vectors and finds nearest neighbors.
Dense retrieval became the default after work showing that encoding questions and passages with separate neural encoders and retrieving by maximum inner product beat keyword baselines on open-domain question answering. The Dense Passage Retrieval paper walks through that method and its evaluation.
| Method | Strength | Weakness | Good fit |
|---|---|---|---|
| BM25 keyword | Exact terms, IDs, names, codes | Misses paraphrases | Policies, product codes, legal text |
| Dense vectors | Handles paraphrase and synonyms | Can miss rare exact tokens | Conversational questions, support docs |
| Hybrid | Recall from both | More moving parts | Most production systems |
The pattern that works in practice is hybrid retrieval: run both, merge the candidate lists, then rerank. It costs more compute and adds complexity, but it catches the failure modes of each method alone. A user searching for “error 4471” needs exact matching. A user asking “why does my invoice keep failing” needs semantic matching. Hybrid handles both.
Vector Search at Scale
Once you have embeddings, you need a way to search them. Approximate nearest neighbor indexes trade a small amount of recall for a large gain in speed. The FAISS library for efficient similarity search is the reference implementation most systems build on or borrow ideas from.
A few practical notes:
- Exact search is fine below roughly a hundred thousand vectors. Do not over-engineer early.
- Above that, approximate indexes with tunable recall parameters are standard.
- Measure recall against a brute-force baseline before trusting any index configuration.
- Vector databases are an implementation choice, not a requirement. A search engine or an in-process library can carry a RAG system perfectly well.
Teams often adopt a managed vector store before they have any data to put in it. Start with the simplest store that meets your latency target and migrate when you have evidence you need to. (Blog)
Reranking: The Cheapest Quality Win
First-stage retrieval optimizes for speed, so it returns a broad candidate set. A reranker then scores each query–passage pair jointly with a cross-encoder, which is slower per item but far more accurate. Applying it to the top 50 candidates and keeping the top 5 is one of the highest-return changes available. The cross-encoder reranking approach described by Nogueira and Cho is the standard reference.
Two caveats. First, reranking adds latency, so budget for it. Second, a reranker cannot rescue a passage that first-stage retrieval never returned. Fix recall before you tune precision.
Prompt Assembly and Context Limits
You have your passages. Now you have to fit them into a prompt without confusing the model.
Long-context models have expanded what fits, but stuffing twenty passages into a prompt still causes problems. Relevant details get buried in the middle, cost climbs, and the model may latch onto an irrelevant passage. The research on how language models use information in the middle of long contexts is worth reading before you assume more context is always better.
What works in practice:
- Put the most relevant passages first and last, not buried in the middle.
- Include source labels so the model can cite them.
- Instruct the model to say when the context does not contain the answer.
- Cap the number of passages and test whether fewer performs better.
That last instruction matters more than it looks. Without an explicit escape hatch, models tend to answer anyway, which is how RAG systems produce confident nonsense.
Evaluation: Two Systems, Two Scorecards
You cannot improve what you do not measure, and RAG has two components that fail independently. Evaluate retrieval and generation separately.
Retrieval metrics include recall@k (did the right passage appear in the top k?) and mean reciprocal rank (how high did it rank?). Build a test set of real questions with known correct passages. Fifty well-chosen questions beat five thousand synthetic ones.
Generation metrics include exact match and F1 against reference answers, plus faithfulness or groundedness: does every claim in the answer trace back to a retrieved passage? A survey of RAG evaluation methods and metrics covers the landscape in more depth.
A practical routine: log every query, retrieved passages, and final answer. Sample weekly, label whether the answer was supported, and track the rate over time. This catches regressions that aggregate benchmarks miss. (Cloud)
Common Mistakes and What to Do Instead
These failures show up again and again.
Chunking by character count. Parse first, chunk second.
Skipping the reranker. It is usually the fastest quality gain available.
No “I don’t know” path. Give the model permission to decline, and test that it does.
Treating the vector database as the architecture. The store is a component. The pipeline is the system.
Evaluating only the final answer. When quality drops, you need to know whether retrieval or generation broke.
Ignoring access control. If different users can see different documents, filter at retrieval time, not after generation.
Assuming 2020 benchmark results reflect today. Early RAG papers reported gains against that era’s baselines. Current models and methods have moved on, so treat those numbers as historical context, not a target.
A Realistic Build Order
For a team starting from scratch, this sequence avoids the usual dead ends.
- Collect 50 real questions with known answers.
- Index a small, clean corpus with simple chunking and dense retrieval.
- Measure recall@10. If it is below roughly 80 percent, fix chunking and parsing before anything else.
- Add hybrid retrieval and compare.
- Add a reranker and compare again.
- Only then tune the prompt and generation settings.
- Add faithfulness checks and a decline path.
- Expand the corpus once the pipeline is stable.
Each step has a measurement attached. That is the difference between a demo and a system.
Conclusion
RAG is not a product you install. It is a pipeline you tune, and the tuning happens mostly on the retrieval side. Get parsing and chunking right, combine lexical and dense search, rerank aggressively, and measure retrieval and generation separately. Do those things and the system will answer from your documents with something resembling reliability. Skip them and you will have a very confident assistant that is occasionally, unpredictably wrong.
Frequently Asked Questions
What is the difference between RAG and fine-tuning?
Fine-tuning changes the model’s weights to shape behavior, style, or task performance. RAG leaves the model alone and supplies facts at query time through retrieval. Use fine-tuning for format and tone, and RAG for knowledge that changes or must be cited. Many teams use both.
How big should chunks be?
There is no universal answer. Most teams land between 200 and 500 tokens with 10 to 20 percent overlap, then measure recall on their own questions. Structure-aware splitting at headings and paragraphs matters more than the exact token count.
Do I need a vector database?
No. A vector database is one implementation choice among several. Small corpora work fine with in-process libraries or exact search. Adopt a dedicated store when your data volume, filtering needs, or latency targets justify it.
How do I stop the model from making things up?
You cannot eliminate it, but you can reduce it sharply. Retrieve better passages, instruct the model to answer only from context, require citations, and give it an explicit way to say the context is insufficient. Then measure faithfulness on a sample of real queries.
How many passages should I retrieve?
Start with 5 to 10 after reranking and test both directions. More passages raise cost and can bury the relevant detail. Fewer passages raise the risk of missing context. The right number depends on chunk size and question type, so measure rather than guess. (NIST AI Risk Management Framework)
How do I know if my RAG system is getting better?
Track retrieval recall@k and answer faithfulness separately on a fixed test set of real questions. Log production queries and sample them for manual review. If recall rises but faithfulness does not, the problem is in generation. If both fall, look at ingestion and chunking first.







