FHIR Subscriptions on Medplum: building real-time healthcare integrations
In today's fast-paced healthcare environment, the ability to respond instantly to critical events can mean the difference between life and death. Whether it's a laboratory result showing dangerous levels, a new patient admission requiring immediate attention, or a medication change that needs urgent review, healthcare systems must be able to react in real-time.
Traditionally, healthcare applications have relied on polling mechanisms to check for updates: constantly querying servers to see if anything has changed. This approach is not only inefficient, consuming unnecessary bandwidth and computational resources, but it also introduces delays that can impact patient care. A system that checks for updates every 15 minutes might miss critical events that require immediate action.
FHIR Subscriptions solve this fundamental problem by inverting the communication model. Instead of applications constantly asking "has anything changed?", they can now say "notify me when something specific happens." This event-driven approach enables true real-time healthcare integrations that are both more efficient and more responsive.
Medplum's implementation of FHIR Subscriptions goes beyond the standard specification, offering advanced features like multiple notification channels, Bot integration for complex workflows, and proprietary extensions for enhanced control over retry policies and security.
Understanding FHIR subscriptions
FHIR Subscriptions are built on several fundamental concepts that work together to create a powerful event notification system:
SubscriptionTopic defines what types of events the system should monitor, such as the creation of new resources, updates to existing ones, or specific state changes.
Subscription is the actual configuration that tells the system what to monitor and where to send notifications. It includes criteria for matching events and channel configuration for delivery.
Channel is the delivery mechanism for notifications, such as webhooks, email, or WebSocket connections.
When a change occurs in your FHIR server, Medplum's subscription engine follows a sophisticated processing pipeline: event detection, criteria evaluation, notification preparation, delivery with retry logic, and comprehensive audit logging. This ensures that events are processed reliably and efficiently, even under high load conditions.
Channel options and configuration
Webhook notifications
Webhooks are the most common channel for system-to-system integrations. When configured, Medplum sends HTTP POST requests to your specified endpoint whenever subscription criteria are met.
Configuration example:
{
"channel": {
"type": "rest-hook",
"endpoint": "https://your-system.com/webhooks/fhir-events",
"payload": "application/fhir+json",
"header": [
"Authorization: Bearer YOUR_API_TOKEN",
"Content-Type: application/fhir+json"
]
}
}
Best practices:
- Always use HTTPS endpoints for security
- Implement proper authentication using API tokens
- Design your webhook endpoint to be idempotent
- Return appropriate HTTP status codes (200 for success, 4xx for client errors)
Email notifications
Email notifications are ideal for human-readable alerts and administrative notifications. Medplum supports rich HTML emails with embedded resource data, perfect for critical lab result alerts, patient admission notifications, and medication reconciliation alerts.
WebSocket connections
WebSocket channels enable real-time bidirectional communication, ideal for interactive applications like real-time dashboards, clinical applications, and live monitoring systems that need immediate updates.
Step-by-step implementation guide
Let's walk through creating a comprehensive subscription system for medication management, a common use case in healthcare applications.
Step 1: create test resources
First, create the foundational resources for our example:
Patient resource:
{
"resourceType": "Patient",
"id": "example-patient-123",
"name": [
{
"given": ["Sarah"],
"family": "Johnson",
"use": "official"
}
],
"telecom": [
{
"system": "email",
"value": "sarah.johnson@example.com"
}
],
"birthDate": "1985-03-15",
"gender": "female"
}
Step 2: create subscription resources
New medication prescription alert:
{
"resourceType": "Subscription",
"id": "medication-prescription-alert",
"status": "active",
"reason": "Alert when new medications are prescribed to monitored patients",
"criteria": "MedicationRequest?patient=Patient/example-patient-123",
"channel": {
"type": "rest-hook",
"endpoint": "https://your-system.com/webhooks/medication-alerts",
"payload": "application/fhir+json",
"header": [
"Authorization: Bearer YOUR_TOKEN_HERE",
"X-Subscription-Type: medication-alert"
]
},
"extension": [
{
"url": "https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",
"valueCode": "create"
}
]
}
Critical lab result email notification:
{
"resourceType": "Subscription",
"id": "critical-lab-alert",
"status": "active",
"reason": "Email alert for critical lab results",
"criteria": "Observation?patient=Patient/example-patient-123&category=laboratory",
"channel": {
"type": "email",
"endpoint": "mailto:dr.smith@hospital.example.com",
"payload": "application/fhir+json",
"header": [
"Subject: CRITICAL LAB RESULT - Immediate Attention Required"
]
},
"extension": [
{
"url": "https://medplum.com/fhir/StructureDefinition/subscription-supported-interaction",
"valueCode": "create"
}
]
}
Step 3: test your subscription
Create a test MedicationRequest to trigger your subscription:
{
"resourceType": "MedicationRequest",
"status": "active",
"intent": "order",
"subject": {
"reference": "Patient/example-patient-123",
"display": "Sarah Johnson"
},
"medicationCodeableConcept": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": "1049502",
"display": "Acetaminophen 325 MG Oral Tablet"
}
]
},
"dosageInstruction": [
{
"text": "Take 1-2 tablets every 4-6 hours as needed for pain"
}
]
}
When you create this MedicationRequest, your webhook endpoint should receive a POST request with the resource data, enabling your system to process the new prescription immediately.
Advanced features and Bot integration
Medplum's proprietary extensions
Medplum extends the standard FHIR Subscription specification with powerful features:
Retry policy configuration:
{
"extension": [
{
"url": "https://medplum.com/fhir/StructureDefinition/subscription-max-attempts",
"valueInteger": 3
}
]
}
HMAC signature verification:
{
"extension": [
{
"url": "
https://www.medplum.com/fhir/StructureDefinition/subscription-secret
",
"valueString": "your-secret-key-here"
}
]
}
Bot integration for advanced workflows
Medplum Bots are serverless functions that can be triggered by subscriptions to perform complex processing on FHIR resources. They're perfect for scenarios that require more than simple notifications.
Example: drug interaction checking bot
import { Bot } from '@medplum/bot-framework';
import { MedicationRequest } from '@medplum/fhirtypes';
export const handler: Bot = async (medplum, event) => {
const medicationRequest = event.resource as MedicationRequest;
// Get existing medications for the patient
const existingMedications = await medplum.searchResources('MedicationRequest', {
patient: medicationRequest.subject.reference.split('/')[1],
status: 'active'
});
// Check for drug interactions
const interactions = await checkDrugInteractions(
medicationRequest.medicationCodeableConcept,
existingMedications
);
if (interactions.length > 0) {
// Create an alert flag
await medplum.createResource({
resourceType: 'Flag',
status: 'active',
category: [{
coding: [{
system: 'http://terminology.hl7.org/CodeSystem/flag-category',
code: 'drug',
display: 'Drug Interaction Alert'
}]
}],
subject: medicationRequest.subject,
text: `Potential interaction detected: ${interactions.join(', ')}`
});
}
};
Security and compliance
HIPAA compliance considerations
Data Encryption: All notifications are encrypted in transit using TLS 1.3, with options for encryption at rest and proper key management.
Access Controls: Implement role-based access control (RBAC) and use the least privilege principle for subscription permissions.
Audit Requirements: Medplum maintains comprehensive audit logs of all subscription activities for compliance monitoring.
Best practices
Authentication security:
- Use unique API tokens for each subscription
- Rotate tokens regularly
- Implement token scoping to limit permissions
- Monitor token usage for suspicious activity
Webhook Security:
- Always use HTTPS endpoints
- Implement HMAC signature verification
- Configure proper retry policies with dead letter queues
- Use reference-only payloads when full resource data isn't needed
Troubleshooting and best practices
Common issues and solutions
Webhook Timeouts: Implement asynchronous processing in your webhook endpoints to acknowledge receipt immediately and process notifications in the background.
Duplicate Notifications: Implement idempotency checking using unique event IDs to prevent duplicate processing.
Failed Delivery: Configure retry policies and dead letter queues to handle temporary failures gracefully.
Performance optimization
- Use specific criteria to minimize unnecessary notifications
- Implement proper indexing on filtered fields
- Use reference-only payloads when full resource data isn't needed
- Monitor key metrics like delivery success rate, latency, and throughput
Monitoring subscription events
Medplum provides comprehensive monitoring capabilities for subscription events. You can view subscription audit events by navigating to:
https://app.medplum.com/Subscription/{{SubscriptionId}}/event
This page displays AuditEvent resources that provide detailed information about each notification sent, including delivery status, timing, and any errors encountered.
For programmatic monitoring, you can query audit events via the API:
const auditEvents = await medplum.searchResources('AuditEvent', {
observer: 'Subscription/{{SubscriptionId}}'
});
Achieving healthcare excellence through FHIR subscription
The combination of standard FHIR Subscription functionality with Medplum's advanced features like Bot integration, multiple notification channels, and proprietary extensions creates a comprehensive toolkit for building sophisticated healthcare integrations.
Whether you're implementing simple notification workflows or complex multi-step automations, Medplum's subscription system provides the reliability, security, and scalability needed for mission-critical healthcare applications. Start with basic webhook notifications and gradually expand to more advanced scenarios as your integration needs grow.
For more detailed information about Medplum's subscription features and Bot system, refer to the official Medplum documentation and explore the extensive examples in their developer resources.