Updated Nov 24, 20267 min read

Build a PHI De-identification Pipeline for Healthcare Analytics

How to turn clinical records into a Safe Harbor de-identified dataset for analytics: which identifiers to remove or generalize, why the study ID must be random rather than a hash, ZIP and age rules, idempotent exports and keeping PHI and analytics data apart in your own cloud account.

Illustration for Build a PHI De-identification Pipeline for Healthcare Analytics

Analytics and research teams want clinical data, and the clinical database is full of protected health information that most of those people should never see. The usual answer is a de-identified copy, refreshed as new encounters arrive, that analysts can query without access to the PHI behind it.

Getting it wrong is easy, because a hashed MRN or a full admission date still identifies people. This guide builds the pipeline around HIPAA's Safe Harbor method.

What does Safe Harbor require?

HHS describes two routes in its de-identification guidance: Expert Determination, where a qualified expert measures the re-identification risk of a specific dataset, and Safe Harbor, which removes 18 identifier types and requires that you have no actual knowledge that what remains could identify someone. Safe Harbor suits an automated pipeline, since the rules can be written as code.

Field in the clinical recordSafe Harbor treatmentPipeline output
Name, MRN, email, phone, street addressRemoveNot selected
Encounter or account numberRemove, it is a unique identifying numberReplaced by a random object key
Birth date, admission dateKeep the year onlybirthYear, encounterYear
Age over 89Group as 90 or older, with any year that implies itage: "90+", birthYear: null
ZIP codeFirst three digits only if that area has more than 20,000 peoplezip3, or 000
Patient IDReplace with a code not derived from the patientRandom studyId
Free-text notesHard to clean reliablyNot exported

Pipelines most often break the rule with the study ID, since section 164.514(c) allows a re-identification code only if it is "not derived from or related to information about the individual", and the same guidance says hashed values need an expert determination, so a SHA-256 or HMAC of the MRN does not qualify under Safe Harbor. A random UUID in a mapping table that never leaves the PHI database does.

How should the pipeline be shaped?

Run it as an event-driven step next to the clinical service: when an encounter is recorded, a message carries its internal ID to a subscriber, which reads only the fields the output keeps, applies the rules and writes one record to a bucket that analytics tools read. The PHI database and the de-identified bucket stay separate resources with separate access, so granting an analyst the bucket grants nothing in the clinical database.

The query computes age and years in SQL, so exact dates never enter the subscriber's memory, and each encounter gets a random object key the first time it is processed, so a redelivered message overwrites the same object instead of adding a duplicate row to the dataset.

How does Encore run the pipeline?

Encore is a backend framework with built-in infrastructure, so the clinical database, the topic and the de-identified bucket are declared in the service code and provisioned in your own AWS or GCP account. Per the AWS infrastructure docs, that is RDS, SNS with SQS and S3, all inside an account covered by your own business associate agreement with AWS or Google Cloud.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

The service that records encounters publishes to encounterRecorded after its insert commits, and this subscriber does the rest:

