Kulcare Docs
DeveloperCare plansCare planCurrent state

LHR Architecture Overview

What is LHR?

Longitudinal Health Records (LHR) is a system that tracks a patient's complete health story across all their medical visits. Instead of treating each visit as an isolated event, LHR connects the dots between visits to provide a comprehensive view of the patient's health journey.

Executive Summary

This document explains how we're enhancing our current careplan system to create a full Longitudinal Health Record system. The key principle is that we're adding new features without changing or breaking any existing functionality. All current workflows will continue to work exactly as they do today.

Key Benefits

For Doctors:

  • See a patient's complete medical history at a glance
  • Track how conditions improve or worsen over time
  • Get automatic alerts for drug interactions and health risks

For Patients:

  • Better continuity of care across visits
  • Comprehensive health score to track wellness
  • Medication safety through continuity tracking
  • Complete health records accessible when needed

For Clinics:

  • Better patient outcomes through connected care
  • Compliance with ABDM/FHIR standards
  • Population health insights
  • Automated quality reporting

Key Design Decisions

We made several important decisions to ensure the LHR implementation is safe and effective:

1. Integration Approach: Enhance, Don't Replace

We're extending the existing save_history.rb file rather than replacing it. This means:

  • All current code continues to work unchanged
  • New LHR features are added alongside existing functionality
  • We can roll out features gradually without disrupting operations

2. Data Migration: Add New Fields Safely

