Slides · Production: cost, serving and observability

RAG security, reliability and release

RAG security, reliability and release

Who may see this? What if it breaks? How do I undo it? Three questions to ask of every box in a RAG system.

Concept

The expensive mistakes are security and release mistakes

  • A missing permission filter or a shared cache key shows one customer another customer’s data.
  • A dependency outage with no plan turns a slow reranker into a full outage.
  • An untested chunker change quietly breaks one document type for weeks.

Ask three questions about every box:

  1. Who may see this? Permissions travel with the data and are checked where data is fetched.
  2. What if it breaks? Decide before the incident what degrades first.
  3. How do I undo it? Every change ships with a version, a gate and a way back.

Numbers in this deck are illustrative unless a source is cited.

Diagram

Enforce permissions where chunks are fetched

Diagram: The diagram runs top to bottom.

hit, still valid

miss

Authenticated session: user, tenant, groups

Answer cache hit?

Return cached answer

Server builds the permission filter

Retrieve only chunks the user may read

Verify the final context again

Prompt and model

Diagram summary: The diagram runs top to bottom. Identity and groups come from the authenticated session, not from anything the user types. A cache lookup comes first and is partitioned by that identity, and a hit is validated before it is returned. On a miss the server builds a filter, retrieval touches only permitted chunks, and the final context is verified a second time before the model sees it.

OWASP’s entry on vector and embedding weaknesses lists permission-aware vector stores and logical partitioning of datasets as prevention, and warns of context leakage between users when groups share one vector database. It also recommends detailed logs of retrieval activity.

Source1 LLM08:2025 Vector and Embedding Weaknesses

Concept

A prompt is not a lock

  • Once restricted text is in the context, the only barrier left is the model choosing to follow an instruction.
  • Retrieved text is also untrusted input. OWASP defines indirect prompt injection as instructions arriving through external content such as websites or files, and says RAG and fine-tuning do not fully mitigate it. It is also unclear whether any prevention is fool-proof. OWASP’s sensitive-information page adds that a system-prompt rule limiting which data may be returned can be bypassed through prompt injection.
  • So reduce the blast radius: mark retrieved text as data, restrict the model’s tool permissions, filter outputs, vet ingestion sources.
  • Hence two checks outside the model: filter at retrieval, verify the final context.

See Guardrails, safety and prompt injection for the injection side in depth.

Sources2 LLM01:2025 Prompt Injection3 LLM02:2025 Sensitive Information Disclosure

Compare

Security and privacy checklist

ConcernControlWhat it prevents
Access controlPermissions stored as chunk metadata, filtered at query time, verified on the final contextA restricted document reaching the wrong user
Poisoned or hidden contentValidate documents before they enter the knowledge base, and ingest only from sources you have verifiedHidden instructions in ingested files (OWASP gives a resume with white-on-white text as an example)
PII and secretsRedact at ingestion or mask at output, encrypt, set retentionSensitive data stored or echoed
Deletion requestsReach vectors, caches and logs (check your legal duties)Deleted data living on in a copy
Audit and testsLog who retrieved what, test tenant isolationLeaks nobody notices
VendorsCheck data residency and terms for hosted models and embeddersData going where policy forbids

Source1 LLM08:2025 Vector and Embedding Weaknesses

Code

A cache that cannot cross a boundary

The lookup happens before retrieval, so the cache has two parts: a partition chosen from the session, and a validity check on the stored entry.

Python

def partition_key(tenant, groups):
    blob = json.dumps({"tenant": tenant, "groups": sorted(set(groups))},
                      separators=(",", ":"), sort_keys=True)
    return hashlib.sha256(blob.encode()).hexdigest()

def put(tenant, groups, question, answer, used):
    deps = dict(used)   # {doc_id: version_seen}, copied from the retrieved chunks' metadata
    entries[(partition_key(tenant, groups), normalise(question))] = {"answer": answer, "deps": deps}

