esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

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.

13 min readIntermediateVery common · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key words

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.

Three checks, then redact

Raw text

transcript, email or document

Three checks in turn

Patterns and checksums

card and ID shapes, checked

Name and address model

finds names in free text

Confidence threshold

keeps only likely matches

Redacted text

safe to store or send

  1. 1The raw text enters the first check.
  2. 2Matches so far pass on to the name model, which adds its own finds.
  3. 3Every find gets a score, and low scores are dropped.
  4. 4Only likely matches are redacted, and the clean text moves on.
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. 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. 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. 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. 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. 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. 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. 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.

Where redaction sits in an LLM app

Text going in

User message

typed by a customer

Retrieved documents

search results from your files

Redact at the door

PII gone before the model reads

Model

sees only the redacted text

Going out

Answer

checked again before it is shown

Logs and traces

scrubbed before they are written

  1. 1The customer's message goes to the redaction step.
  2. 2Retrieved files are redacted too, the same as the chat.
  3. 3Only the redacted text moves on to the model.
  4. 4The model's answer is checked before the customer sees it.
  5. 5The model's output goes to the logs, but only after a scrub.
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.

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

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. 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. 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. 3

    Delete what routing does not need

    Diagnosis details are removed before the model reads the letter.

  4. 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. 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. 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."

    BetterPatterns 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."

    BetterOnly 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."

    BetterLogs 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?

Quick check

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

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q204What are guardrails?11 min
  2. Q205Input vs output guardrails?11 min
  3. Q211What is hidden context exposure (system prompt leakage)?11 min
  4. Q213What is sensitive information disclosure?12 min
  5. Q214What is improper output handling?12 min

Last updated on 26 November 2026

Building an AI app that handles customer or patient data?

I design and build AI products and agents, including the PII checks, the logs around them and the review steps. Book a short call and tell me what data you handle.