EKG Instan by dr. RFS

Inspiration

In emergency medicine, every second counts. When a patient arrives with chest pain, the ECG strip is often the first diagnostic tool — but interpreting it requires specialized training that isn't always available, especially in underserved communities. I've seen firsthand how delayed ECG interpretation can mean the difference between life and death.

The idea for EKG Instan came from a simple observation: what if reading an ECG was as easy as sending a WhatsApp message to a doctor? With advances in multimodal AI models, we finally have the technology to make this vision a reality.

What it does

EKG Instan is a medical AI assistant that lives inside the apps people already use — Telegram and WhatsApp. No downloads. No new accounts. Just open your chat, photograph an ECG strip with your phone camera, and send it — like sending a photo to a specialist for consultation.

In under 30 seconds, the AI:

  1. Analyzes the ECG for rhythm, morphology, and abnormalities across 68 clinical scenarios
  2. Detects clinical scenarios: Normal Sinus Rhythm, AFib, STEMI, Poor Quality, or Not ECG
  3. Flags critical findings with urgency alerts for immediate review
  4. Delivers a structured 15-section report with confidence scores and pixel-level evidence

Every report includes a medical disclaimer reminding users to consult a cardiologist — because AI should augment, not replace, clinical judgment.

How we built it

Architecture:

User (WhatsApp/Telegram) → Webhook → Node.js Backend → AI Providers (Gemini/Qwen) → User
                                          ↓
                                    PostgreSQL (Drizzle ORM)

Future Architecture: As funding permits, we plan to migrate the entire provider layer to a GPT frontier model (e.g., GPT-5.6) for superior clinical reasoning, with a provider-agnostic architecture that makes the switch seamless.

Tech Stack:

  • Backend: Node.js + Express + TypeScript
  • Database: PostgreSQL + Drizzle ORM
  • AI Models: Google Gemini (primary) + OpenRouter/Qwen — planned upgrade to GPT frontier model
  • Messaging: Telegram Bot API + WhatsApp Business API
  • Infrastructure: UpCloud VPS + Docker + Caddy reverse proxy
  • Deployment: Systemd service with webhook-based async processing

Future Tech Stack: With sufficient funding, we intend to consolidate on a single GPT frontier model provider, simplifying the architecture, reducing multi-provider overhead, and significantly improving ECG interpretation accuracy.

Codex Contribution:

OpenAI Codex was the primary development tool used throughout this project. Specifically:

  1. Architecture Design — Codex designed the entire system architecture including the async webhook processing pipeline, provider pattern for multi-model AI support, and the plan-based quota system
  2. Backend Implementation — Codex wrote the complete Node.js/Express/TypeScript backend including routes, services, providers, and database schema
  3. AI Prompt Engineering — Codex designed the 68-scenario ECG reading prompt with pixel-level evidence requirements, few-shot examples, and differential diagnosis logic
  4. Multi-Pass Verification — Codex implemented the dual-call verification system that cross-checks AI readings for accuracy
  5. Quality Gates — Codex built the uncertainty propagation system that rejects readings with too many uncertain measurements
  6. Medical Safety Features — Codex implemented critical alerts, medical disclaimers, and structured clinical reports
  7. Infrastructure — Codex configured the VPS deployment, Caddy reverse proxy, PostgreSQL persistence, and systemd service management
  8. Testing — Codex wrote 30 automated tests covering ECG scenarios, quota management, and provider switching
  9. Debugging — Codex diagnosed and fixed production issues including hallucination prevention, malformed AI responses, and null safety guards

Key Design Decisions (with Codex):

  1. Async webhook processing — Respond immediately (200 OK), run AI in the background
  2. Runtime model switching — Admin can toggle between AI models without restart — future: GPT frontier model as default
  3. Plan-based quota system — Free trial (2 lifetime scans), paid tiers (10-200 monthly)
  4. In-memory fallback — Works even when database is unavailable
  5. Medical safety — Critical alerts trigger explicit warnings for urgent findings

Challenges we ran into

1. AI Model Reliability

Different ECG quality requires different handling. We implemented a validation layer that first assesses image quality before attempting interpretation — rejecting poor quality or non-ECG images with clear feedback. We plan to address this further by upgrading to a GPT frontier model, which offers stronger multimodal reasoning for medical image analysis.

2. AI Hallucination Prevention

Early versions allowed the AI to report findings not visible in the image. Codex redesigned the prompt to require pixel-level evidence for every measurement, with explicit rules: "For each finding, you MUST mention the specific lead (V1, V2, II, aVR, etc) you see, the position on the image, and WHAT YOU SEE on the pixel." A GPT frontier model would further reduce hallucination through its improved instruction-following and reasoning capabilities.

3. Quota Management Across Restarts

