Slides · Production: cost, serving and observability
RAG security, reliability and release
1 / 26
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:
- Who may see this? Permissions travel with the data and are checked where data is fetched.
- What if it breaks? Decide before the incident what degrades first.
- 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
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.
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.
Sources[2] LLM01:2025 Prompt Injection[3] LLM02:2025 Sensitive Information Disclosure
Compare
Security and privacy checklist
| Concern | Control | What it prevents |
|---|---|---|
| Access control | Permissions stored as chunk metadata, filtered at query time, verified on the final context | A restricted document reaching the wrong user |
| Poisoned or hidden content | Validate documents before they enter the knowledge base, and ingest only from sources you have verified | Hidden instructions in ingested files (OWASP gives a resume with white-on-white text as an example) |
| PII and secrets | Redact at ingestion or mask at output, encrypt, set retention | Sensitive data stored or echoed |
| Deletion requests | Reach vectors, caches and logs (check your legal duties) | Deleted data living on in a copy |
| Audit and tests | Log who retrieved what, test tenant isolation | Leaks nobody notices |
| Vendors | Check data residency and terms for hosted models and embedders | Data going where policy forbids |
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.
| Test | Result |
|---|---|
| Same tenant and groups, question differs in case and spacing: hit | pass |
| Other tenant, same question: miss | pass |
| User with an extra group (a different partition): miss | pass |
| Group order does not change the partition | pass |
| Document edited (version bump): miss | pass |
| Document edited after retrieval but before the answer is stored: miss | pass |
| Document permissions narrowed with a version bump: the user who lost access gets a miss | pass |
| Permissions narrowed without a version bump: the re-check still blocks it | pass |
| Document deleted: miss | pass |
| An answer stored for the HR partition is invisible to another partition | pass |
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 design | Safe against | Cost |
|---|---|---|
| Question text only | Nothing: tenant B can receive tenant A’s answer | Highest hit rate |
| Plus tenant | Cross-tenant leaks | Still serves old answers after a permission or document change |
| Partition by tenant and groups, entries validated against document versions and permissions | Both | Fewer 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.
- Is dropping the filter an acceptable degradation?
- What should the request do, and what should you watch?
Answer
- 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.
- 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
| Failure | Mitigation |
|---|---|
| LLM provider outage or rate limit | Bounded retries with backoff and jitter, circuit breaker, fallback model or provider |
| Reranker down | Skip rerank and serve hybrid results (degraded but available) |
| Vector DB slow | Timeouts, replica failover, cached results |
| Empty or low-confidence retrieval | Abstain, ask a clarifying question, or escalate |
| Runaway agent loop | Maximum steps, token and time budgets |
| Stale index | Freshness 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.
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 policy | Calls reaching the provider for one failing request |
|---|---|
| Retries at one layer only (3 attempts) | 3 |
| Retries at all three layers (3×3×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.
Diagram
A circuit breaker stops the pile-up
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.
Source[5] CircuitBreaker
Diagram
Decide what degrades first, before the incident
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:
| Signal | What it can reveal |
|---|---|
| Empty-retrieval rate | Index problem, filter too strict, query rewrite failing |
| Abstention rate | Retrieval losing context, or the model being too cautious |
| Groundedness samples | Answers drifting from the sources |
| Cache hit rate | Savings, and a sudden jump can hint at a key bug |
| Ingestion lag | Staleness against the freshness promise |
| Recall on the golden set | Retrieval quality after any change |
Tracing details: Observability and eval pipelines.
Diagram
Release through gates, with a way back
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.
Compare
Shadow and canary answer different questions
| Aspect | Shadow traffic | Canary |
|---|---|---|
| What happens | A copy of live requests goes to the new version | A small share of real users is served by the new version |
| Who sees the output | Nobody: Istio’s mirroring discards the mirrored responses (“fire and forget”) | Real users |
| What it shows | Latency, errors and cost on real inputs; answer differences only if the shadow service logs them itself, since the responses are discarded | User-facing quality and behaviour, compared with the control |
| Risk | Extra load and model spend; side effects such as tool calls or writes must be disabled for shadow runs; no user sees the output | A small share of users sees any regression |
| Blind spot | Cannot show how users react | Needs 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).
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)| Test | Result |
|---|---|
| All thresholds met | passes |
| One quality metric just under its floor | blocked |
| Quality fine, latency over budget | blocked |
| A metric missing from the report | blocked |
NaN, infinity, True or a string where a number belongs | blocked |
| A negative cost, or a rate of 1.5 | blocked |
No report at all (None), or a list | blocked, 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=n0+n1p0n0+p1n1SE=ppool(1−ppool)(n01+n11)z=SEp1−p0| Symbol | Meaning |
|---|---|
| p0, n0 | Rate of the metric (for example abstention) and request count in the control |
| p1, n1 | The same for the canary |
| SE | Standard error of the difference, assuming the usual normal approximation |
| z | How 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.
| Case | Control n | Canary n | Canary rate | p_pool | SE | z | Decision |
|---|---|---|---|---|---|---|---|
| 40,000 requests a day | 38,000 | 2,000 | 8.0% | 0.0515 | 0.0051 | 5.9 | Roll back |
| 2,000 requests a day | 1,900 | 100 | 9.0% | 0.0520 | 0.0228 | 1.8 | Wait: 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.
- Compute z.
- What do you do?
Answer
- ppool is about 0.0743 and SE about 0.0069, so z=0.00690.006≈0.86.
- 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.
| Pattern | Fix |
|---|---|
| Silent staleness: ingestion fails and answers drift | Freshness target and an alert on ingestion lag |
| Embedding model swapped without re-indexing | Version the model; use the alias swap |
| Access-control bug: a restricted document retrieved | Filter at retrieval, test it, audit |
| Cross-tenant cache hit | Partition the cache by tenant and permissions, and validate document versions on every hit |
| Chunker change hurts tables | A regression set that gates the change |
| Cost spike from agent loops or growing context | Step 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
- Requirements and scale.
- Data sources and freshness.
- Ingestion, chunking and embedding.
- Index choice and sizing.
- Retrieval: hybrid, rerank, filters.
- Generation and prompting.
- Guardrails and security.
- Latency and cost budget.
- Evaluation plan and observability.
- 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)
LLM08:2025 Vector and Embedding Weaknesses (opens in a new tab)
OWASP GenAI Security Project2025Documentation
https://genai.owasp.org/llmrisk/llm082025-vector-and-embedding-weaknesses/
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.
LLM01:2025 Prompt Injection (opens in a new tab)
OWASP GenAI Security Project2025Documentation
https://genai.owasp.org/llmrisk/llm01-prompt-injection/
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.
LLM02:2025 Sensitive Information Disclosure (opens in a new tab)
OWASP GenAI Security Project2025Documentation
https://genai.owasp.org/llmrisk/llm022025-sensitive-information-disclosure/
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.
Timeouts, retries, and backoff with jitter (opens in a new tab)
Amazon Web Services (Builders' Library, AWS Builder Center)2019Article
https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter
Used for Retries add load to an overloaded service; limit retries, add jitter to waits, and use a local retry budget.
CircuitBreaker (opens in a new tab)
Martin Fowler2014Article
https://martinfowler.com/bliki/CircuitBreaker.html
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)
Chapter 16: Canarying Releases (opens in a new tab)
Alec Warner, Štěpán Davidovič2018Book
https://sre.google/workbook/canarying-releases/
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.
Mirroring (opens in a new tab)
Istio2026Documentation
https://istio.io/latest/docs/tasks/traffic-management/mirroring/
Used for Traffic mirroring sends a copy of live traffic out of band and discards the mirrored responses (fire and forget).
Keys: ← → move, Home End first and last, F full screen.