# How Do You Detect and Redact PII?

> How to find personal data in text with patterns, checksums and a name model, then redact it, explained simply for your AI interview.

**In short:** Detect PII in layers: patterns and checksums for numbers, a named-entity model for names and addresses, then a confidence threshold. Redact before the text reaches the model, the logs or the search index, because a copy that leaked is hard to take back.

AI and LLM interview question Q212, Guardrails and AI safety. Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-to-detect-and-redact-pii

## Say it in 30 seconds

PII is personal information, like names, card numbers and addresses. I detect it in layers. Patterns and checksums catch numbers with a fixed shape. A named-entity model finds names and addresses, which patterns miss. Then a confidence threshold keeps only the likely matches. I redact before the text reaches the model, the logs or the index. Redaction can delete a value, mask it, or swap in a token that a locked key can reverse. The honest limit is that every miss is a leak, so I measure misses on labelled samples from our own traffic.

## Say it in 2 minutes

Start with what counts as PII. It is any detail that can identify a person, alone or combined with other facts. The EU's data law, GDPR, calls this personal data. A language model reads everything it is given, and a copy of that text can end up in logs, a search index or a vendor's system. So detection and redaction matter at every step, including the places behind the chat window.

I detect in layers, because no single method finds everything. Patterns with checksums catch card numbers and some ID numbers. A checksum is a check digit, and a string that fails it is not reported. A named-entity model reads the words around a term, so it finds names and addresses in free text that no pattern can match. Then a confidence threshold decides which matches to act on. A higher threshold means fewer false alarms but more misses, and a miss is the leak that matters most.

Then I redact before the text goes to the model, the logs or the index. Deleting is simplest. Masking keeps the length visible. Tokenising keeps the link, so billing can reverse it with a key that stays in a locked system. I also check the model's answer on the way out, and I scrub logs and traces, which often store full prompts by default.

I'm honest about the limits. Detection is never complete. Indirect details, like a job title plus a postcode, can identify someone together. Redacted text can still be personal data if it can be linked back. So I measure misses on samples from our own traffic and keep a person in the loop for risky cases.

## What is PII, in plain words?

PII means personally identifiable information: any detail that can point to one person. A full name, a card number, a phone number, a home address and a diagnosis all count. So do combinations, such as a job title plus a postcode in a small town.

Picture a bank teller who covers the account number on a printed statement before photocopying it for a colleague. The teller still makes the copy, but the identifying part is hidden first. An AI app needs the same habit, because it copies whatever text it reads into logs, search indexes and vendor systems.

The EU's GDPR calls this personal data. It covers any information about a person who can be identified.

- **PII:** Personal details that can identify a person, on their own or combined with other facts.
- **Redaction:** Hiding or removing a value, so the rest of the text stays readable.
- **Tokenisation:** Swapping a value for a stand-in. A locked key can swap it back.
- **Pseudonymisation:** Replacing a name or ID with a code. The code can still be linked back.
- **False negative:** A miss: PII the detector did not find, so it leaks onward.

## How does detection work in layers?

No single method finds all PII. Pattern rules are strong for numbers with a fixed shape, but they flag look-alike numbers such as order numbers, and they are blind to names. A model can read names, but it can also misread a number. So real systems stack the methods. Named-entity recognition (NER) is a model that labels names, places and other entities in text. Google's data protection service puts it this way, and so does OWASP:

> "To detect content that corresponds to built-in infoTypes, Sensitive Data Protection uses various techniques including pattern matching, checksum validation, machine learning, and context analysis." (Google Cloud, Sensitive Data Protection)
>
> "Sanitize with classifiers, not regex alone: pattern matching plus NER plus trained classifiers, because regex fails on encoded and cross-lingual output." (OWASP, LLM02:2026)

Google's term infoType means one kind of sensitive data, such as a card number.

*Diagram, Three checks, then redact: Your text goes through three checks in turn. Patterns and checksums catch numbers with a fixed shape, then a name model reads the free text. A confidence threshold keeps only the likely matches, and only those get redacted.*
1. The raw text enters the first check.
2. Matches so far pass on to the name model, which adds its own finds.
3. Every find gets a score, and low scores are dropped.
4. Only likely matches are redacted, and the clean text moves on.

