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 107/ 160
06. AI Security

PII Redaction

Detect and mask personal data in prompts, logs, and retrieved context.

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

In plain words

PII redaction finds private details like names and card numbers in text and hides or replaces them before the text goes anywhere it shouldn't.

Think of it like…

Blacking out names on a document before photocopying it for outsiders: you share the substance, keep a sealed original, and you check the copies for anything you missed because one missed name defeats the purpose.

Where you’ve seen it

A support platform sends chat transcripts to an external model and stores them for analytics. Regex rules for emails, phone numbers, IBANs and card numbers catch 62% of the 1,200 labelled PII spans in a 5,000-message sample; adding an entity recognizer for names and addresses lifts recall to 94% with 91% precision, so F1 = 2 × 0.91 × 0.94 / (0.91 + 0.94) = 0.924. Card candidates are validated with the Luhn algorithm: for the standard Visa test number 4111 1111 1111 1111, the digits (doubling every second digit from the right) sum to 8 + 14 + 8 = 30, which is divisible by 10, so it's accepted, while a random 16-digit order number usually fails the check and isn't redacted. Redaction runs before the provider call and before logging; names and emails are replaced with consistent tokens (<PERSON_1>, <EMAIL_1>) within a conversation so the model can still follow references, and the token map is kept in an encrypted vault with a 30-day expiry for re-hydrating the reply. Residual misses (6% of spans) are handled by short log retention, access controls and a periodic audit on a sample of 500 redacted messages.

Words you’ll hear

PII
Information that identifies or relates to a person, directly or in combination.
Tokenisation (placeholders)
Replacing values with consistent tokens, optionally reversible from a vault.
Luhn check
A checksum used to validate card numbers and cut false positives.
Recall vs precision
Share of PII caught versus share of redactions that were truly PII.

Visual diagram

Loading interactive diagram

Theory & deep dive

Detection methods and accuracy

Pattern detectors handle structured identifiers: emails, phone numbers (country-specific formats), IBANs, national IDs (with checksum rules where they exist), IP addresses, API-key formats and card numbers validated with the Luhn algorithm (double every second digit from the right, subtract 9 from results above 9, sum; valid if the total is a multiple of 10). Validators cut false positives: a random 16-digit number fails Luhn about 90% of the time. Entity recognition (spaCy, transformer NER, or services like Microsoft Presidio, cloud DLP APIs) finds names, organisations, locations and addresses that regex can't. Context rules ("my password is ...", "SSN:") and deny-lists/allow-lists tune behaviour (don't redact your own company name or public figures in a news summary).

Evaluate on a labelled sample (a few thousand messages with annotated spans) and report recall (the share of true PII found), precision and F1, per entity type and language. Recall matters most for privacy (a miss is a leak), precision for utility (over-redaction destroys meaning). In the example, regex alone reaches 62% recall; adding NER gives 94% recall and 91% precision, F1 0.924. Expect lower accuracy on names in lower-case text, non-English languages, code, OCR output and creative formats, and on quasi-identifiers (a rare job title plus a city) that identify a person without matching any pattern. Keep adding misses to the test set.

Luhn check on a test card

4111 1111 1111 1111, from the right: 1, (1×2=2), 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, (4×2=8). Non-doubled digits: 8 ones = 8. Doubled: seven 2s = 14, plus 8 for the leading 4. Sum = 8 + 14 + 8 = 30, a multiple of 10, so it's valid.

Key takeaway: Combine validated patterns with entity recognition, and judge detectors on labelled data with recall first.

Replacement strategies, placement and limits

Choose the replacement by what the downstream needs. Hard redaction ([REDACTED]) is safest but loses structure. Masking keeps a hint (last four digits). Consistent tokenisation (<PERSON_1>, <EMAIL_1>) lets the model follow "he" and "that email" and lets you re-hydrate the response by swapping tokens back from a vault, so the provider never sees raw values while the user gets a natural reply. Pseudonymisation with realistic fake values preserves language fluency but can mislead if mistaken for real data. Format-preserving or deterministic tokens allow joins in analytics without exposing identities (use a keyed hash, not a plain hash of low-entropy values such as phone numbers, which can be brute-forced).