def get(tenant, groups, question):
    e = entries.get((partition_key(tenant, groups), normalise(question)))
    if e is None: return None
    for d, version in e["deps"].items():
        cur = docs.get(d)
        if cur is None or cur["version"] != version: return None       # edited, deleted or ACL changed
        if cur["tenant"] != tenant or not (cur["groups"] & set(groups)): return None
    return e["answer"]
  • This is the exact-match part of a semantic cache. A semantic cache replaces normalise(question) with a nearest-neighbour search, and that search must run inside the partition.
  • At lookup time the document versions are not known, so they are stored on the entry as dependencies and checked on every hit. Record the version each chunk had when it was retrieved, not the current version at store time; otherwise a document edited during generation makes a stale answer look current. A coarser alternative is a tenant-wide corpus version in the key, which invalidates everything on each ingestion.
  • A change of a document’s permissions must bump its version, as ingestion does for any event. The permission re-check on a hit is a second guard if it does not.
TestResult
Same tenant and groups, question differs in case and spacing: hitpass
Other tenant, same question: misspass
User with an extra group (a different partition): misspass
Group order does not change the partitionpass
Document edited (version bump): misspass
Document edited after retrieval but before the answer is stored: misspass
Document permissions narrowed with a version bump: the user who lost access gets a misspass
Permissions narrowed without a version bump: the re-check still blocks itpass
Document deleted: misspass
An answer stored for the HR partition is invisible to another partitionpass

With the version and permission checks removed (keeping the deleted-document check), 4 of these 10 tests fail (edited, both narrowed cases, and the edit-before-store case). Recording the current version at store time instead of the retrieval-time version fails 1 test. The tests cover this logic only, on a toy store. A real service needs them against its real cache and vector database.

Compare

Finer keys are safer and hit less often

Cache designSafe againstCost
Question text onlyNothing: tenant B can receive tenant A’s answerHighest hit rate
Plus tenantCross-tenant leaksStill serves old answers after a permission or document change
Partition by tenant and groups, entries validated against document versions and permissionsBothFewer hits, bookkeeping for dependencies

Two design choices for the validity part:

  • Corpus version in the key: simple, but every ingestion run invalidates every entry.
  • Per-document dependencies on the entry: invalidate only what changed. Finer, but you must track them.

Deletion requests must also clear these caches.

Check yourself

Check: the permission service is slow

The service that looks up a user’s groups starts timing out. Retrieval would be faster without the group filter, and the dashboard shows rising latency.

  1. Is dropping the filter an acceptable degradation?
  2. What should the request do, and what should you watch?
Answer
  1. No. The filter belongs on the “never drop” list, because a degraded answer is a small quality loss but a leak is a security incident. The system fails closed.
  2. After a short timeout (and at most a retry or two, within a budget), return an error or a safe message instead of retrieving unfiltered. Optionally reuse recently verified group data only if your policy allows it. Watch the lookup’s error and latency rate and alert on it.

Compare

What fails, and the planned response

FailureMitigation
LLM provider outage or rate limitBounded retries with backoff and jitter, circuit breaker, fallback model or provider
Reranker downSkip rerank and serve hybrid results (degraded but available)
Vector DB slowTimeouts, replica failover, cached results
Empty or low-confidence retrievalAbstain, ask a clarifying question, or escalate
Runaway agent loopMaximum steps, token and time budgets
Stale indexFreshness monitor, alert on ingestion lag

AWS’s Builders’ Library notes that retries add load to a service that may already be overloaded, so retries are limited and given jittered, growing waits.

Source4 Timeouts, retries, and backoff with jitter

Worked example

Worked example: retries multiply across layers

Suppose three layers each try a failing call up to 3 times (1 original and 2 retries): the orchestrator calls the LLM gateway, which calls the provider client, which calls the provider.

Retry policyCalls reaching the provider for one failing request
Retries at one layer only (3 attempts)3
Retries at all three layers (3×3×33 \times 3 \times 3)27

A small simulation where every provider call fails reproduces both numbers. The AWS article describes the same multiplication for layered retries (its own example is five layers) and recommends capping retries, adding jitter to waits, and using a local retry budget (a token bucket), so a struggling dependency is not buried by its own clients.

AWS’s advice is to limit retries and handle failures earlier in the architecture. For this example that means retrying at one layer, keeping it bounded, and letting a circuit breaker stop calls when the dependency is clearly down.

Source4 Timeouts, retries, and backoff with jitter

Diagram

A circuit breaker stops the pile-up

Diagram: A breaker starts closed and passes calls through while counting failures.

