Designing a RAG system¶
What you'll be able to do¶
- Draw the ingestion and query paths of a RAG system and name what each stage can silently get wrong.
- Choose chunking, hybrid retrieval and filtering settings, and enforce document permissions at retrieval time instead of in the prompt.
- Evaluate retrieval separately from generation, and plan a reindex when the embedding model changes.
RAG is two pipelines, not a prompt trick¶
Retrieval-augmented generation (RAG) gives a model passages from your own data at question time. It is two pipelines joined by an index: the ingestion path builds and updates the index, and the query path runs on every request under a latency budget.
A model cannot cite a passage the index never delivered. Data and retrieval failures are common enough that you should read the retrieved passages before changing the generation prompt.
| Situation | Better fit | Why |
|---|---|---|
| Users want documents, not an answer | Plain search | No generation step that can be wrong |
| Large or changing corpus, citations, per-user access | RAG | Update by re-indexing; send only permitted passages |
| Consistent style, format or skill | Fine-tuning | Changes behavior; poor for changing facts; removing a deleted document's influence may need retraining or separately validated unlearning |
| Small, stable corpus that fits the window | Long context | No index to build, but cost and latency grow with every token on every query |
Ingestion: the hidden hard part¶
Parsing is where quality is often lost: PDFs store positioned glyphs, not paragraphs, HTML mixes content with navigation, and a flattened table can lose its meaning. Read parsed output before tuning anything else. This is data pipeline discipline applied to documents.
Chunking strategies: fixed-size windows with overlap (the baseline), splitting by structure such as headings and whole tables, and semantic splitting (costlier; verify it beats the baseline). Small chunks match precisely but may lack context; large chunks dilute the embedding and waste prompt tokens. Overlap protects facts cut at a boundary, at the price of storing more chunks.
Metadata per chunk: source, section, timestamp, document version, ACL (who may read it) and embedding model version. Store it at ingestion; it is costly to reconstruct later.
Stable chunk IDs make re-ingestion an update, not a duplicate. Derive the ID from document ID, position and a content hash (see unique IDs), never a fresh random value per run:
import hashlib
doc_id, index, text = "handbook", 0, "Refunds take 5 days."
digest = hashlib.sha1(f"{doc_id}\0{index}\0{text}".encode()).hexdigest()[:12]
chunk_id = f"{doc_id}:{index}:{digest}"
print(chunk_id) # same inputs, same ID on every run
Upserting by ID is not enough. If a document shrinks from five chunks to two, at least the three removed chunks remain. If the surviving chunks' text changed, their IDs changed too, so all five old chunks can remain beside the two new ones. Build the new set first, so that a bad input cannot erase the document, then remove all of its old chunks and write the new ones. Handle deletion events, and periodically reconcile source document IDs against the index. Make the job idempotent (delivery and idempotency); comparing document hashes lets it skip re-embedding unchanged documents.
Retrieval: dense, lexical, hybrid¶
Dense retrieval finds the chunk vectors nearest the query vector, usually by cosine similarity. It finds paraphrases but can miss exact tokens such as error codes. Approximate indexes skip most vectors and trade some recall for speed (choosing a datastore). Raw vectors also cost memory.
Lexical retrieval (BM25) rewards matching terms, weighting rare ones more. It is strong where dense retrieval is weak, so hybrid search runs both. Their scores are not comparable, so fuse ranks with reciprocal rank fusion: score(d) = sum of 1 / (k + rank), with k = 60 a common default. Lexical ranking d1, d2, d3 and dense ranking d3, d1, d4 give:
| Chunk | Ranks | Score |
|---|---|---|
| d1 | 1, 2 | 1/61 + 1/62 = 0.03252 |
| d3 | 3, 1 | 1/63 + 1/61 = 0.03227 |
| d2 | 2 | 1/62 = 0.01613 |
| d4 | 3 | 1/63 = 0.01587 |
Pre-filtering restricts candidates during search; post-filtering takes the top k and then discards disallowed chunks. If a user may see 2% of chunks, k = 10, and relevance were independent of permission, expected survivors are 10 x 0.02 = 0.2, so most queries return nothing. Real data is correlated, but narrow-access users still suffer.
Reranking uses a cross-encoder-style model that reads query and chunk together: more accurate, but run per candidate, so the pattern is retrieve 50, rerank, keep 5. Query rewriting resolves follow-ups ("what about 2023?") but costs an LLM call and can drift from the user's intent.
Context assembly and generation¶
Context is a budget: choose the smallest k that holds recall on your eval set. Deduplicate chunks, order them sensibly, and label each so the model can cite [c3]; verify in code that every cited ID was supplied.
Design the "I don't know" path: tell the model to answer only from the context, and skip generation in code when no permitted results come back. If you add a relevance threshold, calibrate a real relevance score (a reranker's, say) on labeled answerable and unanswerable queries. Do not treat raw RRF scores as confidence: they come from ranks alone, so an irrelevant chunk ranked first by both searches still gets the maximum score. Retrieved text is also untrusted input: a document can say "ignore your instructions". Mark it as data, give the generation step no privileged tools that act on it, and validate outputs (security basics).
Permissions and tenancy¶
A model cannot be trusted to withhold text it has seen, so permissions belong in retrieval. Tag every chunk with its ACL, derive the caller's groups server-side (auth basics) rather than from a client-supplied filter, apply them as a pre-filter, and deny by default: a chunk with no ACL is visible to nobody. When permissions change, update chunk metadata or resolve access from the source of truth at query time.
| Index per tenant | Shared index with tenant filter | |
|---|---|---|
| Isolation | Structural | Only as good as every query's filter |
| Operations | Many indexes; easy per-tenant delete and reindex | One index; efficient for many small tenants |
| Failure | A mistake affects one tenant | One filter bug can leak across tenants |
Evaluating retrieval and generation separately¶
Build a labeled set of query to relevant chunk IDs. Stable IDs preserve labels for unchanged chunks; after document edits or rechunking, map or relabel the affected judgments before comparing recall. Recall@k is the fraction of relevant chunks in the top k, precision@k the fraction of the top k that is relevant, MRR the mean of 1 / rank of the first relevant result. Example: relevant {c3, c7}, results [c1, c3, c9, c7, c2].
| Metric | Arithmetic |
|---|---|
| recall@5 | 2 of 2 found = 1.0 |
| recall@3 | 1 of 2 found = 0.5 |
| precision@5 | 2 relevant of 5 = 0.4 |
| reciprocal rank | first hit at rank 2 = ½ |
| MRR over 3 queries (0.5, 1, 0) | 1.5 / 3 = 0.5 |
Judge generation separately: groundedness (is each claim supported by the context?) and correctness (does it match a reference?). Calibrate any judge model against human labels (evals as tests). For a bad answer, check in order: stale document, wrong chunking, not retrieved, retrieved but ignored.
Operating it¶
Latency is a sum of stages (latency and throughput). These are napkin numbers with assumptions marked; measure your own.
| Quantity | Arithmetic |
|---|---|
| Overlap storage (200-word chunks, 40 overlap) | step 160 words; 200 / 160 = 1.25x chunks |
| Vector memory (1,000,000 x 768 float32) | 1,000,000 x 768 x 4 B = 3,072,000,000 B, about 3.1 GB |
| Context budget (assumed 8,000-token window) | 8,000 - 500 prompt - 200 question - 1,000 answer = 6,300; at 300 tokens per chunk, 21 chunks |
| Time to first token (assumed stage costs) | 20 embed + 30 retrieve + 100 rerank (50 x 2 ms) + 600 until the model's first token = 750 ms |
| Reindex (1,000,000 chunks x 300 tokens) | 300,000,000 tokens to embed again |
Caching (caching and CDN) is safe only when the key and expiry cover everything the value depends on. Key an embedding cache on the exact model and preprocessing versions plus the exact input sent to the model. Retrieval and response caches also need the user's permission scope, the content (index) version and an expiry; a response cache must cover the prompt and model versions and any user-specific input.
Cost drivers are embedding tokens, vector memory, reranker calls and prompt tokens. Monitor empty-result rate, top-score distribution and citation validity, and log query, filters, chunk IDs and versions so a thumbs-down becomes a labeled example (observability and SLOs). If the index is down, degrade deliberately (lexical-only, or an honest "search is unavailable"), never a silent answer from model memory presented as grounded.
Vectors from different embedding models are not comparable. To change models, build a versioned index (chunks_v2): backfill it, dual-write new changes, replay shadow queries on the labeled set, cut over by flipping a pointer, and keep the old index for rollback.
For AI engineers
Your notebook does embed, top-k, prompt. The engineering problem hiding in it is that the index is a database with freshness, permissions and versions. When an answer is wrong, read the retrieved chunks before editing the prompt. Track retrieval metrics on a labeled set like a loss curve, and treat an embedding change as a migration with a rollback plan.
Common mistakes¶
- Choosing a chunk size without reading chunks from your own documents.
- Storing no metadata or ACLs, then enforcing permissions by prompting the model.
- Swapping the embedding model without reindexing.
- Evaluating only the final answer, so a retrieval regression looks like "the model got worse".
- Post-filtering by permission, or ignoring deletes, so users get empty results or see removed documents.
- Stuffing the context window; trusting retrieved text as instructions.
Check yourself¶
A user who can see 2% of the corpus gets "no results" for answerable questions. The code retrieves top 10, then filters by permission. Diagnose and fix.
Post-filtering: the top 10 are mostly chunks the user cannot see. Apply the permission filter inside each search, then take top k.
A document shrinks from five chunks to two. After re-ingestion by upserting chunk IDs, answers still quote removed text. Why?
An upsert only writes the two new chunks. At least the three removed chunks remain, and if the first two changed, their content-hash IDs changed too, so all five old chunks may survive. Remove all of the document's old chunks, then write the new set.
A teammate changes the embedding model in config and redeploys. Recall collapses. Why, and what should the rollout have been?
Queries now live in a different vector space than the stored chunks. Build a versioned index, dual-write, compare on the labeled set, then cut over.
The correct chunk is at rank 2 and recall@5 is 1.0, but the answer is wrong. Which failure class is this, and what do you inspect?
Retrieved but ignored: inspect chunk order, duplicates, missing context in the chunk, and the prompt.
Lab¶
Build a tiny RAG retrieval stack in code/rag-system-design/. Implement chunking with stable IDs, reciprocal rank fusion, recall@k, MRR and BM25 with filters. Then write idempotent ingest and delete, and a hybrid retrieve that cannot leak chunks a user lacks access to. The embedding is a deterministic toy, so everything runs offline. Run: cd code/rag-system-design && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Designed to Scale: caching and indexes.
- PostgreSQL documentation for full-text search as a lexical baseline.
- Related lesson: LLM reliability and cost.