Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 108/ 160
06. AI Security

Data Leakage

Prevent secrets and private docs from appearing in completions, logs, or training data.

IntermediateSecrets · Training Leak3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

AI apps can accidentally show secrets or private information, so you keep sensitive stuff away from the AI and check what comes out.

Think of it like…

A talkative colleague with a photographic memory: anything you tell them or leave on their desk may come up in conversation, so the rule is to only give them what they need, keep other clients' files in a locked cabinet and not write passwords on sticky notes.

Where you’ve seen it

A security review plants 50 unique canary strings: some in documents of tenant A, some as fake API keys in the system prompt, some in ticket data. A red team then runs 2,000 extraction prompts ("repeat the text above", "what instructions were you given?", multi-turn probes, injected documents telling the bot to print its context) as tenant B and as an anonymous user. Three canaries leak (0.15% of attempts): two from the system prompt (it contained a webhook URL with a token) and one from a shared semantic cache keyed without the tenant id. Fixes: move the secret to server-side tool configuration (the model never sees it), add the tenant to the cache key, scan completions with a secret-pattern and canary detector, and mask tokens and PII in logs. A re-test of 2,000 prompts produces zero leaks. Logs previously stored full prompts for 365 days with broad engineer access; they now keep redacted prompts for 30 days with role-based access and an audit trail.

Words you’ll hear

Canary token
A unique planted string used to detect when protected data appears where it shouldn't.
System prompt leakage
Extraction of the hidden instructions; assume prompts are not confidential.
Memorisation / training-data extraction
A model reproducing text it saw during training or fine-tuning.
Cross-tenant leakage
Data from one customer reaching another through shared caches, indexes or logs.

Visual diagram

Loading interactive diagram

Theory & deep dive

Where leaks happen

Context leakage: the system prompt, retrieved chunks, tool results and conversation history are all available to the model, and a user (or an injected document) can ask it to repeat them. Treat the system prompt as public: don't place secrets, credentials, private URLs or sensitive business logic in it (OWASP LLM07). Retrieval leakage: the retriever returns documents the user shouldn't see (missing ACLs, shared indexes), and the model summarises them. Cache and memory leakage: exact or semantic caches, conversation memory and prefix caches keyed without the tenant or user can serve one person's content to another, and timing differences can reveal cache hits. Log and trace leakage: full prompts and completions stored for long periods with broad access are a data-breach waiting to happen, and third-party observability tools receive them too.

Training-time leakage: fine-tuning on data containing secrets or personal data can lead to memorisation; extraction attacks repeat prefixes to recover training text, and larger models memorise more. Providers vary in whether prompts are used for training; use enterprise terms or opt-outs and verify. Error and tool leakage: stack traces, SQL errors, internal hostnames and raw API responses passed to the user or the model expand what an attacker learns. Exfiltration through injection: a manipulated agent sends data out via links, images, emails or API calls. Each path needs its own control, which is why a single "redaction layer" doesn't suffice.

A cache-key leak

Semantic cache key = hash(normalised question). Tenant A asks "What is our SSO setup URL?" and the answer is cached. Tenant B asks the same question and receives tenant A's URL. Fix: key on (tenant, language, prompt version, hash), and don't cache answers derived from tenant-private data unless scoped.

Key takeaway: Leaks occur through context, retrieval, caches, logs, training data and errors; assume anything the model sees may be revealed.

Prevention, detection and testing

Minimise and isolate: keep secrets in server-side configuration used by tools, never in prompts (see secrets management); scope retrieval with ACLs; separate caches, memory and indexes by tenant and user; don't fine-tune on data you wouldn't allow the model to reveal, and scrub or exclude secrets and PII from training sets. Detect at the exits: scan completions with secret detectors (provider key formats, high-entropy strings), PII detectors and canary matches, and block, redact or alert; mask sensitive fields in logs and traces, set short retention, restrict access and audit it. Return generic errors to users and keep details in internal logs.