failures reach threshold

wait period ends

trial call succeeds

trial call fails

Closed

Open

HalfOpen

Diagram summary: A breaker starts closed and passes calls through while counting failures. At a failure threshold it opens and rejects calls immediately. After a wait it goes half-open and tries one real call: success closes it again, failure reopens it.

Martin Fowler’s description gives the reason: callers waiting on an unresponsive supplier can exhaust resources and cause cascading failures. While the breaker is open, your RAG service fails fast and can switch to the fallback model instead of queueing.

Source5 CircuitBreaker

Diagram

Decide what degrades first, before the incident

Diagram: From a healthy system, each failure maps to a planned, safe degradation: unreranked hybrid results, a fallback model, or abstaining.

Rule for every failure:
never drop the filter,
never answer with no sources

Healthy system

Reranker down

LLM down

Weak retrieval

Hybrid, unreranked

Fallback model

Abstain or escalate

Diagram summary: From a healthy system, each failure maps to a planned, safe degradation: unreranked hybrid results, a fallback model, or abstaining. The rule box at the top, deliberately not linked to anything, applies to every branch: never respond to a failure by dropping the permission filter, or by answering with no retrieved sources, which risks hallucination.

Order by cost to the user: lose ordering quality first, then speed or model quality, and refuse before you guess or leak.

Check yourself

Check: the embedding service is down

New questions cannot be turned into query vectors. Your system also has a keyword (BM25) index with the same permission filter. Rank these three responses from best to worst and say why:

(a) Keyword-only retrieval with the filter, flagged as degraded. (b) Reuse the last cached retrieval results for the same question from any user, to stay fast. (c) Keyword-only retrieval with the filter removed because it is faster.

Answer

Best is (a): it keeps retrieval and the filter, losing only semantic matching. (b) can show a user chunks they may not read, and may be stale. (c) is the worst: it turns an availability problem into a data leak. Also plan for recovery: alert, and return to hybrid retrieval when the service passes health checks.

Compare

Watch the stages, not just the answer

Trace each request end to end (query, rewritten query, retrieved ids and scores, reranked order, prompt tokens, model, per-stage latency, cost, guardrail outcomes, answer, feedback). Dashboards specific to RAG:

SignalWhat it can reveal
Empty-retrieval rateIndex problem, filter too strict, query rewrite failing
Abstention rateRetrieval losing context, or the model being too cautious
Groundedness samplesAnswers drifting from the sources
Cache hit rateSavings, and a sudden jump can hint at a key bug
Ingestion lagStaleness against the freshness promise
Recall on the golden setRetrieval quality after any change

Tracing details: Observability and eval pipelines.

Diagram

Release through gates, with a way back

Diagram: A change first has to pass offline thresholds for quality, latency and cost on golden and regression sets.

no

yes

yes

no

Change: chunker, embedder, prompt, model

Offline eval

Thresholds met?

Reject

Shadow traffic, then canary

Online metrics healthy?

Full rollout

Roll back via alias or flag

Diagram summary: A change first has to pass offline thresholds for quality, latency and cost on golden and regression sets. It then runs on shadow traffic and a small canary. Healthy online metrics lead to full rollout, otherwise it is rolled back with an alias or feature flag.

The Google SRE workbook describes canarying as deploying a change to only part of a service for a limited time and evaluating it, and uses that evaluation to decide whether to proceed. For a bad canary it suggests pausing and rolling back, or involving a human.

Source6 Chapter 16: Canarying Releases

Compare

Shadow and canary answer different questions

AspectShadow trafficCanary
What happensA copy of live requests goes to the new versionA small share of real users is served by the new version
Who sees the outputNobody: Istio’s mirroring discards the mirrored responses (“fire and forget”)Real users
What it showsLatency, errors and cost on real inputs; answer differences only if the shadow service logs them itself, since the responses are discardedUser-facing quality and behaviour, compared with the control
RiskExtra load and model spend; side effects such as tool calls or writes must be disabled for shadow runs; no user sees the outputA small share of users sees any regression
Blind spotCannot show how users reactNeeds enough traffic and time to be representative

The SRE workbook advises that a canary be large enough and run long enough to represent the whole deployment, and that you judge it on a short list of metrics (it suggests a dozen at most).