1. **Patterns and checksums:** A pattern is a shape rule, such as digits in a fixed layout. A checksum is a check digit: a string that fails it is not reported. Google says a finding can be dropped when it fails the checksum for its type, and it validates the checksum for credit card numbers.
2. **A name and address model:** A trained model reads the words around a term. That lets it tell a customer's name from a product name, and it catches names and addresses in free text that no pattern can match.
3. **A confidence threshold:** Each match gets a score for how likely it is to be PII. A higher bar gives fewer false alarms and more misses. Set it by testing on real samples, never by guessing.

AWS's Comprehend returns a score for each find, which is the chance the text is that type of data. Its docs also say a Canadian Social Insurance Number can be checked with the Luhn algorithm, a simple check-digit test.

## How do you redact, and what does each choice cost?

Redaction removes or hides a value. The method you pick decides what the rest of the system can still do with the text.

- **Delete: Remove the value.** Simplest, and the safest for logs. Nothing can be recovered, so billing cannot look it up later.
- **Mask: Hide most of it.** Keep the last four card digits, so support can match a charge. The rest becomes stars. It still leaks a little, so use it only where support needs that much.
- **Tokenise: Swap in a stand-in.** Billing keeps a locked key to swap the token back. Use it when a later step needs the real value. Everyone else sees only the stand-in.

Google's service lists the same families: redaction, replacement, masking and crypto-based tokenisation. Replacement swaps the value for a surrogate, such as a label. Some tokenisation can be reversed, which is what makes the last method useful for billing.

Every choice has a cost. A miss is a leak, however small the rate. Redacted text can still be personal data if it can be linked back, and GDPR says so for pseudonymised data:

> "Personal data which have undergone pseudonymisation, which could be attributed to a natural person by the use of additional information should be considered to be information on an identifiable natural person." (EU GDPR, Recital 26)

> **Tip:** A token is only as safe as its key. Store the key apart from the data it protects, and log who uses it.

## Where in an LLM app do you redact?

Put redaction at every door where text enters, leaves or gets stored. A safe model is no use if the text leaks out through a side door.

1. **At ingest:** Scrub PII from documents when they are loaded, before they are turned into searchable number lists (embeddings) and stored in the search index. OWASP's advice is to scrub PII at ingest.
2. **Model input:** Send the model only the fields the task needs. A claims bot does not need the whole medical file to pick a queue.
3. **Model output:** Check the answer before a customer sees it. A model can repeat a value it was given, even when you never meant it to show.
4. **Logs and traces:** OWASP warns that observability tools (software that records each step of a run for debugging) log full prompts, completions, chunks and traces by default. Scrub them before they are written, and limit who can read them.

*Diagram, Where redaction sits in an LLM app: Text enters from the user and from retrieved files. Redaction sits at the door before the model, and the answer is checked on the way out. Logs and traces get the same scrub before they are written.*
1. The customer's message goes to the redaction step.
2. Retrieved files are redacted too, the same as the chat.
3. Only the redacted text moves on to the model.
4. The model's answer is checked before the customer sees it.
5. The model's output goes to the logs, but only after a scrub.

OWASP gives this as an example scenario. Reasoning traces are logged in full to a shared tool, so hundreds of engineers can read PII that the final answer never shows. The answer looks clean, and the log does not.

## What does redaction look like in a small program?

A bank's support team wants call transcripts kept for quality checks, but card numbers must not be stored. This simplified check in plain Python finds card-shaped numbers, runs the Luhn check, and redacts only the ones that pass. Email addresses get a pattern match.

```python
import re

# Finds card-shaped numbers and keeps only those that pass the Luhn check.
CARD = re.compile(r"\b\d(?:[ -]?\d){12,15}\b")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")

def luhn_ok(digits):
    total = 0
    for i, d in enumerate(reversed(digits)):
        n = int(d)
        if i % 2 == 1:
            n = n * 2 - 9 if n * 2 > 9 else n * 2
        total += n
    return total % 10 == 0

def redact(text):
    def card(m):
        digits = re.sub(r"\D", "", m.group())
        return "[CARD]" if luhn_ok(digits) else m.group()
    text = CARD.sub(card, text)
    return EMAIL.sub("[EMAIL]", text)

transcript = (
    "Priya Raman: my card 4111 1111 1111 1111 was charged twice. "
    "Order 1234 5678 9012 3456 is still open. Mail priya.r@example.com."
)
print(redact(transcript))
```

