Build a PII Detection System for Large-Scale Databases
Machine LearningModel answerLast updated
Design an ML-powered pipeline to automatically discover and classify personal information across billions of records in structured tables and unstructured text.
You're building a system for a large company that stores petabytes of user data across multiple databases, data lakes, and logging systems. The data includes structured database tables, semi-structured JSON logs, and unstructured text documents.
Your task is to design an automated system that:
- Discovers records containing personally identifiable information (PII) and sensitive data across all sources
- Classifies the type of sensitive information found (email addresses, phone numbers, government IDs, health records, financial data, etc.)
- Assesses risk by identifying not just obvious identifiers but also subtle patterns—like combinations of fields that together can identify individuals
- Scales to handle billions of existing records plus millions of new records daily
The system should use a combination of approaches: rule-based detection, machine learning models, and large language models where appropriate.
Your design should cover:
- What are the functional and non-functional requirements? What trade-offs matter most?
- What is the overall architecture? Draw out the main components and data flow.
- How does the detection work? Describe your multi-tiered approach and when you'd use rules vs. ML vs. LLMs.
- How do you handle scale—both the initial scan of existing data and continuous monitoring of new data?
- How do you measure success? What metrics matter and how do you improve the system over time?
- What are the privacy and security risks of the detection system itself?
Assume you're dealing with roughly 10 billion existing records (20-50 TB) and 100 million new records per day across heterogeneous schemas.
Hints
Hint 1
For structured data, think about profiling entire columns rather than scanning individual rows—most tables have millions of rows but only dozens of columns
Hint 2
Build a cascade: cheap methods filter the bulk of data, expensive models only run on ambiguous cases where simpler approaches aren't confident
Hint 3
Consider that '45-year-old female in ZIP 02138' might be identifying even without a name—you need table-level analysis, not just field-level pattern matching
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Multi-Tier PII Detection Pipeline
1. Requirements and Trade-offs
Functional requirements:
- Scan structured columns, semi-structured logs, and free text across diverse sources
- Detect direct identifiers (name, email, phone, SSN, IP address)
- Detect sensitive categories (health data, financial info, biometric data, children's data)
- Identify quasi-identifier combinations (age + ZIP + gender can uniquely identify someone)
- Classify severity based on data type, exposure level, and volume
- Support both full historical scans and incremental processing of new data
- Provide findings to compliance teams with context and allow feedback
Non-functional requirements:
- Scale: 10B rows initially, 100M/day ongoing—roughly 20-50 TB of data
- Latency: Batch processing is acceptable for backfill; new data should be scanned within a few hours
- Recall vs. Precision trade-off: High recall is critical for severe types (missing an exposed SSN is costly), but precision matters too (reviewers can't handle millions of false positives)
- Cost: Cannot run expensive LLM inference on billions of records
- Compliance: The detection system must not create new privacy risks—data stays in appropriate regions, findings don't leak raw PII
Key insight: For structured data, we classify columns not rows. A table with 100M rows but 50 columns reduces to 50 classification decisions if columns are homogeneous.
2. High-Level Architecture
Components:
-
Data Connectors: Adapters for databases (via CDC), data lakes (partition scanning), and log streams (Kafka consumers). Normalize to
{source, schema, field, value, metadata}. -
Column Profiler: For structured sources, sample ~10K values per column and compute statistics: regex match rates, cardinality, value length distribution, entropy. Use column names and descriptions as features.
-
Three-Tier Detection Cascade:
- Tier 1 (Rules): Fast regex and dictionary matching—runs on 100% of data
- Tier 2 (ML Models): Transformer-based NER and classifiers—runs on ~10-20% (rule hits + free text)
- Tier 3 (LLM + RAG): Context-aware reasoning—runs on ~0.1-1% (ambiguous cases only)
-
Re-identification Analyzer: Table-level analysis to find quasi-identifier combinations that violate k-anonymity.
-
Severity Scorer: Combines PII type, exposure context, volume, and access controls to assign risk levels (P0-P3).
-
Findings Store & Review UI: Stores results with masked snippets (never raw PII), routes alerts to data owners, collects reviewer feedback.
-
Feedback Loop: Retrains models, updates rules, and refreshes RAG example store based on human labels.
Infrastructure: Spark/Flink for distributed batch processing (Tiers 1-2), dedicated GPU pool for LLM inference (Tier 3).
3. Detection Strategy
Column-Level Classification (Structured Data)
For each table column:
- Extract sample (10K rows via reservoir sampling)
- Run regex validators: email RFC patterns, Luhn checksum for credit cards, phone parsing libraries, IBAN validators
- Check column name against dictionaries (
ssn,dob,phone_number) - Compute cardinality ratio (unique values / total)—high for IDs, low for categories
- If ≥80% of samples match a pattern with high precision, label the entire column
This reduces 10B rows to ~10M columns to classify.
Tier 1: Rule-Based Detection (Fast, High Coverage)
Runs on: All text data, all column samples
Methods:
- Regex with validation: Email patterns + RFC validation, phone numbers + libphonenumber parsing, credit cards + Luhn check, SSNs with format rules
- Entropy checks: High-entropy alphanumeric strings likely to be API keys or tokens (entropy > 4.5 bits/char)
- Name dictionaries: US Census names, international name lists (but expect noise)
- Keyword matching: Column names, field labels
Output: Candidate PII with confidence scores. High-confidence matches (credit cards passing Luhn, valid emails) become findings. Low-confidence discarded. Medium confidence (0.3-0.7) passes to Tier 2.
Tier 2: ML Models (Moderate Cost, Handles Ambiguity)
Runs on: ~10-20% of data—all Tier 1 medium-confidence hits plus all free-text fields
Models:
-
NER model: Fine-tuned DistilBERT or XLM-RoBERTa (for multilingual support) tags spans: PERSON, LOCATION, PHONE, EMAIL, MEDICAL_CONDITION, FINANCIAL_ACCOUNT. Train on labeled datasets (CoNLL, custom annotated PII corpus).
-
Column classifier: Gradient-boosted trees (XGBoost) using profiler features: regex hit rates, entropy, cardinality ratio, column name embedding, value length stats. Outputs probabilities for each PII type.
-
Record-level classifier: For semi-structured/unstructured records, a text classifier predicts sensitive categories (HEALTH, FINANCIAL, CHILDREN, CREDENTIALS).
Calibration: Use Platt scaling or isotonic regression to ensure probabilities are meaningful.
Output:
- Confidence > 0.85: Create finding
- Confidence < 0.4: Discard
- 0.4-0.85: Escalate to Tier 3 (~0.5-1% of original data)
Tier 3: LLM with RAG (Expensive, Context-Aware)
Runs on: <1% of data—only ambiguous cases from Tier 2
Why LLMs? They handle:
- Contextual leaks: "My doctor said my A1C is 8.2" (indirect health disclosure)
- Subtle combinations: "The patient in room 302, a 34-year-old teacher" (quasi-identifiers in narrative)
- Domain-specific terminology without explicit training
Architecture:
-
Retrieval component:
- Index company privacy policy, GDPR definitions, HIPAA rules
- Maintain vector store of human-labeled examples (embed with sentence-transformers)
- For each ambiguous record, retrieve top-k similar labeled examples
-
LLM prompt:
You are analyzing a database record for privacy-sensitive information.
Context: {schema, column names, neighboring fields}
Record: {text, with high-confidence PII already masked as [EMAIL], [PHONE]}
Similar labeled examples: {retrieved examples}
Company policy: {relevant policy excerpts}
Identify any PII or sensitive information. Return JSON:
{
"types": ["PERSON", "HEALTH_INFO"],
"spans": [{"start": 15, "end": 32, "type": "PERSON", "text": "John Smith"}],
"severity": "high",
"rationale": "Contains name and health diagnosis"
}
- Self-hosted model: Use Llama 3 or Mistral (7-13B parameters) hosted internally to avoid sending data to third parties.
Budget check: 1M records/day × 1K tokens × $0.001/1K tokens ≈ $1K/day. Scanning all 100M daily records would cost $100K/day—hence the tiered approach.
Re-identification Analysis
Problem: (age=34, ZIP=02139, gender=F) might uniquely identify someone even without a name.
Approach:
- Identify candidate quasi-identifier columns (age, ZIP, gender, occupation, dates) via profiler
- For column combinations of size 2-4, estimate distinct counts using HyperLogLog sketches
- Compute k-anonymity: fraction of rows where the combination appears in <5 rows
- Flag tables and column sets with k < 5 (common threshold)
- Check for joinable tables—two tables with shared keys multiply re-identification risk
Optimization: Combinatorial explosion is real. Use greedy search starting from high-entropy columns; prune branches once a pair is already near-unique.
4. Scaling Strategy
Initial backfill (10B rows):
- Partition by source and date range
- Process in Spark with checkpointing—if a partition fails, restart just that partition
- Prioritize high-exposure sources (public logs, exports) over locked-down databases
- Column profiling is embarrassingly parallel—one task per column
Incremental processing (100M/day):
- Use CDC (Change Data Capture) for databases—only new/modified rows
- For data lakes, track partition watermarks (process partitions newer than last scan)
- Re-profile columns only when schema changes or value distribution drifts significantly (detect via chi-square test on new samples)
Sampling for low-risk tables:
- For massive, low-risk tables (logs from internal testing environments), scan 1% sample
- If leak rate exceeds threshold (e.g., >0.1% findings), trigger full scan
Caching and deduplication:
- Hash record content—skip re-scanning identical records
- Cache column classifications with schema version
5. Evaluation and Feedback Loop
Metrics:
- Recall per PII type: % of true PII detected (measured on labeled test set + sampled review)
- Precision: % of findings that are true positives (measured via reviewer labels)
- Coverage: % of data sources and columns scanned
- Latency: Time from data ingestion to finding surfaced
Targets example:
- High-severity types (SSN, credit card, health): ≥95% recall, ≥90% precision
- Medium-severity (email, phone): ≥90% recall, ≥80% precision
Feedback loop:
- Reviewers label findings:
true_positive | false_positive | wrong_type | wrong_severity - Weekly: Retrain Tier 2 ML models on new labeled data
- Monthly: Update Tier 1 regex rules based on common false positives
- Continuously: Add labeled examples to RAG vector store for Tier 3
- Quarterly: Audit model performance across demographic groups and languages to detect bias
Active learning: Prioritize reviewer time on:
- Low-confidence predictions near decision boundary
- High-severity types
- Under-represented data sources or schemas
6. Privacy and Security of the System Itself
Risks: The detection system sees all PII and could become a honeypot or leak vector.
Mitigations:
- Data minimization: Store only masked snippets in findings (e.g., "User email: j***@example.com"). Never store full raw values.
- Access controls: Findings database has strict RBAC—only compliance team and data owners can view.
- Encryption: Findings at rest and in transit are encrypted.
- Regional processing: US user data processed only in US region, EU data in EU, per GDPR.
- Audit logs: Track all access to findings and raw data during scanning.
- Retention limits: Auto-delete findings after remediation is verified (e.g., 90 days).
- Model security: LLM must be self-hosted (not OpenAI API) to avoid exfiltration. No training on production data without explicit consent.
Compute isolation: Run detection pipeline in dedicated, locked-down compute environment separate from production serving infrastructure.
7. Common Mistakes to Avoid
- Scanning every row with LLMs: Cost and latency explode. Use tiered cascade.
- Ignoring quasi-identifiers: Combinations are often more identifying than single fields.
- High precision, low recall tuning: Missing a leaked SSN in logs is far worse than a few false positives.
- Storing raw PII in findings: This creates a new compliance risk.
- No feedback loop: Models drift as data changes; human labels are essential.
- One-time scan mindset: This must be continuous—new data arrives daily, schemas evolve.
Complexity and Scale
- Tier 1 (Rules): O(N) where N = total data size, but very fast (regex on 10 TB in hours with Spark)
- Tier 2 (ML): O(0.2N) with model inference, ~10-100× slower than rules but parallelizable on GPUs
- Tier 3 (LLM): O(0.01N) with 100-1000× cost of ML models; budget constrains this to <1%
- Re-identification: O(C × 2^k) where C = # columns, k = max combination size (use k ≤ 4 and pruning)
End-to-end: Initial backfill might take 1-2 weeks; incremental processing runs nightly or hourly.