Sources7 Mirroring6 Chapter 16: Canarying Releases

Code

An offline gate that fails closed

Python

THRESHOLDS = {                     # illustrative numbers
    "recall_at_5":       ("min", 0.85),
    "groundedness":      ("min", 0.90),
    "p95_first_token_s": ("max", 3.0),
    "cost_per_query":    ("max", 0.012),
    "abstention_rate":   ("max", 0.10),
}
RANGES = {"recall_at_5": (0, 1), "groundedness": (0, 1), "abstention_rate": (0, 1)}

def valid_number(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)

def offline_gate(metrics):
    if not isinstance(metrics, dict):
        return (False, ["metrics report is not a dict"])
    failures = []
    for name, (kind, limit) in THRESHOLDS.items():
        v = metrics.get(name)
        if not valid_number(v):
            failures.append(f"{name}: missing or not a finite number"); continue
        lo, hi = RANGES.get(name, (0, math.inf))
        if not lo <= v <= hi:
            failures.append(f"{name}: {v} outside [{lo}, {hi}]")
        elif kind == "min" and v < limit:
            failures.append(f"{name}: {v} < {limit}")
        elif kind == "max" and v > limit:
            failures.append(f"{name}: {v} > {limit}")
    return (len(failures) == 0, failures)
TestResult
All thresholds metpasses
One quality metric just under its floorblocked
Quality fine, latency over budgetblocked
A metric missing from the reportblocked
NaN, infinity, True or a string where a number belongsblocked
A negative cost, or a rate of 1.5blocked
No report at all (None), or a listblocked, no exception

Quality, latency and cost are all in one gate, so a gain that blows the latency budget cannot ship. Fail closed means anything the gate cannot read as a valid number blocks the release. The thresholds are made up for the example.

Math

When is a canary difference real?

ppool=p0n0+p1n1n0+n1p_{\text{pool}} = \frac{p_0 n_0 + p_1 n_1}{n_0 + n_1}SE=ppool(1−ppool)(1n0+1n1)\mathrm{SE} = \sqrt{p_{\text{pool}} \left(1 - p_{\text{pool}}\right) \left(\frac{1}{n_0} + \frac{1}{n_1}\right)}z=p1−p0SEz = \frac{p_1 - p_0}{\mathrm{SE}}
SymbolMeaning
p0p_0, n0n_0Rate of the metric (for example abstention) and request count in the control
p1p_1, n1n_1The same for the canary
SE\mathrm{SE}Standard error of the difference, assuming the usual normal approximation
zHow many standard errors apart the two rates are

This is a simple two-proportion check; it assumes requests are independent, and the cut-offs (z above 3 to roll back, 500 canary requests minimum) are illustrative choices, not standards.

Worked example

Worked example: same change, different traffic

The metric is the share of requests whose time to first token exceeds the 3 s target; the control rate is 5 percent in both cases. Compare a busy service and a quiet one, each with a 5 percent canary.

CaseControl nCanary nCanary ratep_poolSEzDecision
40,000 requests a day38,0002,0008.0%0.05150.00515.9Roll back
2,000 requests a day1,9001009.0%0.05200.02281.8Wait: too few requests

Both canaries saw a worse-looking rate, yet only the first is strong evidence. The second is 4 points above control but within noise, so the honest move is to keep the same small share running for longer, to collect more requests. Do not enlarge the share while the signal is worse: that exposes more users to a possible regression. It is not proof that the change is safe either. Small canaries cannot catch small regressions. The z values follow from the formula on the previous slide.

Check yourself

Check: a mild signal on a decent canary

A change passed the offline gate and shadow. The canary has 1,500 requests, the control 28,500. Thumbs-down rate: control 7.4 percent, canary 8.0 percent. Latency and cost are unchanged.

  1. Compute z.
  2. What do you do?
Answer
  1. ppoolp_{\text{pool}} is about 0.0743 and SE\mathrm{SE} about 0.0069, so z=0.0060.0069≈0.86z = \dfrac{0.006}{0.0069} \approx 0.86.
  2. That is well below the illustrative rollback line of 3, so there is no evidence of harm yet, and also no proof of safety for a 0.6 point shift. Keep the canary running under watch to gather more requests and look at slices before promoting; do not skip straight to full rollout, and do not roll back on this number alone.

