Prompt Details
Model
(claude-5-sonnet)
Token size
1,245
Example input
[Project Name]: Healthcare Patient Analytics & Telemedicine Platform
[Folder structure or repository link]: /core → /patient-service, /appointment-service, /medical-records, /prescription-service /integrations → /hl7-parser, /fhir-adapter, /ehr-connectors, /device-sync /analytics → /data-pipeline, /reporting-engine, /dashboards, /ml-predictions /communication → /video-service, /messaging, /notifications, /audit-logs /security → /encryption, /compliance-checker, /access-control, /pii-masking /scripts → database migrations, data seeding, HIPAA audit generators
[Languages, frameworks, databases]: Node.js (Express + NestJS), Go (high-throughput services), PostgreSQL (HIPAA-compliant), TimescaleDB (time-series vital signs), Kafka, Docker, Kubernetes, AWS HealthLake, Socket.io (video/messaging)
[Architecture Discovery / Legacy Modernization / Documentation / Security Review]: Compliance Audit + Data Privacy Review
[Legacy Code / Missing Documentation / High Complexity / Technical Debt]: PII leaking in logs, inconsistent encryption, patient data accessible across unintended boundaries, audit trail gaps, legacy monolith mixed with new microservices
Example output
## 🧭 REVERSE ENGINEERING EXECUTION
### ✅ SECTION 1 — Executive Architecture Assessment
**System Purpose:**
- 🏥 Patient portal for viewing medical records, booking appointments, receiving prescriptions
- 👨⚕️ Provider dashboard for managing patient lists, video consultations, ordering tests
- 📊 Analytics engine tracking population health metrics, predicting readmission risk
- 📱 Real-time messaging between patients & providers
- 🔗 HL7/FHIR integration with external EHR systems
- ⏰ Appointment scheduling with automated reminders
**Architectural Complexity:** 🔴 Very High
- ➕ Real-time data (vital signs, video streams)
- ➕ Strict regulatory constraints (HIPAA, HITECH, state privacy laws)
- ➕ Data residency requirements (patient data must stay in specific jurisdiction)
- ➕ Audit trail obligations (every data access must be logged)
- ➕ Legacy EHR integrations (HL7 v2.x parsing)
**Engineering Maturity:** ⭐⭐⭐ 3/5
- ✅ Good API design with versioning
- ✅ Kubernetes orchestration implemented
- ❌ Inconsistent encryption practices
- ❌ Compliance gaps from rapid growth
- ❌ Audit logging incomplete
**Maintainability Score:** ⭐⭐ 2/5
- 🔴 PII exposure in application logs
- 🔴 Mixed monolith + microservices (refactoring in progress)
- 🔴 Access control rules scattered across services
- 🔴 Data isolation not enforced at database layer
- 🔴 No centralized compliance monitoring
---
### 🏗️ SECTION 2 — Architecture Reconstruction
**Architectural Style:** 🏛️ Microservices (Healthcare Domain-Driven) + Real-time Communication
**Core Service Boundaries:**
🔐 **Auth & Access Control Service**
- 🔑 OAuth2 + SAML for provider single sign-on
- 🔑 Patient MFA (email OTP or biometric)
- 🔑 Role-based access control (RBAC)
- 🔑 Consent management (patient must explicitly allow provider access)
👥 **Patient Service**
- 👤 Patient registration, demographics
- 👤 Patient preferences, health conditions, allergies
- 👤 Insurance information
- 👤 Emergency contacts
📅 **Appointment Service**
- 📆 Schedule management for providers
- 📆 Patient booking with availability checking
- 📆 Automated reminders (SMS/email 24h before)
- 📆 Cancellation + rescheduling workflows
📋 **Medical Records Service**
- 📄 Store patient documents (PDFs, images, lab results)
- 📄 FHIR-compliant clinical summaries
- 📄 Version history + audit trail per document
- 📄 Redaction capability (providers see only permitted records)
💊 **Prescription Service**
- 💉 Provider writes prescription (stored digitally signed)
- 💉 Pharmacy integration for fulfillment
- 💉 Refill requests + approval workflow
- 💉 Drug-drug interaction checking
🎥 **Telemedicine Service (Real-time)**
- 📹 WebRTC video/audio via Socket.io
- 📹 Session recording (encrypted) with patient consent
- 📹 Screen sharing for medical image review
- 📹 Automatic transcription with PII redaction
💬 **Messaging Service**
- 💭 Secure in-app messaging between patient ↔ provider
- 💭 Message encryption at rest
- 💭 Conversation retention policies (compliance requirement)
- 💭 No external SMS/email storage
📊 **Analytics & ML Service**
- 📈 Aggregate patient population health trends
- 📈 Readmission risk prediction (ML model)
- 📈 Preventive care gap identification
- 📈 De-identified data only (HIPAA safe harbor)
🔗 **EHR Integration Service**
- 🔄 HL7 v2.x message parsing
- 🔄 FHIR REST API clients
- 🔄 Data reconciliation (duplicate patient detection)
- 🔄 Bi-directional sync with external systems
🔏 **Security & Compliance Service**
- 🛡️ PII masking in logs/debugging
- 🛡️ Encryption key management (AWS KMS)
- 🛡️ Audit log generation
- 🛡️ Compliance rule validation (HIPAA Policy Engine)
---
### 📂 SECTION 3 — Repository Intelligence
**Primary Entry Points:**
🚀 **API Gateway** (`core/gateway/index.js`)
- 📡 Express server on port 3000
- 🔐 Authentication middleware intercepts all requests
- 🔀 Routes to appropriate microservice (service discovery via Kubernetes DNS)
- 📊 Request logging (PII-masked)
🏥 **Patient Service** (`core/patient-service/src/main.ts`)
- 🚀 NestJS application on port 3001
- 📦 Connects to PostgreSQL `patients` database
- 🔄 Manages patient CRUD operations
- ✅ Enforces RBAC (only authorized providers see patient data)
📱 **Telemedicine Service** (`communication/video-service/server.js`)
- 🎥 Node.js + Socket.io on port 4000
- 📡 WebSocket connections for real-time video
- 🔐 JWT authentication per session
- 💾 Calls Medical Records Service to store recording
🔧 **Worker Process** (`analytics/data-pipeline/worker.ts`)
- 🔄 Consumes Kafka events (new lab results, patient vitals)
- 📊 Aggregates data for analytics dashboard
- 🚀 Triggers ML model for readmission predictions
- 📤 Publishes results back to Kafka
**Folder Responsibilities:**
📂 `/core/patient-service/dto`
- 🎯 Data Transfer Objects defining API payloads
- 🎯 Validation rules (must have date of birth, SSN masked)
📂 `/integrations/hl7-parser`
- 🔀 Parse HL7 v2.x messages from hospitals
- 🔀 Extract patient demographics, lab results
- 🔀 Handle segment validation (checksum verification)
📂 `/security/pii-masking`
- 🛡️ Redacts sensitive fields before logging
- 🛡️ Patterns: SSN (XXX-XX-9999), phone, email truncation
- 🛡️ Applied to all console.log, Datadog metrics
📂 `/scripts/migrations`
- 🗄️ Liquibase migration scripts (database versioning)
- 🗄️ Create HIPAA audit tables, encryption keys
**Startup Sequence:**
1️⃣ Kubernetes scheduler deploys pod replicas across nodes
2️⃣ Init container: runs database migrations, ensures schema current
3️⃣ Main container: loads KMS encryption keys from AWS Secrets Manager
4️⃣ Auth Service starts → validates database connection
5️⃣ Patient Service starts → waits for Auth Service readiness
6️⃣ Appointment Service starts → subscribes to Kafka topics
7️⃣ Telemedicine Service starts → creates WebSocket listener
8️⃣ Analytics Worker starts → consumes Kafka, precomputes dashboards
9️⃣ Health checks pass → service registered in service mesh (Istio)
🔟 Prometheus scraper begins collecting metrics
---
### 🔗 SECTION 4 — Dependency & Integration Mapping
**Internal Service Call Graph:**
```
API Gateway
├─→ Auth Service (validate token)
├─→ Patient Service (get patient demographics)
├─→ Medical Records Service (fetch documents)
├─→ Appointment Service (schedule visit)
├─→ Prescription Service (write Rx)
└─→ Telemedicine Service (initiate video)
Appointment Service
└─→ Notification Service (send reminder)
└─→ External SMS Gateway (Twilio)
Telemedicine Service
├─→ Auth Service (verify session)
├─→ Medical Records Service (save recording)
└─→ Kafka (publish 'video.completed' event)
Analytics Worker
├─→ Kafka (consume 'lab.result' events)
├─→ Patient Service (get demographic context)
├─→ ML Service (predict readmission risk)
└─→ Kafka (publish 'readmission.alert' event)
EHR Integration Service
├─→ Patient Service (upsert patient from HL7)
├─→ Medical Records Service (import documents)
└─→ Kafka (publish 'ehr.sync' event for auditing)
```
**Data Flow & Isolation:**
🗄️ **PostgreSQL Database** (Multi-database per tenant for data residency)
- `patients_db_us_east_1` → patient records for US East region
- `patients_db_eu_gdpr` → patient records for EU (separate encryption keys)
- ⚠️ **RISK:** Some queries join across databases → slow, potential data leakage
📡 **Kafka Topics** (Event streaming)
- `lab.results` → when new lab tests available
- `vital.signs` → real-time vital sign updates (TimescaleDB -> Kafka)
- `appointment.scheduled` → trigger reminders
- `video.completed` → store recording, update audit log
- `ehr.sync` → track external EHR imports
🔐 **Redis Cache** (PII-sensitive data NOT cached)
- ✅ Cache appointment availability (no PII)
- ❌ DO NOT cache patient records (HIPAA violation if leaked)
- ❌ DO NOT cache medications/diagnoses
🔑 **AWS KMS** (Encryption key management)
- 🔓 Master key (AWS-managed)
- 🔓 Data key for encryption at rest
- 🔓 Separate key per region (data residency)
**External Integrations:**
📞 **Twilio** (SMS notifications)
- 📱 Appointment reminders
- 📱 Account verification codes
- ⚠️ Data leaving healthcare boundary → requires Business Associate Agreement (BAA)
🏥 **HL7 Message Queue** (Hospital EHR systems)
- 📥 Inbound: patient demographics, lab results, discharge summaries
- 📤 Outbound: appointment confirmations, referral updates
💳 **Stripe API** (Payment for consultations - future)
- 💰 Not yet implemented, would require PCI-DSS compliance
---
### 🔄 SECTION 5 — Workflow Reconstruction
**Patient Telemedicine Appointment Workflow:**
1️⃣ **Appointment Booking**
- 👤 Patient logs in via OAuth2 (MFA required)
- 🔍 Searches available provider slots (Appointment Service)
- 📆 Selects time, confirms booking
- ✅ Appointment record created with `status='scheduled'`
- 📧 Email sent to provider (via Notification Service)
- 📱 SMS reminder queued for 24 hours before
2️⃣ **Before Appointment (24h reminder)**
- ⏰ Cron job triggers Notification Service
- 📲 SMS sent: "Your appointment with Dr. Smith is tomorrow at 2 PM"
- 📧 Email also sent with Zoom/WebRTC link
- ✅ Audit log entry: "reminder.sent" for patient compliance
3️⃣ **Start Video Call (5 minutes before)**
- 🎥 Provider clicks "Start" in dashboard
- 🎥 Telemedicine Service generates session token (JWT)
- 🎥 WebSocket connection established via Socket.io
- 📹 Video stream starts (WebRTC peer connection)
- 📝 Session ID: `sess-uuid-12345`, encrypted stored
4️⃣ **During Consultation**
- 🎥 Both parties can see video + audio
- 📷 Provider can share medical images (screen share)
- 📝 Provider types clinical notes in real-time
- 💊 Provider can order lab tests (integrated form)
- 🔏 Telemedicine Service records video (consent already obtained)
- 📊 Vital signs displayed in dashboard (from patient's home device via API)
5️⃣ **End Video Call**
- 🛑 Either party clicks "End Session"
- 📹 Recording automatically encrypted + uploaded to S3
- 🔐 Recording path: `s3://medical-records-us-east-1/encrypted/{patient_id}/{session_id}.mp4`
- 📝 Clinical notes saved to Medical Records Service
- 📋 Visit summary auto-generated (NLP extraction)
- 📤 Visit record published to Kafka: `video.completed` event
6️⃣ **Post-Appointment**
- 📊 Analytics Worker consumes `video.completed` event
- 🔍 Extracts patient context (age, chronic conditions)
- 🤖 ML model predicts if readmission risk > threshold
- 🚨 If high risk → alert notification to care coordinator
- 📧 Patient receives message: "Your provider recommends follow-up in 2 weeks"
- 📋 Appointment marked `status='completed'`
- 🔐 Audit log entry with: patient ID, provider ID, duration, recording stored, consent verified
**Prescription Issuance Workflow:**
1️⃣ Provider decides to prescribe medication
2️⃣ Provider enters drug name → system checks drug-drug interactions
3️⃣ If interaction warning → provider reviews + overrides with notes
4️⃣ Provider signs digitally (PKI certificate)
5️⃣ Prescription Service stores in database + publishes Kafka event
6️⃣ Pharmacy receives notification (NCPDP format)
7️⃣ Patient notified: "New prescription available at CVS, $10 copay"
8️⃣ Patient can request refill (max 11 refills) without provider approval
9️⃣ Audit log tracks: who prescribed, when, what drug, patient consent
**HL7 Message Inbound Workflow (Lab Results):**
1️⃣ Hospital sends HL7 message: `OBX` segment (observation/result)
2️⃣ EHR Integration Service receives via secure TCP connection
3️⃣ HL7 parser validates message structure + checksum
4️⃣ Extract patient MRN → lookup patient record by MRN
5️⃣ ⚠️ **ISSUE:** MRN collision possible across hospitals → requires manual review
6️⃣ Insert result into `lab_results` table with timestamp
7️⃣ Publish Kafka event: `lab.result` {patient_id, result_type, value}
8️⃣ Analytics Worker consumes → aggregates for dashboard
9️⃣ Patient notification triggered (if result critical or abnormal)
🔟 Audit log: EHR sync event (who sent, what data, encrypted transmission)
---
### 🗄️ SECTION 6 — Data Architecture
**PostgreSQL Tables (Core HIPAA Data):**
🏥 **patients**
- 🔐 patient_id (UUID, PK)
- 👤 first_name, last_name (encrypted)
- 📅 date_of_birth (encrypted)
- 🔑 ssn_last4 (XXX-XX-1234, not encrypted — searchable)
- 📍 address (encrypted, null if withheld by patient)
- 📱 phone (encrypted)
- 📧 email (encrypted)
- 🏥 mrn (Medical Record Number, per facility)
- 🔒 data_residency_region (us_east_1, eu_gdpr) — determines encryption key
- ⏱️ created_at, updated_at, deleted_at (soft delete for HIPAA compliance)
📅 **appointments**
- 🔐 appointment_id (UUID, PK)
- 👥 patient_id (UUID, FK), provider_id (UUID, FK)
- 📆 scheduled_datetime
- ⏱️ duration_minutes
- 🏥 location_type (in_person, virtual, phone)
- 📊 status (pending, confirmed, in_progress, completed, cancelled, no_show)
- 📝 visit_notes (nullable, encrypted)
- 🔐 telemedicine_session_id (nullable, references sessions table)
💊 **prescriptions**
- 🔐 prescription_id (UUID, PK)
- 👥 patient_id, provider_id
- 💉 drug_name, drug_code (RxNorm)
- 📊 strength, quantity, refills_remaining
- 🖋️ digital_signature (PEM-encoded, timestamp)
- 🏥 pharmacy_id (NCPDP identifier, nullable)
- 📊 status (pending, filled, cancelled)
- 🚨 ddi_check_result (Drug-Drug Interaction check result)
🎥 **telemedicine_sessions**
- 🔐 session_id (UUID, PK)
- 👥 patient_id, provider_id
- 📹 recording_s3_path (nullable, encrypted path)
- 🔐 recording_encryption_key_id (KMS key used)
- ⏱️ started_at, ended_at
- 📝 transcript (nullable, PII-redacted)
- ✅ patient_consent_recorded (boolean, required for recording)
📄 **medical_documents**
- 🔐 document_id (UUID, PK)
- 👥 patient_id, created_by_provider_id
- 📋 document_type (lab_result, discharge, imaging, note)
- 📄 s3_path (encrypted reference)
- 🔐 encryption_key_id (KMS)
- 📊 visibility_scope (accessible_by_patient, accessible_by_providers, restricted)
- 📋 fhir_resource_type (if FHIR-compliant)
📊 **audit_logs (IMMUTABLE - append-only)**
- 🔐 audit_id (UUID, PK)
- 👥 actor_id (provider or patient), actor_type
- 📋 resource_type (patient, prescription, document)
- 🔍 resource_id (what was accessed)
- 🔔 action (read, write, delete, export)
- ⏱️ timestamp (UTC)
- 📍 ip_address (hashed for privacy)
- 📝 reason (optional, provider must enter for access)
- ❌ cannot be updated or deleted (HIPAA requirement)
**TimescaleDB (Time-Series Data):**
📈 **vital_signs** (hypertable)
- 👥 patient_id
- 📊 temperature, blood_pressure, heart_rate, spo2, glucose
- ⏱️ measured_at (indexed for range queries)
- 🏥 source_device (smartwatch, blood pressure cuff, home lab kit)
---
### 🧩 SECTION 7 — Design Pattern Discovery
**Patterns Identified:**
✅ **Event Sourcing** → audit logs capture all state changes (immutable event stream)
- ✨ Perfect for compliance (every access recorded)
- ✨ Time travel debugging (replay events to see system state at any point)
✅ **CQRS (Command Query Responsibility Segregation)** → Appointment Service writes to PostgreSQL, Analytics reads from denormalized Kafka events
- ✨ Separates read + write optimization
- ✨ Analytics doesn't slow down operational queries
✅ **Saga Pattern** → Multi-step workflows (booking appointment spans Appointment + Notification + Kafka events)
- ✨ Handles distributed transactions across services
- ✨ Compensating transactions if step fails (e.g., cancel notification if appointment cancelled)
✅ **Circuit Breaker** → calls to external SMS gateway (Twilio) have timeout + fallback
- ✨ If SMS gateway down → fallback to email
- ✨ Prevents cascading failures
✅ **Strangler Fig Pattern** → gradually migrating from monolith to microservices
- ✨ Old monolith handles legacy auth
- ✨ New microservices handle telemedicine
- ✨ API Gateway routes based on feature flag
**Anti-Patterns Detected:**
🔴 **Data Duplication Without Sync** → patient demographics stored in PostgreSQL + HL7 message queue + Elasticsearch
- ❌ Risk: data inconsistency if one source updates
- ❌ PII exposure across multiple systems
🔴 **Shared Database Across Services** → multiple services query same `patients` table
- ❌ Tight coupling (can't evolve schema independently)
- ❌ Violates microservice principle (each service owns its data)
- ❌ **HIPAA Risk:** patient data accessible to services that shouldn't access it
🔴 **Audit Logging in Application Code** → scattered across services, inconsistent format
- ❌ Risk: compliance audit fails (can't verify all data access)
- ❌ Some endpoints don't log (gap in audit trail)
🔴 **PII in Logs** → Patient name logged in Datadog/CloudWatch
- ❌ **CRITICAL HIPAA VIOLATION**
- ❌ Increases exposure if log storage breached
🔴 **No Data Isolation Layer** → authorization checks at application level
- ❌ Risk: database leak allows patient to see other patient data
- ❌ Should enforce at query level (database views with row-level security)
🔴 **Synchronous External Calls** → Prescription Service waits for pharmacy response
- ❌ Slow user experience (pharmacy takes 2-5 seconds to respond)
- ❌ Should be async (acknowledge immediately, notify pharmacy later)
---
### ⚠️ SECTION 8 — Risk & Modernization Analysis
**Compliance & Security Risks:**
🔴 **CRITICAL HIPAA VIOLATIONS:**
• 🚨 **PII Exposure in Logs** → Patient names, MRNs visible in Datadog logs
- 🔧 **Fix:** Implement PII masking library on all logging statements
- ⏱️ **Timeline:** Week 1 (highest priority)
• 🚨 **Unencrypted Data at Rest** → Medical documents stored in S3 without encryption
- 🔧 **Fix:** Enable S3 default encryption (AES-256 with KMS keys)
- ⏱️ **Timeline:** Immediate
• 🚨 **Audit Trail Gaps** → Some API endpoints don't log data access
- 🔧 **Fix:** Add audit middleware to ALL endpoints, centralize to immutable database
- ⏱️ **Timeline:** Sprint 1
• 🚨 **Shared Database Across Services** → Auth Service can query Patient Service database
- 🔧 **Fix:** Separate database per service, use API calls for cross-service data
- ⏱️ **Timeline:** Quarter 1 refactoring
🟡 **HIGH RISKS:**
• ⚠️ **Data Residency Violation** → Patient data for EU stored in US region
- 🔧 **Fix:** Implement geo-aware routing, separate encryption keys per region
- 📋 **Compliance:** GDPR Article 32 (data location)
• ⚠️ **No Patient Consent Audit** → Can't prove patient consented to telemedicine recording
- 🔧 **Fix:** Store signed consent document with checkbox timestamp + IP address
- 📋 **Compliance:** State laws vary (some require explicit consent)
• ⚠️ **Weak Encryption Key Rotation** → KMS keys never rotated
- 🔧 **Fix:** Implement AWS KMS automatic key rotation (every 90 days)
- 📋 **Compliance:** HIPAA Security Rule §164.312(a)(2)(i)
• ⚠️ **Missing Business Associate Agreements (BAA)** → 3rd-party vendors (Twilio, Stripe) lack BAA
- 🔧 **Fix:** Obtain signed BAAs from all vendors handling PHI
- 📋 **Compliance:** HIPAA Business Associate Rule §164.504
🟠 **MEDIUM RISKS:**
• 📊 **Analytics Data Not De-identified** → ML model trained on raw patient data
- 🔧 **Fix:** Implement HIPAA safe harbor (remove 18 identifiers) or expert determination
- 📋 **Risk:** If model compromised → patient re-identification possible
• 📱 **SMS Notification Risk** → Phone numbers transmitted in cleartext to Twilio
- 🔧 **Fix:** Use Twilio encrypted endpoints, disable SMS logging in debug mode
- 📋 **Risk:** Moderate (Twilio is BAA-compliant, but best practice to minimize exposure)
---
**Performance & Scalability Issues:**
⚡ **Bottlenecks:**
• 🐌 **Telemedicine Recording Upload** → Full video uploaded synchronously (can be 2GB+)
- 🔧 **Fix:** Implement chunked upload + S3 multipart upload
- 📈 **Improvement:** 10x faster (100MB/s vs 10MB/s)
• 🐌 **Appointment Availability Check** → Queries provider calendar across all services
- 🔧 **Fix:** Cache availability in Redis (invalidate on booking)
- 📈 **Improvement:** 50ms vs 500ms latency
• 🐌 **ML Readmission Prediction** → Synchronous call blocks user experience
- 🔧 **Fix:** Run ML async in background, notify via push notification
- 📈 **Improvement:** User sees result immediately, no UI hang
---
**Modernization Roadmap:**
🗓️ **WEEK 1 (Emergency):**
1️⃣ Audit all logging → remove PII, implement masking library
2️⃣ Enable S3 encryption at rest
3️⃣ Create comprehensive audit log table with immutability constraint
🗓️ **SPRINT 1 (Weeks 2-4):**
4️⃣ Separate databases per service (microservices isolation)
5️⃣ Implement consent management (checkbox + timestamp + IP)
6️⃣ Setup AWS KMS automatic key rotation
7️⃣ Obtain BAAs from all 3rd-party vendors
🗓️ **SPRINT 2 (Weeks 5-8):**
8️⃣ Implement row-level security (RLS) in PostgreSQL
9️⃣ Migrate analytics to safe harbor de-identification
🔟 Add distributed tracing (X-Ray) across telemedicine flows
1️⃣1️⃣ Implement idempotency keys for prescription orders
🗓️ **QUARTER 1 (Months 1-3):**
1️⃣2️⃣ Cache appointments availability in Redis
1️⃣3️⃣ Chunked upload for telemedicine recordings
1️⃣4️⃣ Async ML predictions (Kafka-based)
1️⃣5️⃣ Implement patient data deletion (right to be forgotten)
🗓️ **QUARTER 2 (Months 4-6):**
1️⃣6️⃣ Geo-aware routing for data residency compliance
1️⃣7️⃣ Multi-region backup + disaster recovery testing
1️⃣8️⃣ SOC 2 Type II audit
1️⃣9️⃣ Penetration testing + threat modeling
---
### 📖 SECTION 9 — Documentation Generation
**High-Level Architecture Summary:**
🏗️ The healthcare platform separates concerns into:
- 🔐 **Boundary Layer** → API Gateway enforces authentication, rate limiting, audit logging
- 🏥 **Domain Services** → Patient, Appointment, Prescription (business logic)
- 🎥 **Real-time Services** → Telemedicine (WebSocket, WebRTC)
- 🔗 **Integration Layer** → HL7/FHIR, external EHR systems
- 📊 **Analytics Layer** → Kafka stream processing, ML predictions
- 🛡️ **Compliance Layer** → Encryption, audit trails, consent management
**Data Protection Strategy:**
🔐 **At Rest:**
- AES-256 encryption via AWS KMS
- Separate keys per region (data residency)
- Key rotation every 90 days
- Encrypted file store: S3 + EBS volumes
🔐 **In Transit:**
- TLS 1.3 for all network traffic
- Certificate pinning for mobile clients
- WebSocket connections encrypted (wss://)
- HL7 over secure TCP (not raw SFTP)
🔐 **Access Control:**
- OAuth2 + MFA for providers
- Patient self-service portal (MFA required)
- Role-based access control (RBAC)
- Patient consent for each provider
- Time-limited access tokens (15 min, refresh token 7 days)
**Audit Compliance:**
📋 Every data access logged:
- Who accessed (provider ID, patient ID)
- What resource (patient ID, document ID)
- When (UTC timestamp)
- Why (reason optional, required for sensitive access)
- How (IP address hashed, device type)
- Result (success/failure)
Audit logs stored in immutable PostgreSQL table (no DELETE allowed).
---
## 🧾 FINAL REVERSE ENGINEERING REPORT — TOP 10 RECOMMENDATIONS
**🔴 CRITICAL (Fix in Days):**
1️⃣ 🚨 **Remove all PII from application logs**
- Implement masking library on console.log, Datadog, CloudWatch
- Audit existing logs, redact patient data from retention
- **Owner:** DevOps + Security team
- **Timeline:** 3 days
2️⃣ 🚨 **Enable S3 default encryption for all buckets**
- Enable S3 default encryption (AES-256)
- Enable versioning + MFA delete
- **Owner:** DevOps
- **Timeline:** 1 day
3️⃣ 🚨 **Create immutable audit logging table**
- PostgreSQL table with trigger that prevents DELETE/UPDATE
- Audit all data access (read, write, delete)
- **Owner:** Database team
- **Timeline:** 5 days
---
**🟡 HIGH (Fix in Weeks):**
4️⃣ 🔐 **Separate database per microservice**
- Break monolithic `patients` database into service-specific databases
- Enforce data ownership boundaries
- **Owner:** Architecture team
- **Timeline:** 2 weeks
5️⃣ 🔐 **Implement patient consent management**
- Store signed consent documents (checkbox + timestamp + IP)
- Verify consent before recording/sharing data
- **Owner:** Product + Engineering
- **Timeline:** 1 week
6️⃣ 🔐 **Obtain Business Associate Agreements (BAAs)**
- Twilio, SendGrid, 3rd-party vendors
- Add BAA requirement to vendor selection process
- **Owner:** Legal + Procurement
- **Timeline:** 2 weeks
7️⃣ 🔐 **Setup AWS KMS key rotation**
- Enable automatic key rotation (90-day cycle)
- Monitor key rotation audit logs
- **Owner:** DevOps + Security
- **Timeline:** 3 days
---
**🟠 MEDIUM (Fix in Sprints):**
8️⃣ 📊 **Implement de-identified analytics dataset**
- Remove 18 HIPAA identifiers (name, MRN, etc.)
- Use safe harbor or expert determination
- Separate dataset from operational data
- **Owner:** Data team + Analytics
- **Timeline:** 2 weeks
9️⃣ 🎥 **Implement chunked upload for recordings**
- Replace synchronous upload with multipart S3 upload
- Stream directly to S3 (don't buffer in memory)
- **Owner:** Backend team
- **Timeline:** 1 week
🔟 📍 **Implement geo-aware data routing**
- Route EU patient data to EU region only
- Separate encryption keys per jurisdiction
- Prevent cross-border data transfer
- **Owner:** Architecture team
- **Timeline:** 4 weeks
---
**Test Execution Complete** ✅
By purchasing this prompt, you agree to our terms of service
CLAUDE-5-SONNET
Many software systems outlive their original documentation. Over time, architecture diagrams disappear, developers leave, business logic becomes hidden, and the codebase evolves into a black box. ⚠️
🏗️ Complete architecture reconstruction
🔍 Dependency & module relationship mapping
🔄 Business workflow reconstruction
📊 Data flow & request lifecycle analysis
🗄️ Database & integration architecture
📚 Reverse-engineered technical documentation
🚀 Modernization & refactoring roadmap
Understand an
...more
Added over 1 month ago