// deid/deid.ts import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Bucket } from "encore.dev/storage/objects"; import { Topic, Subscription } from "encore.dev/pubsub"; import { randomUUID } from "node:crypto"; const clinical = new SQLDatabase("clinical", { migrations: "./migrations" }); // Analysts get access to this bucket only, never to the clinical database. const deidentified = new Bucket("deidentified-encounters", { versioned: false }); export interface EncounterRecorded { encounterId: number; } export const encounterRecorded = new Topic<EncounterRecorded>("encounter-recorded", { deliveryGuarantee: "at-least-once", }); // Three-digit ZIP areas HHS lists as 20,000 people or fewer (2000 Census). // Refresh from current Census data, as the HHS guidance asks. const RESTRICTED_ZIP3 = new Set([ "036", "059", "063", "102", "203", "556", "692", "790", "821", "823", "830", "831", "878", "879", "884", "890", "893", ]); interface SourceRow { patient_id: number; age: number; birth_year: number; encounter_year: number; sex: string; zip: string | null; diagnosis_codes: string; } export interface DeidentifiedEncounter { studyId: string; age: string; birthYear: number | null; encounterYear: number; sex: string; zip3: string; diagnosisCodes: string[]; } export function deidentify(row: SourceRow, studyId: string): DeidentifiedEncounter { const over89 = row.age > 89; const zip3 = (row.zip ?? "").slice(0, 3); return { studyId, age: over89 ? "90+" : String(row.age), birthYear: over89 ? null : row.birth_year, encounterYear: row.encounter_year, sex: row.sex, zip3: /^\d{3}$/.test(zip3) && !RESTRICTED_ZIP3.has(zip3) ? zip3 : "000", diagnosisCodes: row.diagnosis_codes ? row.diagnosis_codes.split(" ") : [], }; } const _ = new Subscription(encounterRecorded, "deidentify-encounter", { handler: async ({ encounterId }) => { // Select only what the output keeps; names, MRNs, contact details and notes never load. const row = await clinical.queryRow<SourceRow>` SELECT e.patient_id, date_part('year', age(e.admitted_at::date, p.birth_date))::int AS age, date_part('year', p.birth_date)::int AS birth_year, date_part('year', e.admitted_at)::int AS encounter_year, p.sex, p.zip, array_to_string(e.diagnosis_codes, ' ') AS diagnosis_codes FROM encounters e JOIN patients p ON p.id = e.patient_id WHERE e.id = ${encounterId}`; if (!row) return; // A random study ID, not derived from patient data, kept only in the PHI database. const sid = await clinical.queryRow<{ study_id: string }>` INSERT INTO study_ids (patient_id) VALUES (${row.patient_id}) ON CONFLICT (patient_id) DO UPDATE SET patient_id = EXCLUDED.patient_id RETURNING study_id::text`; // One random key per encounter, reused on redelivery so the object is overwritten. const exp = await clinical.queryRow<{ object_key: string }>` INSERT INTO deid_exports (encounter_id, object_key) VALUES (${encounterId}, ${`encounters/${row.encounter_year}/${randomUUID()}.json`}) ON CONFLICT (encounter_id) DO UPDATE SET encounter_id = EXCLUDED.encounter_id RETURNING object_key`; const record = deidentify(row, sid!.study_id); await deidentified.upload(exp!.object_key, Buffer.from(JSON.stringify(record)), { contentType: "application/json", }); }, retryPolicy: { minBackoff: "10s", maxBackoff: "5m", maxRetries: 8 }, });
-- deid/migrations/1_create_tables.up.sql CREATE TABLE patients ( id BIGSERIAL PRIMARY KEY, mrn TEXT NOT NULL UNIQUE, full_name TEXT NOT NULL, birth_date DATE NOT NULL, sex TEXT NOT NULL, street TEXT, zip TEXT, phone TEXT, email TEXT ); CREATE TABLE encounters ( id BIGSERIAL PRIMARY KEY, patient_id BIGINT NOT NULL REFERENCES patients (id), admitted_at TIMESTAMPTZ NOT NULL, diagnosis_codes TEXT[] NOT NULL DEFAULT '{}', notes TEXT ); -- Re-identification map: stays in the PHI database, never exported. CREATE TABLE study_ids ( patient_id BIGINT PRIMARY KEY REFERENCES patients (id), study_id UUID NOT NULL UNIQUE DEFAULT gen_random_uuid() ); CREATE TABLE deid_exports ( encounter_id BIGINT PRIMARY KEY REFERENCES encounters (id), object_key TEXT NOT NULL UNIQUE );

encore run starts Postgres locally and stores bucket objects on the local filesystem, so the pipeline can be tested with synthetic patients before it touches real data, and deidentify is a plain function you can unit test with edge cases such as a 90-year-old or a restricted ZIP. The object storage docs cover listing and downloading the output, and the Pub/Sub docs cover the retry policy and the dead-letter queue for records that fail.

To deploy, connect your AWS or GCP account as described in Connect your cloud account and push, and the bucket and database are created as separate resources in that account. Encore does not make a dataset HIPAA compliant on its own, and the de-identification rules, your BAA and your access policies remain the parts you own.

With the rules in one typed function and the resources declared beside it, a coding agent asked to export a new field has to add it to the query, the function and the output type in the same diff, which keeps the change visible to the reviewer who checks it against Safe Harbor.

Best fit: Healthcare teams that need a refreshed, de-identified analytics dataset produced in their own cloud account, with the rules in reviewed code.

What should you test before go-live?

Run patients aged 89, 90 and 104 through deidentify and confirm only the first keeps an exact age and birth year. Feed a ZIP from the restricted list and a malformed ZIP and check both become 000, then redeliver the same encounter and confirm the bucket still holds one object for it and the study ID did not change.

Frequently asked questions

What are the two HIPAA de-identification methods?

Safe Harbor removes 18 types of identifiers, such as names, most geographic detail, all date elements except the year and record numbers, and requires that you have no actual knowledge the rest could identify someone. Expert Determination has a qualified expert apply statistical methods and document that the risk of re-identification is very small.

Can I use a hash of the patient ID as the study ID?

Not under Safe Harbor. The re-identification rule in 45 CFR 164.514(c) requires that a re-identification code is not derived from information about the individual, so use a random identifier stored in a mapping table. HHS guidance says hashed codes can be acceptable only when an expert determination covers them.

What happens to ZIP codes and ages over 89 under Safe Harbor?

You may keep the first three digits of a ZIP code only if that three-digit area contains more than 20,000 people, and otherwise replace it with 000. Ages over 89, and any date elements that reveal such an age, must be grouped into a single category of 90 or older.

How do I run a de-identification pipeline in my own AWS or GCP account?

With Encore you declare the clinical Postgres database, a Pub/Sub topic for new encounters and a bucket for the de-identified output in the service, and a subscriber writes one de-identified record per encounter. Deploying provisions RDS, SNS with SQS and S3 in your own AWS account, or the GCP equivalents.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders