Introduction
Every enterprise handles sensitive data — names, emails, IDs, addresses, medical notes, financial numbers. Regulations (GDPR, CCPA, HIPAA) and simple business risk demand you find personally identifiable information (PII) quickly and treat it correctly. Manual scans are slow and error-prone. An AI-based data classification pipeline fast-tracks discovery, applies anonymization or masking rules, and provides human-review flows for edge cases.
This article walks you through designing and implementing a production pipeline that:
Detects PII with hybrid methods (rules + ML)
Assigns sensitivity and confidence levels
Applies anonymization, pseudonymization, or redaction policies
Supports human-in-the-loop review (Angular UI)
Integrates with a .NET backend, storage, and message buses
Is auditable, testable, and scalable
I assume you want a practical guide you can implement in enterprise systems: clear architecture, data models, sample code, testing strategy, and operational guidance.
Goals and Non-Goals
Goals
Reliable PII detection across structured (tables) and unstructured (text, documents) data.
Risk-based anonymization: reversible pseudonymization for analytics; irreversible masking for exports.
Human review for low-confidence detections.
Scalable and observable pipeline for batch and streaming workloads.
Non-Goals
This is not a legal compliance checklist — consult privacy counsel for final policy.
This is not an attempt to cover every PII type (biometrics, genetic data) — extend patterns as needed.
High-Level Architecture (Block Diagram B)
┌────────────────────────┐
│ Data Sources │
│ (DBs, Files, Streams) │
└──────────┬─────────────┘
│
▼
┌────────────────────┐
│ Ingest Layer │
│ (Batch / Stream) │
└──────────┬─────────┘
│
┌─────────────▼────────────┐
│ Preprocessing & Normal. │
│ (tokenize, normalize) │
└─────────────┬────────────┘
│
┌────────────▼────────────┐
│ Hybrid Detector │
│ - Regex & Heuristics │
│ - ML Model (NER) │
└────────────┬────────────┘
│
┌────────────────┴────────────────┐
│ Confidence Scorer & Risk Engine │
└────────────┬─────────────┬──────┘
│ │
▼ ▼
┌────────────────────┐ ┌──────────────┐
│ Auto-Anonymizer │ │ Review Queue │
│ (mask/replace/hash) │ │ (UI + Human) │
└─────────┬───────────┘ └──────────────┘
│ │
▼ ▼
┌────────────────────┐ ┌────────────────┐
│ Output Store (Safe)│ │ Audit + Logs │
│ (masked / pseud.) │ │ (who, when) │
└────────────────────┘ └────────────────┘
Key Concepts and Decisions
Hybrid Detection: Rules + ML
Rules (regular expressions, dictionaries, checksum validators) are deterministic and fast. Use them for exact patterns: email, credit-card numbers (Luhn), phone numbers.
ML (NER — Named Entity Recognition) catches context-dependent PII: person names in free text, organization names, ID tokens that vary by country.
Combine both in a pipeline: run fast rules first, then ML for remaining uncertain tokens.
Confidence And Risk
Every detection must carry a confidence score and a risk label (Low/Medium/High). Risk drives action:
High confidence, high-risk → automatic anonymize.
Medium confidence → send to review queue.
Low confidence → annotate but leave untouched.
Anonymization Modes
Masking / Redaction: Replace characters with
***— irreversible. Use for public exports.Pseudonymization: Replace identifier with a reversible token (store mapping in a secure vault) — useful for analytics where you need to join events across datasets without exposing raw PII.
Tokenization (Vault): Store actual value in a secrets store or HSM and replace with token reference.
Hashing: Irreversible hash, optionally salted per-tenant. Use when joinability is needed and reversal is forbidden.
Human-in-the-Loop
Low confidence items should be pushed into a review UI where privacy officers or data stewards can approve, adjust classification, or add suppression rules.
Auditability and Explainability
Record each detection event (original value, detected type, detector used, score, action taken, operator decisions). This is essential for compliance audits.
Data Model (Core Tables)
Simplified SQL schema for meta:
CREATE TABLE DetectionJob (
JobId UNIQUEIDENTIFIER PRIMARY KEY,
SourceName NVARCHAR(200),
StartedAt DATETIME2,
CompletedAt DATETIME2 NULL,
Status NVARCHAR(20) -- Pending, Running, Completed, Failed
);
CREATE TABLE DetectionRecord (
RecordId BIGINT IDENTITY PRIMARY KEY,
JobId UNIQUEIDENTIFIER,
SourceKey NVARCHAR(400), -- pointer to source row or file path
FieldName NVARCHAR(200) NULL,
OriginalSnippet NVARCHAR(MAX),
DetectedType NVARCHAR(100), -- EMAIL, SSN, NAME, CREDIT_CARD
Confidence FLOAT,
RiskLevel NVARCHAR(20), -- Low, Medium, High
ActionTaken NVARCHAR(50), -- Masked, Pseudonymized, Reviewed
ActionedAt DATETIME2 NULL,
ActionedBy NVARCHAR(200) NULL,
AuditJson NVARCHAR(MAX) NULL -- detector traces, regex matched groups, model logits
);
For pseudonymization mapping:
CREATE TABLE PseudonymMap (
PseudoId UNIQUEIDENTIFIER PRIMARY KEY DEFAULT NEWID(),
HashKey NVARCHAR(200), -- salted hash of original
EncryptedValue VARBINARY(MAX), -- encrypted original value
CreatedAt DATETIME2 DEFAULT SYSUTCDATETIME()
);
Encryption and key management must use Key Vault/HSM in production.
Pipeline Flow (Detailed)
Ingest
Batch: schedule ETL jobs to extract columns / files.
Stream: subscribe to CDC topics, Kafka, or messaging streams.
For files (PDF/DOCX), run OCR first (Tesseract or cloud OCR) to get text.
Preprocess
Normalize whitespace, remove HTML tags, canonicalize formats (phone internationalization).
Tokenize into sentences/words; keep offsets for redaction.
Rule-Based Pass
Run fast regex checks and dictionary lookups.
Validate numbers (credit-card Luhn, IBAN patterns, checksum validation).
Mark exact matches as high confidence.
ML Model Pass
Run a Named Entity Recognition model (fine-tuned for PII).
Models can be Transformers (DistilBERT, RoBERTa), CRF over tokens, or lighter spaCy pipelines for speed.
Capture per-entity confidence logits.
Confidence Fusion & Risk Scoring
Combine rule and ML signals with heuristics: e.g., regex match + model support → raise confidence.
Apply contextual checks: presence of "SSN" label near numbers increases risk.
Assign final action via policy rules.
Auto-Anonymize or Queue for Review
If auto-action → apply anonymization per policy (mask, pseudonymize).
If review → emit event to review queue with original snippet and suggested action.
Persist and Audit
Store detection record and mapping (if pseudonymized) securely.
Push audit logs to immutable store (append-only) with operator metadata.
Downstream
Safe data flows to analytics, exports, or storage.
Provide APIs for data retrieval which enforce decryption/authorized token resolution.
Implementation: .NET Backend
Technology Choices
.NET 8 / ASP.NET Core for APIs and workers.
Entity Framework Core for metadata and mapping tables (or plain Dapper for performance).
Kafka / Azure Event Hub for streaming ingestion and review queue.
Redis for fast rule caches (blacklists, dictionaries).
Key Vault / HSM for pseudonym encrypted storage.
ML model serving: options
Host models in Python microservice (FastAPI) and call from .NET via HTTP/gRPC.
Use ONNX models and run them in .NET via
Microsoft.MLor ONNX Runtime for faster, native inference.

Join the conversation! Your thoughts help the community grow.