Sub topic 17
Running RAG in Production
This chapter assumes you can read basic Python and that you have built a small RAG pipeline: ingestion, chunking, embeddings, top-k retrieval, and a grounded prompt. It also assumes you have measured retrieval and answer quality separately, as covered in the evaluation and failure-mode chapters. Here the question changes from "does it work?" to "does it keep working, safely, at a cost we can afford?"
What changes after the prototype
A prototype runs on a fixed set of documents, one user, and a patient reader. A production system has documents that change, many users with different permissions, a latency target, and a monthly bill. Four concerns account for most of the work:
- Freshness: the index must reflect the source documents.
- Access control: users must only see passages they are allowed to see.
- Latency: the whole request must finish quickly enough for the interface.
- Cost: embedding, storage, reranking, and generation all cost money.
A fifth concern, observability, cuts across the other four. You cannot fix what you cannot see.
Index freshness
An index goes stale when a source document is edited, moved, or deleted and the stored chunks still hold the old text. The model then cites outdated information with full confidence, and the citation looks legitimate.
Detect changes with content hashes
Store a hash of each document's cleaned text next to its chunks. On each sync, recompute the hash and compare. Only changed documents are re-chunked and re-embedded, which saves embedding cost.
import hashlib
def content_hash(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def plan_sync(source_docs, stored_hashes):
"""source_docs: {doc_id: text}. stored_hashes: {doc_id: hash}.
Returns which documents to add, update, and delete."""
current = {doc_id: content_hash(text) for doc_id, text in source_docs.items()}
added = [d for d in current if d not in stored_hashes]
updated = [d for d in current if d in stored_hashes and current[d] != stored_hashes[d]]
deleted = [d for d in stored_hashes if d not in current]
return added, updated, deleted
source = {"a": "refund policy v2", "b": "shipping times", "c": "new page"}
stored = {"a": content_hash("refund policy v1"),
"b": content_hash("shipping times"),
"d": content_hash("old page")}
print(plan_sync(source, stored))This prints (['c'], ['a'], ['d']). Document a changed, c is new, and d disappeared from the source.
Handle updates and deletes explicitly
An update is not an append. If you add the new chunks of document a without removing the old ones, both versions are retrievable. Give every chunk a doc_id in its metadata, and on update delete all chunks with that doc_id before inserting the new ones. Better, write the new chunks first and delete the old ones afterward, so a query that arrives mid-update still finds something.
Deletes matter most for legal and privacy reasons. If a document must be removed, confirm that its chunks, its embeddings, and any cached answers built from it are all gone.
Choose a sync schedule
| Approach | Staleness | Complexity | Fits when |
|---|---|---|---|
| Nightly full or incremental batch | Up to a day | Low | Documents change slowly |
| Event-driven (webhook or queue) | Seconds to minutes | Medium | Users expect recent edits |
| Query-time lookup of a live source | None | High, adds latency | A small set of fast-changing records |
Record an indexed_at timestamp and the embedding model name on every chunk. Both are needed later for debugging and for migrations.
Access control
A RAG system can leak data in a way the source systems never did. If the index holds every document and retrieval ignores who is asking, a user can ask a question and receive an answer built from a file they could never open.
Filter at retrieval time
Store access information as metadata on each chunk, such as allowed_groups. Apply the filter inside the search, before the top-k cut. Filtering after retrieval is a bug: the top 5 results might all be forbidden, leaving the user with nothing, or leaking through the model's answer if the filter is skipped.
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = sum(x * x for x in a) ** 0.5
nb = sum(y * y for y in b) ** 0.5
return dot / (na * nb) if na and nb else 0.0
def secure_top_k(query_vec, index, user_groups, k=3):
# index is a list of dicts: text, vector, allowed_groups (a set)
visible = [item for item in index if item["allowed_groups"] & user_groups]
scored = [(cosine(query_vec, it["vector"]), it["text"]) for it in visible]
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]
index = [
{"text": "Salary bands", "vector": [1.0, 0.0], "allowed_groups": {"hr"}},
{"text": "Holiday calendar", "vector": [0.9, 0.1], "allowed_groups": {"hr", "staff"}},
]
print(secure_top_k([1.0, 0.0], index, {"staff"}))A user in staff sees only the holiday calendar, even though the salary document is the closer match.
Keep permissions in sync
Permissions change as often as content. If you copy access lists into the index, a user who loses access still retrieves the document until the next sync. Two common fixes:
- Refresh the metadata on a short schedule, separate from the slower content sync.
- Store only a document id in the index, then check permissions against the source system for the final results before building the prompt.
The second option is more accurate and costs one extra call per request.
Other leak paths
- Logs and traces: if you log prompts for debugging, you are storing the retrieved passages. Apply the same access rules to logs.
- Caches: a cached answer for one user must not be served to another with different rights. Include the user's permission scope in the cache key.
- Prompt injection: a retrieved document can contain text like "ignore your instructions". Treat passages as data. Keep them clearly delimited in the prompt, and do not give the model tools that can act on its own output without checks.
Latency
A RAG request runs several steps in sequence. Measure each one separately, because the slowest step is often not the one you expect.
| Step | Typical contribution | Common fix |
|---|---|---|
| Query embedding | Tens of milliseconds | Cache repeated queries |
| Vector search | Milliseconds to tens of milliseconds | Approximate index, smaller `k` |
| Reranking | Often 100 ms or more | Rerank fewer candidates |
| Generation | Usually the largest share | Shorter prompt, smaller model, streaming |
Typical numbers vary a lot with hardware and provider, so measure your own.
Practical techniques:
- Stream the answer. Time to first token matters more to users than total time.
- Run independent steps in parallel. Keyword and vector search do not depend on each other.
- Trim the prompt. Fewer, better passages reduce both generation time and cost.
- Report percentiles. Track p50 and p95. An average hides the slow requests users remember.
Cost
Costs come from several places, and they scale differently.
- Ingestion: embedding every chunk once, again on every change. This is a one-time cost per chunk, so incremental sync keeps it low.
- Storage: vectors take memory or disk. A vector of 1,536 float32 values is about 6 KB, so 10 million chunks is roughly 60 GB before index overhead.
- Per query: the query embedding, reranking, and above all the generation tokens. Every retrieved passage you put in the prompt is billed on every request.
The largest lever is usually prompt size. Cutting k from 8 to 4 halves the context tokens. Check recall at k against the smaller value first, since the savings are not worth a drop in answer quality.
Other levers: a smaller embedding dimension, caching answers to frequent questions, and a cheaper model for simple queries.
Observability and quality over time
Log one structured record per request:
- the user's query and the rewritten query, if any
- the ids and scores of retrieved chunks
- the final prompt size in tokens
- timings for each step
- the answer, and whether the model refused
Retrieval quality drifts. Documents change, users ask new kinds of questions, and a model update can shift behavior. Keep a fixed set of test questions with known relevant documents, and run it on a schedule. The recall_at_k function from the evaluation chapter works well here. Alert when recall drops, and review a sample of real queries where the answer was a refusal, because these often reveal missing documents.
Collect user feedback such as thumbs up or down. Add failed queries to the test set so the same failure is caught next time.
A pre-launch checklist
- Every chunk carries
doc_id,indexed_at, embedding model name, and access metadata. - Updates and deletes are tested, including a deleted document that must no longer appear.
- Access filters apply inside the search, and a test confirms a user without rights gets no restricted text.
- Caches and logs respect permissions.
- p95 latency and cost per request are measured against targets.
- A scheduled evaluation run reports recall and answer quality.
- A plan exists for switching embedding models without downtime.
Exercise
A user loses access to an HR document at 9:00. Your index copies access lists from the source system and refreshes them nightly. Name the problem, and give two ways to reduce it.
Show answer
Until the next nightly refresh, the index still lists the user as allowed, so retrieval can return passages from the HR document and the model can quote them. To reduce it, refresh access metadata on a much shorter schedule than content, or store only a document id in the index and check permissions against the source system for the final results before building the prompt.
Exercise
You switch to a new embedding model and re-embed only the documents that changed this week. Search quality gets worse across the whole collection. Why, and what should you have done?
Show answer
Vectors from different embedding models are not comparable, so the index now mixes two vector spaces and similarity scores are unreliable. You should have built a complete new index with the new model beside the old one, evaluated it on the test questions, and then switched traffic to it.
Exercise
Your RAG service costs too much per request. Retrieval takes 30 ms and reranking takes 150 ms, but generation takes 2 seconds, and most input tokens come from 8 retrieved passages. What is the first change to try, and what must you check afterward?
Show answer
Reduce the number of passages sent to the model, for example from 8 to 4, perhaps after reranking so the best ones remain. This cuts input tokens, cost, and generation time. Afterward, check recall at the new k and answer quality on the test set, to confirm that the smaller prompt did not drop relevant passages.