Apply redaction at every boundary: before provider calls, before writing logs and traces, at RAG ingestion (so embeddings and chunks don't contain PII), in tool outputs and in training or evaluation datasets. Also scan outputs for PII the model might reveal. Be clear about limits: redaction is risk reduction, not anonymisation; re-identification through context is possible, and some tasks genuinely need the raw values, in which case use providers under appropriate agreements, access controls and retention limits instead. Protect the token vault (encryption, short expiry, tight access), set short log retention, restrict who can view transcripts and audit samples regularly. Legal obligations vary by jurisdiction (privacy, health and payment regulations), so involve privacy and legal teams rather than treating this lesson as legal advice.

Round trip with tokens

Input: "Hi, I'm Maria Lopez (maria@example.com). Card 4111 1111 1111 1111 was charged twice." Sent to the model: "Hi, I'm <PERSON_1> (<EMAIL_1>). Card ****1111 was charged twice." The reply "Thanks <PERSON_1>, I've opened a refund" is re-hydrated to "Thanks Maria" for the user.

Key takeaway: Redact at every boundary with reversible tokens where needed, protect the vault, shorten retention and remember it's risk reduction.

How it works, step by step

Step 1 of 4
Privacy + engineering

1. Inventory PII flows

Map where personal data enters prompts, logs, vector stores, tools and datasets, and which destinations are external.

provider calls · logs · RAG index
Key numbers at this step
Classify
data types

When to use it & trade-offs

What it is

PII redaction detects personal data (names, emails, phone numbers, addresses, national IDs, payment card numbers, health details) in text and removes or replaces it before the text is sent to a model provider, stored in logs, embedded for retrieval or shown to someone who shouldn't see it. Detection combines patterns (regular expressions with validation such as the Luhn check for card numbers), named-entity recognition for names and places, and context rules. Replacement can be redaction ([REDACTED]), masking (****1111), tokenisation with consistent placeholders (<EMAIL_1>) that can be re-inserted later from a secure vault, or pseudonymisation with realistic surrogates.

Why it matters: Prompts, retrieved documents, tool outputs and chat logs routinely contain personal data. Sending it to third-party providers, keeping it in logs and embedding it in vector stores creates privacy, compliance and breach risk, and it can later resurface in outputs. Redaction reduces what can leak, supports data-minimisation obligations and makes observability safer, but it trades off against utility (a model can't personalise or reason about a masked name) and is never perfect, so you must measure recall and design for residual risk.

When to reach for it

  • Sending data to external model providers
  • Logging and tracing LLM traffic
  • Ingesting documents into RAG indexes

When to avoid or be careful

  • Hashing low-entropy values like phone numbers with a plain hash
  • Redacting only the final response and not the logs
  • Assuming redaction equals anonymisation

Replacement strategies

Hard redaction
Best for: Logs and analytics where identity isn't needed

Strengths: Safest; simple.

Watch out: Loses structure and reference.

Reversible tokenisation
Best for: LLM calls that need coherent references

Strengths: Model can follow entities; reply can be re-hydrated.

Watch out: Needs a protected vault.

Pseudonymisation with surrogates
Best for: Test data and demos needing realistic text

Strengths: Fluent, realistic content.

Watch out: Can be mistaken for real data; consistency work.

Interview signals & numbers to know

When this topic comes up

  • “We log full prompts”
  • “Can we send customer data to the provider?”
  • Luhn validation
  • Presidio and NER
  • Re-hydration

Benchmarks & rules of thumb

62% → 94% -
recall of regex alone versus regex plus NER
F1 = 0.924 -
from precision 0.91 and recall 0.94
multiple of 10 -
Luhn sum for a valid card number

Common mistakes & follow-ups

Common interview mistakes

  • Skipping RAG ingestion and letting PII land in embeddings.
  • Over-redacting until the model can't answer.
  • Never measuring recall on real data.

Likely interviewer follow-ups

  • How would you prevent PII from reaching an LLM provider?
  • Why use reversible tokens instead of hard redaction?
  • How do you evaluate a PII detector?
Interview tip: Report recall, not just precision, and say where residual risk is managed (retention, access). It shows realistic privacy engineering.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply PII Redaction with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Output Validation
Next topic
Data Leakage