Learn
RAG & vector databases

What is RAG (Retrieval-Augmented Generation)?

The short answer

RAG retrieves passages from your own documents at query time and places them in the prompt, so the model answers from evidence rather than from memorised weights. This walks the full pipeline: ingestion, chunking, embeddings, hybrid search, reranking, prompt assembly, evaluation, cost arithmetic, and the failure modes that separate a working system from a demo.

On this page

The problem RAG actually solves

A language model's knowledge lives in its weights, and weights are a lossy, frozen compression of the training text. Three consequences follow. The model cannot know anything after its cutoff. It cannot know documents it never saw, which includes every internal wiki, ticket, contract and support thread you own. And when it does not know, it does not reliably say so: it produces a fluent answer with the shape of the right answer and none of the content.

The usual framing is that RAG turns a closed-book exam into an open-book one. At query time you search a corpus for passages that bear on the question, paste those passages into the prompt, and instruct the model to answer from them. The model's job narrows from recall to reading comprehension, which is a task it is much better at. You also get something a fine-tuned model cannot give you cheaply: a citation trail. If the answer is wrong, you can inspect which passage produced it and whether the fault lies in retrieval or in generation. That separation is the practical reason RAG dominates enterprise deployments, more than any accuracy claim.

There is an economic argument too. Changing what the system knows becomes an indexing operation rather than a training run: a new policy is chunked, embedded and upserted, answerable within seconds, and deleting a document removes it, which matters for access control and erasure requests.

The pipeline, end to end

RAG has two paths that meet at an index. The offline path runs when documents change: fetch, parse, split into chunks, embed each chunk, and write the vector plus metadata plus raw text into a store. The online path runs per query: embed the question with the same model, search for nearest neighbours, rerank the candidates, assemble the survivors into a prompt, and call the generator.

The critical constraint is that both paths must use the same embedding model and preprocessing. Upgrade the embedder and every vector in the index is in a different space, so the whole corpus must be re-embedded. Teams that treat the embedding model as a config value rather than a schema version end up with indexes that silently return nonsense. Record model name, dimension, chunking parameters and parser version in the index metadata, and treat a change to any of them as a migration.

Parsing is the least glamorous stage and the most common source of ceiling. A two-column PDF that extracts interleaved produces chunks whose sentences are scrambled, and no reranker recovers from that. Tables flattened into a stream of numbers lose their header semantics. Before tuning retrieval, read fifty random chunks from your index; if they do not read like something a human would cite, fix parsing first.

What goes into the prompt

A typical prompt has four parts: a system instruction defining the task and refusal behaviour, the retrieved context, the conversation history if any, and the question. Make the contract explicit — answer only from the context, cite a source identifier per claim, and say when the context does not contain the answer. Without that last clause you have built a machine that always answers, which is worse than one that sometimes declines.

Context ordering matters more than people expect. Models attend most reliably to the beginning and the end of a long prompt and least reliably to the middle — lost in the middle. Put the highest-scoring chunk first and the second-highest last, and do not assume position twelve of twenty gets the attention position one gets. Ten chunks of four hundred tokens is 4,000 tokens of context, a fraction of a cent at current input prices.

Number the chunks and require inline citations by number. This is not decoration: it makes grounding checkable and gives you a signal at evaluation time. Treat an answer with no citation as ungrounded even when it is correct.

Retrieval is a search problem, not a model problem

The default mistake is to build dense-only retrieval and stop. Embeddings capture meaning, which is exactly what you want when a user asks about cancellation policy and the document says termination of subscription. They are weaker at exact tokens: part numbers, error codes, surnames, legal citations, version strings. A query for XK-4471 will not reliably retrieve the chunk containing XK-4471 if the embedder treats it as an opaque rare token, whereas BM25 will nail it because the term frequency is decisive.

Production systems therefore run hybrid retrieval: lexical search, dense search, and a fusion step. Reciprocal rank fusion is the usual choice because it needs no score calibration — each result contributes one divided by a constant plus its rank, summed across lists. It beats either retriever alone on mixed workloads and costs one extra query.

