# System Design: Design Electronic Health Records (EHR) — HIPAA, Patient Data, Interoperability, HL7 FHIR, Audit Logging

Source: https://www.techinterview.org/post/3233474386/system-design-design-electronic-health-records-ehr-hipaa-compliance-patient-data-interoperability-hl7-fhir-audit-logging/
Updated: 2026-04-20 · techinterview.org

Electronic Health Record systems manage the most sensitive data in technology -- patient medical histories, diagnoses, prescriptions, and lab results. Designing an EHR tests your understanding of strict regulatory compliance (HIPAA), data interoperability standards (HL7 FHIR), audit logging, role-based access control, and the unique challenges of healthcare data. This is a niche but increasingly common system design question, especially at health tech companies.

## HIPAA Compliance Architecture

HIPAA (Health Insurance Portability and Accountability Act) governs how Protected Health Information (PHI) is stored, accessed, and transmitted. Technical requirements: (1) Encryption at rest -- all PHI must be encrypted. AES-256 for database encryption (PostgreSQL pgcrypto or transparent data encryption). S3 server-side encryption for medical documents and images. (2) Encryption in transit -- TLS 1.2+ for all API communication. No unencrypted PHI transmission. (3) Access controls -- role-based access: doctors see their patients records, nurses see assigned patients, billing sees financial data only, and patients see their own records. Minimum necessary principle: each role sees only the data required for their function. (4) Audit logging -- every access to PHI must be logged: who accessed what data, when, from where, and for what purpose. Audit logs are immutable and retained for 6 years minimum. (5) Business Associate Agreements (BAA) -- every cloud provider handling PHI must sign a BAA. AWS, GCP, Azure offer HIPAA-eligible services with signed BAAs. Not all services are eligible -- verify each one. (6) Breach notification -- if PHI is exposed, patients and HHS must be notified within 60 days. Penalties: $100 to $50,000 per violation, up to $1.5 million per year per violation type.

## Patient Data Model

Core entities following HL7 FHIR (Fast Healthcare Interoperability Resources) standard: (1) Patient -- demographics: name, date of birth, gender, contact info, insurance, emergency contacts. Unique identifier: MRN (Medical Record Number). (2) Encounter -- a visit: patient_id, provider_id, facility, date, type (outpatient, inpatient, emergency), diagnosis_codes (ICD-10), procedures. (3) Observation -- clinical data: vitals (blood pressure, heart rate, temperature), lab results (blood glucose, cholesterol), and measurements (height, weight, BMI). Each observation: patient_id, code (LOINC), value, unit, date, status. (4) Medication -- prescriptions: patient_id, medication_code (RxNorm), dosage, frequency, prescriber_id, start_date, end_date, status (active, completed, discontinued). (5) Condition -- diagnoses: patient_id, code (ICD-10), onset_date, status (active, resolved), severity. (6) Document -- clinical notes, imaging reports, discharge summaries. Stored as FHIR DocumentReference pointing to the actual document in S3. Database: PostgreSQL for structured clinical data (relational integrity for patient safety). S3 for medical images (DICOM format from CT/MRI/X-ray) and documents (PDF clinical notes). Elasticsearch for clinical search (find all patients with diabetes AND hypertension prescribed metformin).

## Interoperability: HL7 FHIR API

Healthcare systems must exchange data: a hospital sends lab results to a patient primary care doctor. HL7 FHIR is the modern standard for healthcare data exchange. FHIR API: RESTful API with standardized resources (Patient, Observation, MedicationRequest, etc.). Each resource has a defined JSON structure. Example: GET /Patient/12345 returns the patient demographics in FHIR JSON format. GET /Observation?patient=12345&code=8867-4 returns all heart rate observations. Standard operations: read, search, create, update, delete, and history (version history of a resource). SMART on FHIR: an authorization framework for healthcare apps. Uses OAuth 2.0 with healthcare-specific scopes: patient/*.read (read all resources for the authorized patient), user/Observation.write (write observations as the authorized user). This enables third-party apps (patient portals, wearable integrations) to access EHR data securely. CDS Hooks (Clinical Decision Support): the EHR triggers hooks at key workflow points (prescribing a medication, ordering a test). External CDS services receive the clinical context and return recommendations (drug interaction warnings, guideline-based suggestions). Real-time interoperability. Data exchange patterns: (1) Pull -- a provider queries another system FHIR API for patient data. (2) Push -- a system sends data to another (lab sends results to the EHR via FHIR message). (3) Subscription -- a system subscribes to notifications when specific data changes (notify me when a lab result is available for patient X).

## Audit Logging

Every access to PHI generates an audit log entry. This is non-negotiable for HIPAA compliance. Audit log entry: timestamp, user_id, user_role, action (read/create/update/delete), resource_type (Patient/Observation/Medication), resource_id, patient_id (whose data was accessed), IP_address, user_agent, facility, and justification (why the access occurred -- e.g., "treating physician," "billing review"). Volume: a hospital with 1000 providers each accessing 50 patient records per day = 50,000 audit entries per day. A large health system: millions per day. Storage: append-only log in a separate audit database (not the same database as clinical data -- separation of concerns and preventing audit log tampering). Use a write-optimized store: Kafka -> ClickHouse or AWS CloudTrail -> S3 + Athena. Immutability: audit logs must be tamper-proof. Write to an append-only store with no delete permissions. Use S3 Object Lock (WORM -- Write Once Read Many) for archived audit logs. Alert on suspicious access patterns: a provider accessing records of patients not assigned to them, bulk record access (downloading many records), and access outside normal working hours. These may indicate insider threats or compromised credentials.

## Clinical Decision Support and Safety

EHR systems have life-critical safety requirements: (1) Drug-drug interaction checking -- when a provider prescribes a medication, the system checks all active medications for interactions. Severity levels: mild (informational), moderate (warning), and severe (hard stop -- requires override justification). Interaction databases: First Databank (FDB), Multum, and RxNorm. (2) Allergy checking -- before prescribing, check the patient allergy list. Alert if the prescribed medication or its class matches a documented allergy. (3) Dosage validation -- verify the prescribed dose is within the therapeutic range for the patient age, weight, and kidney function. Alert on: overdose (exceeds maximum), underdose (below therapeutic minimum), and renal dose adjustment needed. (4) Order set templates -- standardized order sets for common conditions (sepsis bundle, post-surgery care) reduce errors and ensure evidence-based care. These safety checks must be real-time (during the prescribing workflow) and reliable (false negatives -- missing a dangerous interaction -- are unacceptable). The CDS engine runs locally within the EHR (low latency) with a regularly updated drug database. Override tracking: when a provider overrides a safety alert, log the override with justification. Review overrides regularly for patterns indicating alert fatigue (providers clicking through all alerts without reading).