Code

Version everything that can change

YAML

# release manifest (illustrative names)
release: 2026-10-23-a
prompt: support-answer@14
embedding_model: emb-v3
chunker: chunker@5
index: kb-v7              # alias kb-live points here
reranker: rerank@2
llm: provider-model-x     # pin an exact model id
cache_namespace: r-2026-10-23-a
feature_flags:
  new_reranker: 5%
  • Every item above can change behaviour, so every item goes through the same gate: offline eval, shadow, canary, rollback.
  • Treat prompt edits like code: version, review, test. Editing a live prompt in a console skips all of that.
  • Rollback means restoring the previous manifest (alias back, flag off), which only works if the old versions are still around.
  • Putting a version in the cache namespace keeps old answers from being served after a change.

Compare

Six recurring failure patterns

These are common patterns, not reports of specific incidents.

PatternFix
Silent staleness: ingestion fails and answers driftFreshness target and an alert on ingestion lag
Embedding model swapped without re-indexingVersion the model; use the alias swap
Access-control bug: a restricted document retrievedFilter at retrieval, test it, audit
Cross-tenant cache hitPartition the cache by tenant and permissions, and validate document versions on every hit
Chunker change hurts tablesA regression set that gates the change
Cost spike from agent loops or growing contextStep and token budgets, per-tenant cost alerts

Pick the two patterns that worry you most in your own system. For each, what signal would you want on a dashboard before it happens?

Process

A 45-minute whiteboard order

  1. Requirements and scale.
  2. Data sources and freshness.
  3. Ingestion, chunking and embedding.
  4. Index choice and sizing.
  5. Retrieval: hybrid, rerank, filters.
  6. Generation and prompting.
  7. Guardrails and security.
  8. Latency and cost budget.
  9. Evaluation plan and observability.
  10. Failure modes and rollout.

Say the trade-off at every box.

Provenance: generated practice. A suggested structure, not a verified interview format for any company.

Summary

Recap

  • Enforce permissions at retrieval and verify on the final context; a prompt is not a lock.
  • Partition caches by tenant and permissions, and validate document versions on every hit.
  • Decide in advance what degrades first: reranker before retrieval, and abstain rather than answer without sources. Never drop the filter.
  • Bounded retries, a circuit breaker and fail-closed gates.
  • Release through offline gate, shadow, canary and rollback, with every component versioned.

References

References & Sources (1 of 2)

  1. LLM08:2025 Vector and Embedding Weaknesses (opens in a new tab)

    OWASP GenAI Security Project2025Documentation

    Used for Permission-aware vector stores and logical partitioning, context leakage between groups sharing a vector database, validating knowledge sources (including hidden text in documents), and logging retrieval activity.

  2. LLM01:2025 Prompt Injection (opens in a new tab)

    OWASP GenAI Security Project2025Documentation

    Used for Indirect prompt injection arrives through external content; RAG and fine-tuning do not fully mitigate it; mitigations include separating untrusted content, least privilege and output filtering.

  3. LLM02:2025 Sensitive Information Disclosure (opens in a new tab)

    OWASP GenAI Security Project2025Documentation

    Used for A system-prompt restriction on which data may be returned can be bypassed through prompt injection, so it is not an access control.

  4. Timeouts, retries, and backoff with jitter (opens in a new tab)

    Amazon Web Services (Builders' Library, AWS Builder Center)2019Article

    Used for Retries add load to an overloaded service; limit retries, add jitter to waits, and use a local retry budget.

  5. CircuitBreaker (opens in a new tab)

    Martin Fowler2014Article

    Used for The closed, open and half-open states of a circuit breaker and why it prevents cascading failures.

References

References & Sources (2 of 2)

  1. Chapter 16: Canarying Releases (opens in a new tab)

    Alec Warner, Štěpán Davidovič2018Book

    Used for Canarying is a partial, time-limited deployment plus its evaluation; the canary should be sizeable and long enough to be representative; judge it on a short list of metrics; roll back or call a human on a bad canary.

  2. Mirroring (opens in a new tab)

    Istio2026Documentation

    Used for Traffic mirroring sends a copy of live traffic out of band and discards the mirrored responses (fire and forget).