The number of candidates you pull is a separate decision from the number you keep. A common configuration retrieves 50 from each retriever, fuses to 60 or 80, reranks, and keeps 8 to 12 for the prompt. Recall is the metric that matters at the retrieval stage: if the right passage is not in the candidate set, no downstream component can recover it. Precision is the reranker's job.

Reranking is the cheapest quality win

A bi-encoder embeds the query and the document independently, so it can precompute document vectors and compare them with a dot product. That independence is what makes it fast and also what limits it: the query never influences how the document is read. A cross-encoder takes the query and the document together as one input and outputs a relevance score, which lets it model term-level interaction and negation. It is far more accurate and far too slow to run over a million documents.

The standard pattern is therefore retrieve-then-rerank: a cheap first stage narrows millions to dozens, and a cross-encoder scores those dozens in a single batched forward pass. Reranking 50 candidate pairs of 512 tokens takes on the order of 50 to 150 milliseconds on a modern GPU and is usually the single largest quality improvement available per unit of engineering effort. Measure it: compute nDCG at 10 with and without the reranker on a labelled set. If the delta is small, your first stage is already good and you should spend the effort elsewhere.

Two practical notes. Cross-encoders cap input length, often at 512 tokens, so long chunks are truncated and their tails become invisible to the scorer. And a domain-tuned reranker trained on a few thousand labelled pairs often beats a larger general one, which makes this a good place to spend annotation budget.

Query transformation

Users write short, context-dependent queries. The question what about the enterprise tier, asked as a follow-up, contains no retrievable content on its own. Rewriting the query against the conversation history before retrieval is often worth more than swapping the embedding model. A small model with the last few turns can turn it into a standalone query with the product and the topic made explicit.

Multi-query expansion generates three to five paraphrases, retrieves for each and fuses the results. It helps when the user's vocabulary differs from the document's — a customer says refund, the policy says credit — and costs proportionally more retrieval calls, which is cheap next to generation. HyDE takes another route: have the model write a hypothetical answer, embed that, and search with the answer's vector. Answers and passages look more alike than questions and passages, so the match improves; the risk is that a confidently wrong hypothetical pulls retrieval towards its own error.

Query decomposition handles questions needing several independent facts, such as comparing the SLA across two plans. Splitting into sub-questions, retrieving for each and merging the evidence beats one blended query, at the cost of more calls and more context to fit.

Agentic and iterative retrieval

Single-shot retrieval assumes one search answers the question. For research-style tasks it does not: the model needs to read a result, notice a missing piece, and search again. Agentic RAG exposes retrieval as a tool and lets the model call it in a loop, deciding when it has enough evidence. This handles multi-hop questions that fixed pipelines fail on, and it makes the trajectory auditable — you can see every query issued and every passage returned.

The cost is latency and unpredictability. A three-hop question may issue six searches and take fifteen seconds, and loops can stall by repeating a query that returned nothing, so cap the iterations and require a changed query on retry. For most product Q&A a fixed pipeline with rewriting and reranking is faster, cheaper and easier to evaluate; reserve the loop for questions that genuinely need assembly across documents.

Failure modes worth naming

Retrieval miss is the dominant failure: the passage exists but never reaches the candidate set, usually through vocabulary mismatch, chunking that severed the answer, or a query that needed rewriting. Distractor dominance is second: the right passage is present but surrounded by plausible wrong ones sharing its vocabulary, and the model averages them. Chunk-boundary errors are a subset of the first, where the answer spans a split and neither half suffices.

Then there are corpus problems no retrieval tuning fixes. Conflicting sources: two documents disagree and the model has no basis for preferring one, so it should surface the conflict. Stale index: the document was updated and the chunk was not re-embedded. Permission leakage: the retriever returns a chunk the user may not see, which is an access-control bug, not a ranking bug. Filter by permission in the index, not in the prompt.

Finally, over-answering. Given weak context, the model fills gaps from parametric memory and produces a confident synthesis citing a passage it did not really use. This is why groundedness evaluation beats eyeballing answers.

Evaluating RAG

