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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Beginner Three promises

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.

Freshnesschange detection, deletion, version dates
Accessidentity, filters, live checks
Integritytrusted sources, injection limits
Costper stage measurement
Latencybudgets and fallbacks
Evidencelogs, tests, alerts
None of these is a feature of the model. All are properties of your system.
Intermediate Freshness and permissions

Freshness, incremental indexing and deletion

Set a target per source

SourceExample freshness targetChange detection
Access revocationsMinutes, or checked liveEvents or query-time check
Prices and operational statusDo not index: query liveTool call
TicketsAn hourWebhooks plus periodic sweep
PoliciesSame dayPublish events
ArchivesWeeklyScheduled 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

ApproachHowTrade-off
Early filteringAccess labels stored with chunks and applied in the searchFast; labels can lag behind the source
Late checkingAsk the source system about each candidateCurrent; slower and may leave few results
BothFilter early, confirm the final few liveA good default for sensitive content
Separate indexesOne per tenant or classificationStrong 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.
The agent must not be a shortcut

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.

Expert Integrity, cost and latency

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.

SituationRisk if ignoredTest
Nested groupsPeople wrongly excluded or includedA user two levels deep
Explicit denyA denied user sees the item through a groupDeny plus allow on one document
Inherited folder rightsMoving a file does not change index labelsMove a document and search
Anyone-with-link sharingTreated as visible to all staff in searchConfirm the intended policy
Disabled accountsOld sessions keep workingDisable and retry immediately
Attachments and commentsDifferent rights from the parentRestricted 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.

LayerControl
SourcesAllow-list them; separate editable community content from approved content
IngestionStrip hidden text, flag instruction-like passages, record the author
RetrievalPrefer authoritative sources; limit results from one document or author
PromptMark passages as data with identifiers
ActionsRestrict tools after untrusted content; require approval for consequences
OutputBlock unexpected links and remote images that could carry data out
MonitoringAlert 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.

LeverEffectCheck
Fewer, better passagesLess inputRecall at the new k
Trim passagesLess inputLost caveats
Prompt caching of stable instructionsCheaper repeated prefixCache hit rate
Route easy questions to smaller modelsLower unit priceQuality by category
Cache retrieval or answersSkips workPermissions and freshness in the key
Smaller or quantized vectorsCheaper indexRecall against exact search
Batch embeddingCheaper indexingFreshness lag
Skip retrieval when unnecessarySaves a stageWrong 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.

Semantic caches

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.
Illustrative example: the departed contractor

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

SignalWhy it mattersFirst response
Age of oldest unprocessed change, by sourceFreshness promise at riskCheck the connector and queue
Items hidden or removed per dayA sudden jump may mean a faulty sync; zero may mean deletions are ignoredCompare with the source's own records
Chunks without access labelsShould be zero among searchable itemsHide them and fix the mapping
Final live checks that refuse a candidateShows how far index permissions lagShorten the permission sync
Input tokens per questionMain cost driverLook at passage count and size
Questions with no usable evidenceContent gaps or retrieval faultsSample 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

  1. Disable the affected source or index path.
  2. Identify which users received which passages from retrieval logs.
  3. Purge caches and derived copies.
  4. Correct the mapping or content and rebuild.
  5. Notify owners and affected people as your obligations require.
  6. 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

Next steps