Early versions stored quotas in memory, resetting on every service restart. We solved this with PostgreSQL-backed persistence using Drizzle ORM, implementing daily/monthly counters with atomic updates.

4. Webhook Processing Latency

Telegram webhooks require a fast response (<5s), but AI interpretation takes 10-30s. We decoupled the webhook acknowledgment from AI processing — the bot responds "Processing..." immediately, then sends the full report asynchronously.

5. Medical Accuracy vs. Accessibility

Balancing technical simplicity with clinical rigor was challenging. We implemented:

  • Structured report formats (Rate, Rhythm, Axis, Intervals, Morphology)
  • Confidence scores for each finding
  • R-R interval regularity analysis (Regular/Regularly irregular/Irregularly irregular)
  • Critical alert thresholds for life-threatening patterns

6. Malformed AI Response Handling

Gemini sometimes returns JSON missing expected fields. Codex added retry logic and null safety guards to ensure the bot never crashes — it gracefully degrades to a simplified report when the full analysis is unavailable. Migrating to a GPT frontier model would largely eliminate this issue through its more consistent structured output adherence.

Accomplishments that we're proud of

#1: Real-Time Clinical Impact

The bot has successfully analyzed ECGs from test users, with AI interpretation matching cardiologist-level accuracy for common scenarios (Normal, AFib, STEMI detection).

#2: Zero-Friction User Experience

No app download required. Users simply open WhatsApp/Telegram, send a photo, and get a diagnosis. It feels exactly like texting a doctor for consultation.

#3: Production-Ready Architecture

  • 30/30 automated tests passing
  • PostgreSQL persistence surviving service restarts
  • Runtime model switching without downtime
  • Comprehensive error handling and fallbacks

#4: Medical Safety Built-In

Every response includes:

  • Medical disclaimer
  • Critical alerts for urgent findings
  • Confidence scores for transparency
  • Structured clinical reports with 15 sections

#5: Scalable Infrastructure

Deployed on UpCloud VPS with:

  • Docker containerization
  • Caddy reverse proxy with auto-HTTPS
  • Systemd service management
  • Webhook-based architecture supporting 2B+ WhatsApp users

What we learned

1. AI in Healthcare Requires Guardrails

Multimodal AI models are powerful, but medical applications demand:

  • Clear disclaimers about AI limitations
  • Confidence scoring for transparency
  • Human-in-the-loop validation
  • Regulatory compliance considerations

2. User Experience Trumps Technical Complexity

The hardest part wasn't building the AI — it was making it feel natural. Users shouldn't need to learn new software; they should just send a photo like they would to a friend.

3. Persistence is Non-Negotiable

Early in-memory storage taught us that medical data must persist across restarts. PostgreSQL + Drizzle ORM provided the reliability we needed.

4. Async Processing is Critical

Decoupling webhook acknowledgment from AI processing transformed the user experience from frustrating (waiting 30s for a response) to instant (acknowledgment in <1s).

5. Medical Disclaimer is Not Optional

We learned that every AI health tool must clearly communicate:

  • AI is a tool, not a replacement for doctors
  • Critical findings require immediate medical attention
  • Users should always consult healthcare professionals

6. Codex Accelerated Development Dramatically

What would have taken weeks of manual coding was accomplished in days. Codex's ability to understand complex medical domain requirements, write type-safe TypeScript, and implement production-grade error handling was invaluable.

What's next for EKG Instan

Immediate Priority: GPT Frontier Model Upgrade

With sufficient funding, our first priority is migrating the entire AI provider layer to a GPT frontier model. This will:

  • Improve ECG interpretation accuracy across all 68 scenarios
  • Reduce hallucination through stronger reasoning and instruction-following
  • Simplify architecture by consolidating on a single provider
  • Enable more nuanced clinical reasoning and differential diagnosis

Short-Term (3-6 months)

  • GPT frontier model integration — Replace Gemini/Qwen with a single GPT frontier model
  • Multi-language support — Expand beyond Indonesian to English, Malay, Thai
  • Clinic dashboard — Web portal for healthcare providers to manage patients
  • Batch analysis — Upload multiple ECGs for comparative analysis
  • Export functionality — PDF reports for medical records

Medium-Term (6-12 months)

  • FDA/CE marking — Regulatory approval for clinical use
  • EHR integration — Connect with hospital systems (HL7/FHIR)
  • Wearable support — Apple Watch, Fitbit, and other device ECGs
  • Telemedicine features — Video consultation with AI pre-analysis

Long-Term (1-2 years)

  • Global expansion — Deploy in 10+ countries across Southeast Asia
  • Research partnerships — Collaborate with medical institutions
  • Advanced AI — Real-time continuous monitoring, predictive analytics
  • Open API — Allow third-party developers to build on our platform

EKG Instan — Because every heartbeat matters, and every community deserves access to cardiac diagnostics.

Built With

Share this project:

Updates