Evaluate the halves separately, because one end-to-end score says something is wrong without saying what. For retrieval, annotate gold passage ids for 100 to 300 questions and measure recall at k — the fraction where a gold passage appears in the top k — plus mean reciprocal rank and nDCG at 10 for ordering. These numbers are cheap and stable, and they let you A/B a chunking change or reranker without invoking the generator.

For generation, the metrics that matter are faithfulness (is every claim supported by the retrieved context), answer relevance (does it address the question asked) and citation accuracy (do the cited chunks actually contain the support). LLM-as-judge is the practical way to measure these at scale, but it has known biases: it favours longer answers, it favours its own outputs, and it is sensitive to prompt wording. Calibrate the judge against a few hundred human labels before you trust its absolute numbers, and use it comparatively — variant A versus variant B on the same items — rather than as a fixed quality score.

Keep a regression set containing the questions the system currently fails, and run it on every chunking or model change. Failures are more informative than passes and accumulate into the most valuable artefact the project owns.

The cost and latency arithmetic

Ingestion is dominated by embedding. A million chunks averaging 400 tokens is 400 million tokens; at roughly two cents per million tokens that is about eight dollars, and storage at 1,024 dimensions in float32 is roughly 4 GB. Re-embedding after a model change costs the same again, which is another reason to choose the embedder deliberately.

Per-query cost is dominated by the generator's input. Eight chunks of 400 tokens plus instructions is roughly 3,500 prompt tokens; at fifteen cents per million that is about half a cent, with a few hundred output tokens on top. Query embedding, ANN search and rerank are rounding errors beside it. Latency is the harder constraint: 20 milliseconds to embed, 5 to 20 for the search, 50 to 150 to rerank, then generation from half a second to several. For sub-second responses, stream the answer and accept that the first token waits on retrieval.

Caching helps more than people expect. Exact-match question-to-answer caching is trivial; semantic caching needs a conservatively tuned threshold or it serves a subtly wrong answer to a slightly different question. Caching retrieval results keyed by normalised query and index version is always safe.

RAG versus long context versus fine-tuning

Long context is not a substitute for retrieval, but it changes the calculus at small corpus sizes. If the whole knowledge base is 40,000 tokens, stuffing it into every prompt is simpler than building an index, and prompt caching makes the repeated prefill cheap. It breaks down on three axes: cost scales with corpus size on every call, precision degrades as the window fills with irrelevant material, and access control becomes all-or-nothing.

Fine-tuning is the right tool for behaviour rather than knowledge: output format, tone, domain vocabulary, a classification task, a strict JSON schema. It is a poor tool for facts because facts change and weights do not, and because a fine-tuned model cannot cite. The two compose well — fine-tune for shape, retrieve for content — and that combination is what most mature systems converge on.

A stack you can build this week

Parse with a structure-aware extractor that preserves headings and tables. Chunk at 400 to 600 tokens on natural boundaries with 10 to 15 percent overlap. Embed with a strong general model at native dimension, normalise, and store in Postgres with pgvector if you already run Postgres, or Qdrant past a few million chunks. Keep raw text and metadata beside each vector. Add BM25, fuse with reciprocal rank fusion, rerank the top 50 with a cross-encoder, and pass the best 8 to the generator with numbered citations.

Then instrument it: log the query, the rewritten query, retrieved ids and scores, reranked order, prompt token count, answer and citations. Without that log you cannot diagnose a bad answer and every later improvement becomes guesswork. Build the fifty-question evaluation set before tuning anything, so tuning has a direction.

Common mistakes

  • Chunking by fixed character count across headings and tables, which severs answers from their context and produces chunks no human would cite.
  • Dense-only retrieval, which loses exact identifiers, error codes and rare names that lexical search would have caught.
  • Skipping the reranker while spending weeks on embedding-model selection, where the achievable gain is smaller.
  • Passing twenty chunks because more context feels safer, which dilutes attention and raises cost without raising accuracy.
  • Embedding the query with a different model or preprocessing than the corpus, then wondering why similarity scores are meaningless.
  • No refusal path: the prompt never authorises the model to say the context is insufficient, so it always answers.
  • Evaluating only the final answer, which cannot distinguish a retrieval failure from a generation failure.
  • Indexing documents without permission metadata, then filtering after retrieval — a leak waiting to happen.
Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.