Skip to content
Back to Blog
Healthcare AIArchitectureCodeDiagrams

PHI-Safe LLM Architecture: A Data Flow Guide for Engineers

A BAA is where HIPAA work starts, not where it ends. Map what crosses each boundary, decide when to de-identify, keep PHI out of telemetry, and build systems that fail closed.

September 15, 20268 min read
HIPAAPHIDe-identificationSecurityLLM
PHI-Safe LLM Architecture: A Data Flow Guide for Engineers

"We signed a BAA" is often where the HIPAA conversation ends on an AI project. It should be where it starts. A Business Associate Agreement defines who is responsible for protected health information. It does not stop PHI from ending up in your traces, your eval fixtures, or a support ticket.

This guide is about the engineering side: how to map where PHI goes, when to remove it, and how to build a system that stops when a control fails.

Engineering Guidance, Not Legal Advice

HIPAA obligations depend on your role, contracts, and use case. Treat this as a starting point for a conversation with your privacy and compliance teams.

Start with a Data Flow Map

Before you compare models, draw every place clinical data can travel. For each boundary, answer four questions:

  1. What crosses it? Be specific: full chart, a filtered context, or surrogates.
  2. Who is accountable on the other side? Name the vendor and the contract.
  3. How long does it stay? Include logs, caches, and backups.
  4. How would you prove it? A control you cannot demonstrate is an assumption.

People usually remember the model API. The boundaries that get missed tend to be quieter ones: tracing tools, error reporting, product analytics, vector databases, CI logs, and the spreadsheet someone made to debug a bad output.

What a BAA Does and Does Not Do

If a vendor creates, receives, maintains, or transmits PHI for you, you generally need a BAA with them. HHS guidance on cloud computing applies this even when a provider stores only encrypted data and holds no key.

For LLM vendors, read the details rather than just the headline:

  • Coverage by feature. A BAA may not cover every product, beta, or hosted tool. Check each feature you use.
  • Retention. Confirm what is kept, for how long, and whether any zero-retention arrangement applies to your models and features.
  • Training. Get in writing that your inputs are not used to train models.
  • Subprocessors and region. Know who else may process data and where inference runs.

Then repeat that review for every other tool on your map. An observability vendor with no BAA is a common and avoidable gap.

De-Identify When the Task Allows It

With a BAA in place, PHI can often lawfully reach the model. That does not mean it should. Many tasks do not need identifiers at all, and removing them reduces your exposure if something else goes wrong.

TaskNeeds identifiers?Approach
Proposing integration mappingsNoDe-identified samples
Terminology and code suggestionsNoSend the term and context only
Drafting a note from a visitRarelySurrogates for names and dates where possible
Patient letterYes, in the final textGenerate with surrogates, restore locally
Population analyticsNoAggregate, or use properly de-identified data

HIPAA defines two de-identification methods, described in HHS guidance. Safe Harbor removes 18 categories of identifiers, including all date elements except the year, and requires that you have no actual knowledge that the remainder could identify someone. Expert Determination relies on a qualified expert finding the re-identification risk very small.

Surrogates Are Not Automatically De-Identified

Replacing a name with a token reduces risk, but it does not by itself meet the legal standard. Free-text notes can still identify someone through rare conditions or narrative details, and you hold a key that can reverse the tokens. Keep treating surrogate text as PHI, under a BAA, unless your compliance team has determined otherwise.

Here is a simple surrogate pass using Microsoft Presidio for detection. The mapping stays on your side of the boundary.

phi/surrogates.py
from collections import defaultdict
 
from presidio_analyzer import AnalyzerEngine, Pattern, PatternRecognizer
 
mrn_recognizer = PatternRecognizer(
    supported_entity="MRN",
    patterns=[Pattern(name="site_mrn", regex=r"\bSYN-\d{7}\b", score=0.9)],
)
 
analyzer = AnalyzerEngine()
analyzer.registry.add_recognizer(mrn_recognizer)
 
 
def to_surrogates(text: str) -> tuple[str, dict[str, str]]:
    """Replace detected identifiers with stable tokens. Keep the vault in the PHI zone."""
    findings = analyzer.analyze(text=text, language="en")
    counters: dict[str, int] = defaultdict(int)
    token_for: dict[tuple[str, str], str] = {}
    vault: dict[str, str] = {}
 
    # Where spans overlap, keep the higher-confidence finding.
    kept = []
    for finding in sorted(findings, key=lambda f: -f.score):
        if all(finding.end <= k.start or finding.start >= k.end for k in kept):
            kept.append(finding)
 
    # Replace from the end of the text so earlier offsets stay valid.
    kept.sort(key=lambda f: -f.start)
 
    for finding in kept:
        value = text[finding.start:finding.end]
        key = (finding.entity_type, value)
        if key not in token_for:
            counters[finding.entity_type] += 1
            token_for[key] = f"[{finding.entity_type}_{counters[finding.entity_type]}]"
            vault[token_for[key]] = value
        text = text[:finding.start] + token_for[key] + text[finding.end:]
    return text, vault
 
 