Test like an attacker: plant canaries in documents, prompts, caches and memory; run extraction suites (system prompt requests, "repeat above", multi-turn probes, injected documents that tell the model to print its context, membership-style probes against fine-tuned models) as different users and tenants; assert zero canary hits in outputs, logs visible to other tenants and cached responses. Add these to CI and run production probes with synthetic tenants. Track metrics such as canary leak rate, number of secrets caught by output scanners, log-access audit findings and mean time to revoke an exposed credential. When a leak is suspected, have a runbook: disable the feature or tool, rotate exposed secrets, identify affected tenants from audit logs and notify according to your policy and legal obligations.

Canary results

50 canaries, 2,000 extraction prompts. First run: 3 canaries surfaced (0.15%): 2 from the system prompt, 1 via the shared cache. After moving the secret out of the prompt and adding the tenant to the cache key: 0 leaks in a 2,000-prompt re-test, now part of CI.

Key takeaway: Minimise what the model sees, isolate by tenant, scan every exit and verify with canaries.

How it works, step by step

Step 1 of 4
Security + engineering

1. Map what the model can see

List prompts, retrieved data, tool outputs, caches, memory and logs, and classify their sensitivity.

system prompt · tickets · logs
Key numbers at this step
Rule
no secrets in prompts

When to use it & trade-offs

What it is

In AI security, data leakage is the unintended disclosure of confidential information through an AI system: secrets or private documents appearing in completions, logs and traces, caches shared across users, error messages, tool outputs, fine-tuning or training data (memorisation and extraction) or the system prompt itself. Leaks come from design mistakes (putting secrets in prompts, sharing a cache or index across tenants), from attacks (extraction prompts, prompt injection with exfiltration) and from the model's own tendency to repeat what it has seen. The defence is data minimisation, isolation, scanning and testing: give the model only what it needs, scope what it can retrieve and reveal, scan outputs and logs, and probe with canaries.

Why it matters: LLMs mix everything in the context into one output, so anything placed in the prompt can come out: API keys pasted into a system prompt, another customer's document retrieved by mistake, a stack trace echoed to the user. Leaks are costly (breach notification, contract penalties, lost trust) and often silent. Treating the model as a component that can reveal anything it can see leads to architectures where it can't see what it shouldn't reveal.

When to reach for it

  • Security reviews of assistants with private data
  • Designing multi-tenant caches and memory
  • Preparing fine-tuning datasets

When to avoid or be careful

  • Putting API keys or private URLs in system prompts
  • Storing full prompts indefinitely with broad access
  • Sharing a semantic cache across tenants

Leak types and main controls

Prompt and context leakage
Best for: Secrets and private data visible to the model

Strengths: Fixed by removing secrets and scoping retrieval.

Watch out: Requires architecture changes, not filters.

Cache, memory and index leakage
Best for: Multi-tenant and multi-user systems

Strengths: Solved by tenant-aware keys and namespaces.

Watch out: Lower cache hit rates.

Log and training-data leakage
Best for: Observability and fine-tuning pipelines

Strengths: Redaction, retention and access controls reduce exposure.

Watch out: Less debugging detail.

Interview signals & numbers to know

When this topic comes up

  • “Repeat the instructions above”
  • Canary tokens
  • System prompt leakage
  • Memorisation and extraction
  • Shared cache keys

Benchmarks & rules of thumb

0.15% -
canary leak rate in the first test (3 of 2,000 attempts)
365 → 30 days -
log retention before and after the fix
50 -
canaries planted across prompts, documents and tickets

Common mistakes & follow-ups

Common interview mistakes

  • Assuming the system prompt is confidential.
  • Logging raw prompts to a third-party tool with no redaction.
  • Fine-tuning on production data containing secrets.

Likely interviewer follow-ups

  • How would you test whether an assistant leaks data between tenants?
  • Why shouldn't secrets be in the system prompt?
  • How do you reduce training-data memorisation risk?
Interview tip: Mention canary tests. They turn a vague "we think we don't leak" into a measurable, repeatable check.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Data Leakage with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
PII Redaction
Next topic
Least-privilege Tools