Instead of changing existing database tables, we're:

  • Adding new columns with default values (so existing code won't break)
  • Using background jobs to populate historical data
  • No downtime required for deployment

3. Problem Tracking: Use Existing Tables

Rather than creating a new patient_problems table, we're enhancing the existing encounter_complaints table by:

  • Adding fields to track problems across visits
  • Linking related complaints between encounters
  • Marking chronic conditions automatically

4. Naming Convention: Careplan → Encounter

We're renaming "Careplan" to "Encounter" because:

  • "Encounter" is the industry-standard term for a medical visit
  • It better describes what the record represents
  • We'll maintain backward compatibility so existing code still works

5. MVP Scope: Core LHR Features

The initial release will include:

  • Health scoring system (0-100 scale showing overall patient wellness)
  • Problem lists that track conditions across visits
  • Medication continuity to track chronic medications across visits
  • Clinical coding support for standardized documentation

System Architecture

The LHR system is built in layers, with each layer having a specific responsibility:

Frontend Layer (React)

The user interface includes:

  • Enhanced Encounter Forms: Capture visit type (walkin, scheduled, telemedicine, home_visit), urgency level (routine, urgent, emergency), and chief complaint (free text)
  • Card-Based LHR Dashboard: Health summary with modular cards:
    • Health Score Card (0-100 scale with trend)
    • Recent Encounters Card (last 3 visits)
    • Active Problems Card (chronic conditions)
    • Current Medications Card (active prescriptions)
    • Recent Vitals Card (BP, weight, temperature)

API Layer (Rails Controllers)

We have two types of APIs:

  • Enhanced Existing APIs: Current endpoints like /encounters accept new UI fields (visit_type, urgency, chief_complaint) and return LHR data when available
  • New LHR APIs: Card-based endpoints like /patients/:id/health_summary that return structured data for dashboard widgets

Service Layer

The core business logic lives here:

  • PatientHistory::SaveHistory: This existing service is enhanced to trigger LHR processing after saving regular data
  • Background Jobs: Heavy calculations like health scoring happen asynchronously to keep the system fast
  • Specialized Services: New services handle health scoring and medication continuity

Model Layer

Database models are enhanced and new ones added:

  • Enhanced Models: Existing models like Encounter get new fields for LHR data
  • New Models: PatientHealthScore and PatientHealthSummary store calculated LHR data

Database Layer (PostgreSQL)

The database changes include:

  • Renamed Tables: careplans becomes encounters (with aliases for backward compatibility)
  • Enhanced Tables: encounter_complaints and encounter_medicines get new fields for tracking across visits
  • New Tables: patient_health_scores and patient_health_summaries store LHR-specific data

How Data Flows Through the System

Current Flow (Unchanged)

When a medical event happens today, here's what occurs:

  1. A medical event (like creating a careplan) triggers save_history.rb
  2. This calls the appropriate save class (like SaveCareplan)
  3. Data is saved to the database
  4. The process completes

This flow continues to work exactly the same with LHR.

Enhanced LHR Flow (Added)

With LHR, we add an extra step after the regular save:

  1. The same medical event triggers save_history.rb
  2. The regular save happens first (ensuring no disruption)
  3. If successful, LHR enhancement is triggered
  4. A background job is queued to:
    • Calculate the patient's health score
    • Link related problems across visits
    • Check for medication interactions
    • Suggest clinical codes
  5. Results are stored in new LHR tables

Important: The LHR enhancement happens in the background, so it doesn't slow down the regular save process. If the LHR enhancement fails for any reason, the original save is unaffected.

Core LHR Features

1. Cross-Encounter Problem Tracking

What it does: Tracks medical problems across multiple visits instead of treating each visit in isolation.

How it works:

  • When a doctor records "Hypertension" in visit 1, the system remembers this
  • In visit 2, when the doctor mentions hypertension again, the system automatically links it to the previous occurrence
  • Over time, the system builds a complete picture of how the condition is progressing

Benefits:

  • Doctors can see if a condition is improving, stable, or worsening
  • Chronic conditions are automatically identified after multiple occurrences
  • No important medical history gets lost between visits

2. Medication Continuity

What it does: Ensures chronic medications are tracked across visits to prevent accidental discontinuation.

How it works:

  • Medications are marked as chronic (long-term) or acute (short-term)
  • When creating a new encounter, chronic medications from previous visits are shown
  • Doctors can select which chronic medications to continue
  • Selected medications are automatically added to the new encounter

Example scenario:

  • Patient was prescribed Lisinopril (marked as chronic) in January
  • In March visit, system shows: "Patient's chronic medications: Lisinopril 10mg daily"
  • Doctor can continue it with same or updated dosage

3. Health Scoring System

What it does: Calculates a wellness score from 0-100 based on multiple health factors.

Components and weights:

  • Vitals (25%): Blood pressure, weight, temperature within normal ranges
  • Problems (30%): Number and severity of active medical conditions
  • Medications (25%): Active medications and chronic medication management
  • Preventive Care (20%): Immunizations, screenings up to date

Example: A patient with controlled blood pressure (good vitals), diabetes (moderate problem), taking medications regularly (good adherence), and up-to-date vaccinations might score 78/100.

4. Clinical Coding Support

What it does: Standardizes medical terminology using international coding systems.

Supported systems:

  • ICD-10/ICD-11: For diagnoses (e.g., "Essential Hypertension" = I10)
  • SNOMED-CT: For clinical findings and procedures
  • RxNorm: For medications (ensures consistent drug names)

Benefits:

  • Enables interoperability with other healthcare systems
  • Required for ABDM compliance
  • Improves reporting and analytics accuracy

Integration Points

Existing Systems (No Changes Required)

All current integrations continue to work without any modifications:

  • Patient Management: Creating and managing patients works exactly as before
  • Appointment System: Scheduling and appointment workflows remain unchanged
  • Billing Integration: Razorpay and billing processes are unaffected
  • Notifications: SMS and email notifications continue as normal
  • Current Reports: All existing reports keep functioning

New LHR Integrations

We're adding new integrations that enhance the system without affecting existing ones:

1. ABDM/FHIR Integration

  • Converts LHR data to FHIR format for sharing with other healthcare systems
  • Enables patients to access their records through ABDM
  • Automatic generation of standardized health records

2. Clinical Decision Support

  • Analyzes patient data to provide real-time alerts
  • Suggests treatment guidelines based on conditions
  • Warns about drug interactions or allergies

3. Population Health Analytics

  • Aggregates data across all patients to identify trends
  • Helps clinics understand common conditions in their patient base
  • Enables preventive care initiatives

4. Quality Measure Reporting

  • Automatically calculates quality metrics
  • Generates reports for regulatory compliance
  • Tracks clinic performance indicators

Performance Considerations

We've designed the LHR system to be fast and scalable:

Database Optimizations

  • Smart Indexing: We're adding indexes on commonly searched fields like patient ID, dates, and status fields
  • JSONB Storage: Flexible fields use PostgreSQL's JSONB type for fast queries on semi-structured data
  • Background Processing: Heavy calculations happen asynchronously so users don't wait

Caching Strategy

To keep the system responsive, we cache frequently accessed data:

  • Patient Health Summaries: Cached for 5 minutes
  • Health Scores: Cached for 1 hour (they don't change frequently)
  • Clinical Codes: Cached for 24 hours (rarely change)

Asynchronous Processing

Different tasks have different priorities:

  • High Priority: Saving encounters (happens immediately)
  • Medium Priority: LHR enhancements like linking problems
  • Low Priority: Health score calculations and report generation

Performance Targets

We're aiming for:

  • API responses in under 200ms
  • Health summary dashboard loads in under 3 seconds
  • Background jobs complete within 1 minute
  • 95% of database queries complete in under 50ms

Security & Compliance

Security and compliance are built into every aspect of the LHR system:

HIPAA Compliance

We ensure patient data protection through:

  • Access Control: Role-based permissions ensure users only see data they're authorized to access
  • Audit Logging: Every access to patient health information is logged with user, timestamp, and action
  • Data Encryption: All patient data is encrypted both in storage (AES-256) and transmission (TLS 1.3)
  • Data Retention: Automatic 7-year retention policy as required by regulations

Clinical Safety

Patient safety is our top priority:

  • Fail-Safe Design: If LHR enhancement fails, the core save operation still succeeds
  • Data Validation: All inputs are validated before saving to prevent errors
  • Alert Prioritization:
    • Critical alerts (red): Drug allergies, severe interactions
    • Warnings (yellow): Abnormal values, potential duplicates
    • Information (green): Recommendations, reminders

Access Control

Different roles have different access levels:

  • Super Admin: Full system access and configuration
  • Clinic Owner: Full access to their clinic's data
  • Doctor: Can read and write their patients' records
  • Nurse: Can update vitals and basic information
  • Receptionist: Read-only access to appointment-related data
  • Patient: Can view their own records through patient portal

Monitoring & Analytics

The LHR system provides comprehensive monitoring to ensure optimal performance and patient care:

Clinical Metrics

We track key health indicators across the patient population:

  • Average Health Score: Shows overall wellness of patients (target: >75)
  • Problem Resolution Time: How quickly conditions are resolved (target: <21 days)
  • Medication Adherence Rate: Percentage of patients taking medications correctly (target: >80%)
  • Chronic Condition Management: How well chronic conditions are controlled (target: >75%)

System Performance

Real-time monitoring of system components:

  • SaveHistory Service: Core saving functionality (target: <100ms)
  • LHR Processor: Background enhancement processing (target: <5s)
  • Health Scoring: Calculation time for health scores (target: <1s)
  • Queue Status: Number of pending, processing, and failed jobs

Data Quality

We monitor data completeness to ensure high-quality records:

  • Chief Complaints: Percentage with proper documentation
  • Clinical Codes: Percentage with standardized codes
  • Medication Lists: Completeness of medication records
  • Problem Linking: Success rate of linking problems across visits

Implementation Roadmap

The LHR implementation will be rolled out in phases to minimize risk:

Phase 1: Foundation

  • Database schema changes (add new columns and tables)
  • Update models with new fields
  • Basic LHR processing framework

Phase 2: Core Features

  • Health scoring algorithm implementation
  • Cross-encounter problem tracking
  • Medication continuity tracking

Phase 3: Advanced Features

  • Clinical coding lookup system
  • ABDM/FHIR data export

Phase 4: Polish & Optimize

  • Performance tuning and optimization
  • UI enhancements and polish
  • Production deployment and monitoring

Summary

The LHR system enhances our current careplan system to provide comprehensive patient health tracking across visits. By following the principle of "enhance, don't replace," we ensure that all existing functionality continues to work while adding powerful new features that improve patient care and clinical efficiency.

Key points to remember:

  • All existing code and workflows continue to work unchanged
  • New features are added through background processing
  • The system is designed to be fail-safe - if LHR fails, core operations continue
  • Implementation is phased to minimize risk
  • Performance is optimized through caching and async processing

Next Steps:

  • Review the database design for detailed schema changes
  • Check the service architecture for implementation details
  • See the API design for new endpoints
  • Review UI alignment for frontend integration

On this page