def restore(text: str, vault: dict[str, str]) -> str:
    for token, value in vault.items():
        text = text.replace(token, value)
    return text

Detection is probabilistic, so treat it as a control you must measure. Label a test set, track recall per identifier type, and include notes with unusual names and formats. A recall figure you have measured is worth much more than a tool's reputation.

Minimum Necessary by Construction

HIPAA's minimum necessary standard has exceptions, including disclosures for treatment. Follow the principle anyway, because it is simply good system design: a smaller context means less exposure, lower cost, and often better answers.

Avoid passing "the chart" to a model. Build a context function per task, with an explicit list of what it may read. A medication question gets the medication list and relevant labs. It does not get psychotherapy notes. When you limit data in code rather than in a prompt, the limit holds even if the model is manipulated.

Keep PHI Out of Telemetry

This is the most common leak, because it happens by accident. A developer logs a prompt once to debug something, and now the logs contain PHI.

Use an allowlist, not a blocklist. Blocklists fail open, since anything you did not predict goes through. An allowlist fails closed.

telemetry/redact.py
from opentelemetry.sdk.trace import ReadableSpan
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
 
ALLOWED_ATTRIBUTES = frozenset({
    "gen_ai.operation.name",
    "gen_ai.request.model",
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "app.policy.version",
    "app.patient.hash",
    "app.task",
})
 
 
def allowed_attributes(span: ReadableSpan) -> dict:
    return {k: v for k, v in (span.attributes or {}).items() if k in ALLOWED_ATTRIBUTES}
 
 
class AllowlistExporter(SpanExporter):
    """Forwards each span with only approved attributes, and drops events, which can carry content."""
 
    def __init__(self, inner: SpanExporter):
        self.inner = inner
 
    def export(self, spans) -> SpanExportResult:
        return self.inner.export([
            ReadableSpan(
                name=span.name,
                context=span.context,
                parent=span.parent,
                resource=span.resource,
                attributes=allowed_attributes(span),
                events=(),
                links=(),
                kind=span.kind,
                status=span.status,
                start_time=span.start_time,
                end_time=span.end_time,
                instrumentation_scope=span.instrumentation_scope,
            )
            for span in spans
        ])
 
    def shutdown(self) -> None:
        self.inner.shutdown()

The OpenTelemetry GenAI conventions give you useful standard attributes for tokens and models. Leave any message content capture turned off in production.

The same rule applies elsewhere. Error messages should reference record IDs instead of values. Eval fixtures should be synthetic or properly de-identified, so production PHI never becomes a test case in a repository.

Test with Canaries

Seed staging with a synthetic patient who has a distinctive made-up name. Run the full workflow, including failures, then search your logs, traces, analytics, and vendor dashboards for that name. Any hit is a leak you found before a real patient was involved.

Fail Closed

Each control should stop the request when it fails, rather than quietly degrading.

De-identification unavailable

Stop the request. Do not fall back to sending the raw text.

Policy check errors

Deny by default. A timeout on an authorization check is not a pass.

Audit write fails

Return no clinical data. If you cannot record an access, it should not happen.

Fallback models and vendors

Route only to endpoints already covered by your BAA and your data flow map. Automatic failover to an unreviewed provider turns an outage into a disclosure.

Keep an Eye on the Rules

The HIPAA Security Rule overhaul proposed by HHS would make safeguards such as encryption and multi-factor authentication explicit requirements, and would call for a written technology asset inventory and network map. Final action has been pushed back, with the regulatory agenda now projecting July 2027, and the content could still change. The current rule remains in force.

The practical takeaway is that the data flow map you just drew is valuable either way. It is the artifact most of these requirements are really asking for.

Design the data flow first

Choosing a compliant vendor is one decision among many. Map every boundary, remove what a task does not need, allowlist your telemetry, test with canaries, and make every control fail closed. The result is a system whose privacy you can demonstrate, not just describe.

References

TC

TwilightCore Team

AI & Digital Studio

We build production AI systems and full-stack applications. Writing about the technical decisions, architecture patterns, and engineering practices behind real-world projects.