Sub topic 17
Running RAG in production
This chapter covers what changes when a RAG system moves from a notebook to real users. It assumes you have read the earlier chapters on ingestion, retrieval, prompt assembly, and evaluation. It also assumes you know basic Python and how to call APIs.
What changes in production
A prototype answers questions from a fixed set of documents for one person. A production system has four extra problems. Documents change, users have different permissions, requests must be fast, and every request costs money.
Index freshness
The index is a copy of your sources, and copies go stale. Decide how fresh answers must be, then pick an update method.
- Full rebuild: simple, but slow and costly for large corpora.
- Incremental update: re-embed only documents whose content hash changed.
- Deletion handling: remove chunks of deleted documents, or the model will keep citing them.
Store a source id, a content hash, and an updated timestamp as metadata on every chunk. The hash lets you skip unchanged files.
import hashlib
def needs_update(doc_id, text, stored_hashes):
new_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
if stored_hashes.get(doc_id) == new_hash:
return False
stored_hashes[doc_id] = new_hash
return TrueRe-embed a document only when needs_update returns True. If you change the embedding model, you must re-embed everything, because vectors from different models are not comparable.
Access control
Retrieval can leak data. If a user cannot open a document, the system must not put its text in that user's prompt.
Filter by permission during retrieval, using metadata such as an allowed-groups field. Do not retrieve first and hide results afterward. Filtering after the fact can also leave you with fewer than k results.
Latency
Each stage adds time. Embedding the query, searching the index, reranking, and generation all count. Generation is usually the largest part.
- Cache embeddings for repeated queries.
- Retrieve a modest k, and rerank only that shortlist.
- Stream the answer so users see tokens early.
- Set timeouts and a fallback, such as returning the top passages if the model call fails.
Measure each stage separately, and track the 95th percentile, not only the average.
Cost
Cost comes from embedding documents, embedding queries, and model tokens. The prompt is the main lever. Every extra passage adds input tokens to every request.
| Lever | Effect |
|---|---|
| Lower k | Fewer prompt tokens, but risk of missing evidence |
| Smaller chunks | Less wasted context per passage |
| Response caching | No model call for repeated questions |
| Smaller model for easy queries | Lower cost per request |
Monitoring
Log the query, the retrieved chunk ids, and the answer, taking care with private data. Track the metrics from the evaluation chapter on live traffic. Add user feedback and the rate of "I don't know" answers. A rising refusal rate often means the index is stale or documents are missing.
Exercise
A user in the sales group asks a question. The top retrieved chunk comes from an HR-only document. You filter the chunk out after retrieval, and the system returns only 2 of the 5 passages you wanted. What is the better design, and why?
Show answer
Apply the permission filter inside the search, using metadata, so the index returns the top 5 passages the user is allowed to see. Filtering afterward wastes retrieval slots and returns too few results. Filtering inside the search also keeps restricted text out of any intermediate step, such as reranking or logs.
Exercise
You switch to a newer embedding model and only embed new documents with it. Retrieval quality drops. Why?
Show answer
Vectors from different models live in different spaces, so similarity scores between a new query vector and old document vectors are meaningless. Re-embed the whole corpus with the new model, and embed queries with the same model.