Output:

```text
Priya Raman: my card [CARD] was charged twice. Order 1234 5678 9012 3456 is still open. Mail [EMAIL].
```

The card number becomes a [CARD] label, which is the replacement method from Google's list. The order number fails the check, so it stays. The customer's name also stays, because a pattern cannot know a word is a name. That gap is why real systems add a name model as a second layer.

### How would you add redaction to a claims triage agent?

An insurer runs an agent that reads claim emails and attached medical letters, then routes each claim to the right team. The router needs the policy number and the claim type, but not the diagnosis.

1. **Map every door:** List everywhere the text goes: the model, the search index, the ticket tool and the logs. Each one needs its own redaction rule.
2. **Tokenise what routing needs:** The policy number becomes a token that is the same every time, so the router can still match it. Only the claims system holds the key.
3. **Delete what routing does not need:** Diagnosis details are removed before the model reads the letter.
4. **Limit the routing tool:** The tool can write only to the claims queues. Even a fooled model can reach only those queues, which limits the damage.
5. **Measure the misses:** A claims officer labels a sample of realistic emails by hand, then counts what slipped through. Set the threshold from that count.
6. **Send doubt to a person:** Low-confidence matches go to a claims officer, who makes the call.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: PII is any detail that can point to a person.
- [ ] Layers: patterns and checksums, a name model, then a threshold.
- [ ] The redaction methods, and what each one costs in usefulness.
- [ ] Where to redact: ingest, model input, model output, logs and traces.
- [ ] Honest limits: a miss is a leak, and redacted text can still be personal data.
- [ ] Measurement on labelled samples from your own traffic.

**Common traps**

- Trap: "A regex catches all the PII." Better: Patterns catch numbers with a fixed shape. Names and addresses need a model, and the threshold decides what counts.
- Trap: "Redacted means anonymous, so GDPR no longer applies." Better: Only truly anonymous data falls outside GDPR. Redacted text that can be linked back is still personal data.
- Trap: "We log everything and clean it up later." Better: Logs copy PII the moment they are written. Redact before the write, because the copy is what leaks.

## Can you spot the leak?

**Spot the leak:** Your team logs every model call for debugging. Which log line leaks PII?

A. Request 8841 finished in 1.2 seconds using 412 tokens.
B. Customer message: refund card 4111 1111 1111 1111 for order 2291.
C. Index updated: 340 claim notes embedded for the motor queue.
D. Model latency at the 95th percentile was 2.3 seconds this week.

**Answer:** B. The raw card number is written to the log, so anyone who can read logs can read it. Redact before the line is written, because copies of a secret spread to other tools.

**Quick check:** Billing must still see which card was charged, but no one else should see the number. Which redaction fits?

A. Delete the card number from the transcript
B. Tokenise it, with the key kept only in billing
C. Ask the model to skip card numbers in its answers
D. Use a bigger model, which spots more numbers

**Answer:** B. Tokenising keeps a link that only billing can reverse. Deleting the number loses that link. A prompt cannot be trusted to hide a value, and a bigger model finds more matches without changing who can read them.

## Can you answer these from memory?

**Flash cards**

- **What is PII?** Any detail that can point to one person, alone or combined with others.
- **Why use layers?** Patterns catch fixed shapes, a name model catches free text, and a threshold sets the bar.
- **Redaction or tokenisation?** Redaction removes or hides. Tokenisation swaps in a stand-in that a locked key can reverse.
- **Is pseudonymised data anonymous?** No. GDPR says it stays personal data, because extra information can link it back.
- **Where do you redact?** At ingest, model input, model output, and in logs and traces.
- **Why measure misses?** Each miss is a leak. Measure on labelled samples from your own traffic.

## Likely follow-up questions

- Q204 What are guardrails? https://designervenkat.online/interview/ai/what-are-guardrails
- Q205 Input vs output guardrails? https://designervenkat.online/interview/ai/input-vs-output-guardrails
- Q211 What is hidden context exposure (system prompt leakage)? https://designervenkat.online/interview/ai/what-is-hidden-context-exposure-system-prompt-leakage
- Q213 What is sensitive information disclosure? https://designervenkat.online/interview/ai/what-is-sensitive-information-disclosure
- Q214 What is improper output handling? https://designervenkat.online/interview/ai/what-is-improper-output-handling
