RAG Security, Freshness and Cost
The operating duties that decide whether a retrieval system can be trusted: current content, correct access, resistance to hostile documents and a bill you can explain.
Keep the index in step with its sources, including deletions and permission changes. Enforce access inside search from verified identity, isolate tenants, and treat every document as possibly hostile. Then control cost and latency by measuring each stage, sending fewer but better passages and caching only where permissions and freshness allow.
What you will learn: freshness targets and incremental indexing, deletion, permission-aware retrieval, tenant isolation, injection and poisoning risks, leak testing and cost and latency optimization.
Prerequisites: RAG Explained and Agentic RAG and Document Ingestion, Parsing and Chunking.
What users assume
People using a knowledge assistant assume three things without being told: the answer reflects current documents, it shows only what they may see, and it will not be turned against them by something hidden in a file. A fourth assumption belongs to whoever pays: the cost is predictable. Each needs deliberate engineering.
Freshness, incremental indexing and deletion
Set a target per source
| Source | Example freshness target | Change detection |
|---|---|---|
| Access revocations | Minutes, or checked live | Events or query-time check |
| Prices and operational status | Do not index: query live | Tool call |
| Tickets | An hour | Webhooks plus periodic sweep |
| Policies | Same day | Publish events |
| Archives | Weekly | Scheduled comparison |
These are illustrations; set your own with content owners, and measure the actual lag.
Change, delete, reconcile
- Update only what changed, using stable identifiers and content hashes.
- Handle deletion as a first-class event. Hide the item immediately, then remove it physically.
- Reconcile on a schedule: compare the identifiers in the source with those in the index, because events get lost.
- Remove derived data too: embeddings, summaries, graph edges, cached answers and exported test sets.
- Show effective dates in answers, so users can judge currency.
"""Sync deletions and permission changes, then test that nothing leaks."""
source = { # the system of record: doc -> (tenant, groups, text)
"pay": ("acme", {"hr"}, "Salary bands"),
"faq": ("acme", {"staff"}, "Holiday FAQ"),
"road": ("acme", {"staff"}, "Draft roadmap"),
"faq2": ("globex", {"staff"}, "Globex FAQ"),
}
index = {}
def sync():
changes = []
for doc, (tenant, groups, text) in source.items():
new = (tenant, frozenset(groups), text)
if index.get(doc) != new:
changes.append(("upsert", doc))
index[doc] = new
for doc in [d for d in index if d not in source]:
changes.append(("delete", doc))
del index[doc]
return changes
def search(tenant, groups, live_check=True):
hits = [d for d, (t, g, _) in index.items() if t == tenant and g & groups]
if live_check: # ask the source again before showing anything
hits = [d for d in hits if d in source and source[d][1] & groups]
return sorted(hits)
sync()
print("before:", search("acme", {"staff"}))
source.pop("faq") # deleted at the source
source["road"] = ("acme", {"leads"}, "Draft roadmap") # access narrowed
print("stale index :", search("acme", {"staff"}, live_check=False))
print("live check :", search("acme", {"staff"}))
print("sync :", sync())
print("after sync :", search("acme", {"staff"}, live_check=False))
assert "faq2" not in search("acme", {"staff", "hr", "leads"})
assert "pay" not in search("acme", {"staff"})
print("leak tests passed")
Output:
before: ['faq', 'road']
stale index : ['faq', 'road']
live check : []
sync : [('upsert', 'road'), ('delete', 'faq')]
after sync : []
leak tests passed
Between a change at the source and the next synchronization, the stale index still returns a deleted page and one whose access was narrowed. The live check closes that window by asking the source before showing a result. After synchronization the index agrees again. The assertions at the end are the smallest form of a leak test; keep them running.
Permission-aware search and tenant isolation
Where to enforce
| Approach | How | Trade-off |
|---|---|---|
| Early filtering | Access labels stored with chunks and applied in the search | Fast; labels can lag behind the source |
| Late checking | Ask the source system about each candidate | Current; slower and may leave few results |
| Both | Filter early, confirm the final few live | A good default for sensitive content |
| Separate indexes | One per tenant or classification | Strong boundary; more to operate |
Rules that hold
- Take identity from the authenticated session; never from the question or a model argument.
- Make tenant a required parameter of the search function.
- Map groups and inherited permissions carefully, including links shared with individuals.
- Deny when permission information is missing or the check fails.
- Filter before reranking, summarizing, logging or caching.
- Include permission scope in every cache key.
An indexer usually reads everything with a powerful service account. Search then has to restore the limits that the account ignores. If it fails, the assistant becomes the easiest way to read any file in the company. It will also surface files that were shared too widely long ago, so review oversharing before launch.
Mapping permissions correctly
Source systems express access in different ways: groups inside groups, inheritance from folders, explicit denials, sharing links and temporary grants. A connector that handles only direct group membership will be wrong in quiet ways. Write down the rules for each source, then test them with real examples chosen with the system's administrator.
| Situation | Risk if ignored | Test |
|---|---|---|
| Nested groups | People wrongly excluded or included | A user two levels deep |
| Explicit deny | A denied user sees the item through a group | Deny plus allow on one document |
| Inherited folder rights | Moving a file does not change index labels | Move a document and search |
| Anyone-with-link sharing | Treated as visible to all staff in search | Confirm the intended policy |
| Disabled accounts | Old sessions keep working | Disable and retry immediately |
| Attachments and comments | Different rights from the parent | Restricted comment on a public page |
Where a source offers a way to ask "may this user read this item now?", use it for the final confirmation. Where it does not, shorten the synchronization interval for permissions and prefer separate, narrowly populated indexes for sensitive material.
Hostile and poisoned content
A retrieved passage is input to a model that follows instructions. Text hidden in a web page, email or uploaded file can attempt to redirect the agent: this is indirect prompt injection. Separately, an attacker who can add documents can plant false facts crafted to be retrieved for particular questions. The PoisonedRAG study demonstrated that a small number of injected texts can steer answers to chosen targets in its test settings.
| Layer | Control |
|---|---|
| Sources | Allow-list them; separate editable community content from approved content |
| Ingestion | Strip hidden text, flag instruction-like passages, record the author |
| Retrieval | Prefer authoritative sources; limit results from one document or author |
| Prompt | Mark passages as data with identifiers |
| Actions | Restrict tools after untrusted content; require approval for consequences |
| Output | Block unexpected links and remote images that could carry data out |
| Monitoring | Alert on a new document that suddenly dominates retrieval |
No filter catches every injection. Design so that a successful one can do little. See Excessive Agency, Exfiltration and Privilege Escalation and Supply Chain and Retrieval Poisoning.
Protect the stores themselves
The index holds copies of your most useful content. Give it the same encryption, network restrictions, access reviews and backup care as the source. Do not assume embeddings are anonymous: research has shown that substantial information about the original text can be recovered from them in some settings.
Cost and latency optimization
Know where the money goes
"""Where RAG money goes. Prices are invented units: put your own in."""
PRICE = {"input": 2.00, "output": 10.00, "embed": 0.02, "rerank": 1.00}
# per million tokens per 1,000 searches
def per_query(chunks, chunk_tokens, answer_tokens, rerank, cache_hit=0.0):
prompt = 800 + 40 + chunks * chunk_tokens # rules + question + evidence
parts = {
"embed query": 40 * PRICE["embed"] / 1e6,
"rerank": PRICE["rerank"] / 1000 if rerank else 0.0,
"model input": prompt * PRICE["input"] / 1e6,
"model output": answer_tokens * PRICE["output"] / 1e6,
}
return {k: v * (1 - cache_hit) for k, v in parts.items()}
SETUPS = {
"top 20, no rerank": per_query(20, 500, 300, rerank=False),
"rerank to 5": per_query(5, 500, 300, rerank=True),
"rerank to 5 + cache": per_query(5, 500, 300, rerank=True, cache_hit=0.3),
}
for name, parts in SETUPS.items():
total = sum(parts.values())
top = max(parts, key=parts.get)
print(f"{name:20} per 1,000 queries {total * 1000:6.2f} largest: {top}")
Output:
top 20, no rerank per 1,000 queries 24.68 largest: model input
rerank to 5 per 1,000 queries 10.68 largest: model input
rerank to 5 + cache per 1,000 queries 7.48 largest: model input
The prices are invented units, so only the shape matters. In this example the model's input dominates, and reranking pays for itself by sending five passages instead of twenty. That holds only if five passages answer as well, which your evaluation must confirm. Replace the numbers with your providers' prices and your measured token counts, and add indexing, storage and judge costs, which this per-query view leaves out.
| Lever | Effect | Check |
|---|---|---|
| Fewer, better passages | Less input | Recall at the new k |
| Trim passages | Less input | Lost caveats |
| Prompt caching of stable instructions | Cheaper repeated prefix | Cache hit rate |
| Route easy questions to smaller models | Lower unit price | Quality by category |
| Cache retrieval or answers | Skips work | Permissions and freshness in the key |
| Smaller or quantized vectors | Cheaper index | Recall against exact search |
| Batch embedding | Cheaper indexing | Freshness lag |
| Skip retrieval when unnecessary | Saves a stage | Wrong skips |
Latency
Measure each stage at the slow end of the distribution. Run independent searches in parallel, set timeouts with a stated fallback and stream the answer. Agentic loops multiply latency, so cap searches per question. A fallback must never skip the permission check; if that check is unavailable, fail closed.
Returning a stored answer for a "similar" question saves money and invites mistakes: similar questions can differ in the one word that matters. Restrict such caches to public, stable answers and keep permissions and source versions in the key.
A cost review routine
Once a month, take the total spend and divide it by answered questions and by useful answers, judged from sampled reviews and feedback. Break it into indexing, search, reranking, generation and evaluation. Look for sources that are indexed but never retrieved, questions that trigger many searches and prompts that have grown since the last review. Each finding becomes one change tested against the same question set, so that savings never arrive with an unnoticed drop in quality. Agent FinOps, Budgets and Chargeback describes budgets and ownership.
Tests and alerts
- Canary documents in each tenant that must never appear elsewhere.
- A revoked user loses access within the promised time.
- A deleted document disappears from search, caches and answers.
- Injected instructions in a test document cause no restricted action.
- Alerts for indexing lag, failed connectors, reconciliation differences and cost per question.
A contractor's access ends on Friday. The document system updates at once, but the index refreshes nightly. Because the assistant confirms the final passages against the source, nothing restricted appears in the gap. The weekly reconciliation then finds forty documents whose labels had never synchronized, which the team fixes and turns into a monitored check.
What to put on the dashboard
| Signal | Why it matters | First response |
|---|---|---|
| Age of oldest unprocessed change, by source | Freshness promise at risk | Check the connector and queue |
| Items hidden or removed per day | A sudden jump may mean a faulty sync; zero may mean deletions are ignored | Compare with the source's own records |
| Chunks without access labels | Should be zero among searchable items | Hide them and fix the mapping |
| Final live checks that refuse a candidate | Shows how far index permissions lag | Shorten the permission sync |
| Input tokens per question | Main cost driver | Look at passage count and size |
| Questions with no usable evidence | Content gaps or retrieval faults | Sample and classify |
Set each alert with an owner and a written first step. A dashboard that nobody is expected to act on becomes decoration, and the first person to learn of a leak or a stale policy will then be a user.
When something goes wrong
- Disable the affected source or index path.
- Identify which users received which passages from retrieval logs.
- Purge caches and derived copies.
- Correct the mapping or content and rebuild.
- Notify owners and affected people as your obligations require.
- Add a test that would have caught it.
Common mistakes
- Copying content but not permissions.
- Handling additions but not deletions.
- Filtering after generation.
- Caching answers across users.
- Cutting cost without measuring quality.
- Trusting internal documents completely.
Review this list whenever you add a source. A new connector brings its own permission model, change signals and kinds of content, so assumptions proven for the first source do not automatically hold for the next one.
Checklist
- Each source has a freshness target that is measured.
- Deletion and revocation are tested end to end.
- Reconciliation runs on a schedule.
- Identity is verified and filters run inside search.
- Missing permission data means no access.
- Untrusted content cannot trigger consequential actions.
- Cost and latency are tracked per stage.
- Caches respect permissions and versions.
Frequently asked questions
Is an internal knowledge base safe from injection?
Safer, not safe. Emails, tickets, uploaded files and shared pages let outsiders or careless insiders add text. Keep the action limits in place.
How fresh must an index be?
As fresh as the decisions made from it require. Values that change by the minute should be queried live instead of indexed.
One index or many?
Separate indexes give clearer boundaries for tenants and classifications. Shared indexes with enforced filters scale to many small groups. Test whichever you choose.
Where should I cut cost first?
Measure first. In many systems the number and size of passages sent to the model is the largest controllable item.
References and further reading
- OWASP Top 10 for LLM applications
- Zou et al.: PoisonedRAG
- Greshake et al.: Indirect prompt injection
- Morris et al.: Text embeddings reveal almost as much as text
- pgvector documentation, including filtering
- Claude documentation: Prompt caching
Next steps
Build a RAG Knowledge Assistant
Build an assistant with these controls in place.
Agent Threat Model and OWASP Agentic Risks
Map the threats across the whole agent.
Reducing Tokens, Tool Calls and Spend
Go further on spending.