Redacting PHI at Scale: Protecting Patient Identifiers in Generative AI Ingestion Using Amazon Comprehend Medical
Generative AI and modern RAG (Retrieval-Augmented Generation) architectures have an insatiable appetite for context. The more detailed clinical notes, laboratory panels, and discharge letters you feed into a vector database or an LLM context window, the more accurate and insightful your clinical assistant becomes.
And therein lies the single greatest regulatory hazard in modern digital health.
Under HIPAA in the United States and GDPR across Europe and the UK, Protected Health Information (PHI) cannot simply be slung into cloud-hosted embeddings or commercial model inference endpoints without rigorous data governance.
Once a patient’s full name, social security number, home address, or exact date of birth is vectorized into high-dimensional embedding spaces (like pgvector, OpenSearch, or Amazon Bedrock Knowledge Bases), it is virtually impossible to extract or "unlearn" without dropping the entire index.
To make matters worse, legacy redaction approaches—specifically hardcoded regular expressions—fail miserably in healthcare:
- A regex for names will happily miss "saw Ms. Katherine at the bedside" while aggressively redacting "Parkinson's disease", "Alzheimer's dementia", or "Hashimoto's thyroiditis" simply because they contain capitalized surnames.
- A naive date regex will strip vital clinical chronologies like "titrated metformin after 14 days" while missing unstructured physician dictation timestamps.
Here is how we designed and implemented a production-grade, structurally sound PHI redaction pipeline in Node.js 22 using Amazon Comprehend Medical, character offset mathematics, and non-destructive entity replacement before a single token ever reaches Amazon Bedrock.
1. The Architectural Blueprint: Zero-Trust Document Ingestion
The core thesis of our ingestion architecture is straightforward: No document enters the vector database or LLM reasoning loop in its raw state.
When a multi-page scanned PDF or digital referral letter arrives, it passes through an isolated sanitization gate inside our asynchronous processing Lambda (clinical-document-processor.mjs):
flowchart TD A["Raw Clinical PDF / Scan"] --> B["Amazon Textract<br>(Table & Form Extraction)"] B --> C["Raw Markdown / Text Buffer"] C --> D["Chunking Engine<br>(Paragraph-Aware Boundary Splitting)"] D --> E["Amazon Comprehend Medical<br>(DetectPHICommand)"] E --> F["Global Offset Mapper<br>(Relative Chunk Offsets to Document Offsets)"] F --> G["Span Sorter & Collision Merger<br>(mergeSpans)"] G --> H["Single-Pass Non-Destructive Redactor<br>(applyRedactionSpans)"] H --> I["Sanitized Clinical Text<br><i>[REDACTED-NAME], [REDACTED-DOB]</i>"] I --> J["Comprehend Medical<br>(DetectEntitiesV2Command - Clinical Facts)"] I --> K["Amazon Bedrock Knowledge Base<br>(Titan Vector Embeddings)"] 2. Why Amazon Comprehend Medical? (The Eponym Problem)
Standard NLP models trained on news articles or Wikipedia cannot parse the contextual subtleties of clinical prose.
Amazon Comprehend Medical is trained specifically on EHR records, clinical trial notes, and physician dictations. It distinguishes between:
- PHI Entities (
DetectPHICommand): Names, dates of birth, geographic locations, phone numbers, email addresses, medical record numbers (MRNs), health plan IDs, and social security numbers (the 18 HIPAA Safe Harbor identifiers). - Clinical Entities (
DetectEntitiesV2Command): Anatomy, Medical Conditions, Medications, Test/Treatment/Procedures.
The Eponym Challenge
In medicine, dozens of common diseases and clinical signs are named after the physicians who discovered them:
- Babinski sign
- Crohn's disease
- Bell's palsy
- Hodgkin lymphoma
If an automated redaction system strips "Crohn's", the clinical vector embedding transforms from "Severe flare-up of Crohn's disease" into "Severe flare-up of [REDACTED] disease". The embedding loses its semantic meaning, corrupting RAG retrieval accuracy.
Comprehend Medical’s clinical context engine natively recognizes that "Dr. Crohn" in the provider header is a NAME (PHI), whereas "Crohn's disease" in the assessment section is a MEDICAL_CONDITION (Clinical fact, preserved).
3. The Engineering Challenge: Character Offset Mathematics at Scale
Comprehend Medical’s DetectPHICommand enforces an API payload ceiling (typically 10,000 to 20,000 UTF-8 bytes per call). A comprehensive 30-page patient oncology history can easily exceed 150,000 characters.
This introduces a difficult algorithmic trap: The String Shift Problem.
If you detect the name "Christopher Walken" (18 characters) at index 45 and replace it with [REDACTED-NAME] (15 characters), your document length shrinks by 3 characters. Every subsequent index returned by the API is now offset by $-3$. If you perform multiple naive replacements, your document becomes a scrambled mess of clipped words and misplaced redaction tags.
Here is the exact algorithmic implementation we used in clinical-document-processor.mjs to solve this cleanly.
Step A: Paragraph-Aware Window Chunking
We split large documents into processing windows, but we strictly respect double-newline (\n\n) and single-newline (\n) boundaries so words and entities are never sliced in half:
const MAX_COMPREHEND_CHARS = 10000; function chunkClinicalText(text) { if (text.length <= MAX_COMPREHEND_CHARS) return [text]; const chunks = []; let offset = 0; while (offset < text.length) { let end = Math.min(offset + MAX_COMPREHEND_CHARS, text.length); // If not at the end of text, find the nearest paragraph break if (end < text.length) { const window = text.slice(offset, end); const breakAt = Math.max(window.lastIndexOf("\n\n"), window.lastIndexOf("\n")); // Only snap to newline if it doesn't discard more than 60% of the chunk if (breakAt > MAX_COMPREHEND_CHARS * 0.4) { end = offset + breakAt + 1; } } chunks.push(text.slice(offset, end)); offset = end; } return chunks; } Step B: Mapping Relative Chunk Offsets to Global Document Offsets
Comprehend Medical returns offsets (BeginOffset, EndOffset) relative to the chunk it was handed. We iterate over the chunks, maintain a running globalOffset, and build an absolute document coordinate map:
const PHI_REDACT_TYPES = new Map([ ["NAME", "[REDACTED-NAME]"], ["DATE", "[REDACTED-DOB]"], ["PHONE_OR_FAX", "[REDACTED-PHONE]"], ["ADDRESS", "[REDACTED-ADDRESS]"], ["ID", "[REDACTED-ID]"] ]); function phiSpansFromEntities(entities, globalOffset) { const spans = []; for (const e of entities) { const t = e.Type; if (!t || !PHI_REDACT_TYPES.has(t)) continue; const begin = (e.BeginOffset ?? 0) + globalOffset; const end = (e.EndOffset ?? 0) + globalOffset; if (end <= begin) continue; spans.push({ begin, end, label: PHI_REDACT_TYPES.get(t) }); } return spans; } Step C: Span Sorting and Collision Merging
Occasionally, Comprehend Medical flags overlapping or adjacent entities (e.g., an address spanning across a street name and zip code). Replacing overlapping spans directly will duplicate characters or crash slice pointers.
We sort the spans and merge overlaps in $O(N \log N)$ time:
function mergeSpans(spans) { // Sort by start position ascending, then end position descending const sorted = [...spans].sort((a, b) => a.begin - b.begin || b.end - a.end); const merged = []; for (const s of sorted) { const last = merged[merged.length - 1]; if (!last || s.begin > last.end) { // No overlap: push new span merged.push({ ...s }); } else { // Overlap detected: extend previous span to cover both last.end = Math.max(last.end, s.end); } } return merged; } Step D: Single-Pass Non-Destructive String Assembly
Instead of executing destructive in-place string mutations, we construct the sanitized document in a single linear pass ($O(N)$):
function applyRedactionSpans(text, spans) { const merged = mergeSpans(spans); let result = ""; let cursor = 0; for (const span of merged) { if (span.end <= cursor) continue; // 1. Copy unaffected clean text preceding the PHI if (span.begin > cursor) { result += text.slice(cursor, span.begin); } // 2. Inject the semantic replacement token result += span.label; // 3. Advance the cursor past the redacted PHI span cursor = Math.max(cursor, span.end); } // 4. Append remaining trailing text result += text.slice(cursor); return result; } This algorithm guarantees that every character of surrounding clinical text remains pixel-perfect, regardless of how many hundreds of names, dates, or telephone numbers are scrubbed.
4. Preserving Downstream Clinical Utility
A common blunder in healthcare data pipelines is using crude black-box redaction (like ████████ or XXXXX).
While this prevents data leaks, it completely destroys the semantic readability of the document for an LLM:
Bad Redaction:
"Patient ████████ seen on ████████ for ████████ mg of metformin."
(The LLM no longer understands if the redacted entity was a doctor, a hospital, or a family member).Semantic Tag Redaction:
"Patient [REDACTED-NAME] seen on [REDACTED-DOB] by Dr. [REDACTED-NAME] for 500mg of metformin."
(The LLM immediately recognizes the relationships: a patient visited a doctor on a specific date for a specific dosage).
By preserving semantic placeholders ([REDACTED-NAME], [REDACTED-DOB], [REDACTED-PHONE]), the downstream Bedrock model can answer clinical questions like "Was the patient seen by a specialist for their medication adjustments?" with full confidence, even though all true personal identifiers have vanished.
5. Architectural Performance, Costs, and Feature Flags
Comprehend Medical is priced per unit of text ($0.01 per 10,000 characters). On a large scale platform ingesting thousands of research papers, medical journals, or regional NHS guidelines, redacting documents that contain no patient data whatsoever is a massive waste of cloud spend.
In serverless.yml and clinical-document-processor.mjs, we introduced a clean operational toggle:
function shouldSkipComprehendRedaction() { return process.env.SKIP_COMPREHEND_REDACTION === "true"; } - For Multi-Tenant Institutional Knowledge Bases (UK/US/Ireland public clinical guidelines):
SKIP_COMPREHEND_REDACTION=true. We bypass Comprehend Medical completely, reducing ingestion latency by ~70% and saving 100% of NLP costs. - For Personal Patient Portals (Uploaded lab panels, doctor referral letters):
SKIP_COMPREHEND_REDACTION=false. Every single page is scrubbed through the full Comprehend Medical offset pipeline before vectorization.
Summary: Key Lessons for Production AI Compliance
- Vector Databases are Forever: Treat vector stores as permanent data sinks. Once PHI is embedded into high-dimensional vectors, redaction is no longer possible. Sanitization must occur at the raw text stage.
- Never Trust Regex for Human Names: Human clinical writing is inherently irregular. Specialized medical NLP models (like Amazon Comprehend Medical) are mandatory to protect eponyms like Parkinson's or Alzheimer's while reliably catching conversational patient identifiers.
- Use Single-Pass Offset Assembly: String manipulation by search-and-replace will corrupt your documents. Always calculate absolute offsets, merge collisions, and reconstruct the text linearly.
- Redact Semantically, Not Blankly: Using semantic tags (
[REDACTED-NAME]) keeps the grammatical and relational context intact, ensuring your downstream Bedrock RAG models retain 100% of their clinical reasoning power.