Notification Service
Overview
The Notification Service is responsible for sending alerts, reminders, and messages to patients, healthcare providers, and pharmacies across multiple channels (SMS, Email, Push Notifications).
Service Information
| Property | Value |
|---|---|
| Service Name | notification-service |
| Namespace | app-stack |
| Port | 8080 |
| Protocol | HTTP/REST |
| Health Check | /health |
| Metrics | /metrics (Prometheus) |
Architecture
Key Features
Multi-Channel Support
- SMS: Via local Egyptian providers (Vodafone, Etisalat) or Twilio
- Email: SMTP with template support
- Push Notifications: iOS (APNS) and Android (FCM)
- WhatsApp: WhatsApp Business API for rich messaging
Message Types
1. Patient Notifications
- ✅ Prescription ready for pickup
- ✅ Medication refill reminders
- ✅ Appointment reminders
- ✅ Drug recall alerts
- ✅ Insurance coverage updates
2. Provider Notifications
- ✅ High-risk drug interaction alerts (URGENT)
- ✅ Patient allergy warnings
- ✅ Prescription status updates
- ✅ Regulatory compliance alerts
3. Pharmacy Notifications
- ✅ New prescription available
- ✅ Stock alerts (low inventory)
- ✅ Insurance authorization approved/rejected
- ✅ Patient waiting for medication
4. Administrative Notifications
- ✅ System health alerts
- ✅ Audit trail reports
- ✅ Compliance reports
- ✅ Public health announcements
API Endpoints
Send Notification
http
POST /api/v1/notifications
Content-Type: application/json
Authorization: Bearer <token>
{
"type": "sms",
"recipient": "+201234567890",
"template": "prescription_ready",
"variables": {
"patientName": "أحمد محمد",
"pharmacyName": "صيدلية النور",
"prescriptionId": "RX-2024-001234"
},
"priority": "normal",
"metadata": {
"prescriptionId": "RX-2024-001234",
"source": "prescription-service"
}
}Response:
json
{
"notificationId": "not-uuid-here",
"status": "queued",
"estimatedDelivery": "2024-01-15T10:30:00Z",
"queuePosition": 5
}Get Notification Status
http
GET /api/v1/notifications/{notificationId}
Authorization: Bearer <token>Response:
json
{
"notificationId": "not-uuid-here",
"type": "sms",
"status": "delivered",
"sentAt": "2024-01-15T10:30:45Z",
"deliveredAt": "2024-01-15T10:30:47Z",
"recipient": "+201234567890",
"provider": "vodafone-egypt",
"cost": 0.05,
"metadata": {
"prescriptionId": "RX-2024-001234"
}
}Get Notification History
http
GET /api/v1/notifications/history?userId=patient-123&limit=50
Authorization: Bearer <token>Message Templates
Templates support multiple languages (Arabic, English) with RTL support.
Template: Prescription Ready (SMS)
Arabic:
مرحبا {{patientName}}،
روشتتك رقم {{prescriptionId}} جاهزة للصرف من {{pharmacyName}}.
الرجاء إحضار بطاقة الهوية والتأمين.English:
Hello {{patientName}},
Your prescription {{prescriptionId}} is ready for pickup at {{pharmacyName}}.
Please bring your ID and insurance card.Template: Drug Interaction Alert (Email)
html
<div dir="rtl">
<h2 style="color: #d32f2f;">⚠️ تنبيه تفاعل دوائي خطير</h2>
<p>دكتور {{doctorName}}،</p>
<p>تم اكتشاف تفاعل دوائي محتمل الخطورة:</p>
<ul>
<li><strong>الدواء الأول:</strong> {{drug1}}</li>
<li><strong>الدواء الثاني:</strong> {{drug2}}</li>
<li><strong>مستوى الخطورة:</strong> {{severity}}</li>
</ul>
<p><strong>التوصية:</strong> {{recommendation}}</p>
<p>الرجاء مراجعة الروشتة رقم: {{prescriptionId}}</p>
</div>Message Queue System
Uses Redis for high-performance queueing with priority lanes:
Rate Limiting & Cost Control
Per-Channel Limits
| Channel | Rate Limit | Cost per Message | Daily Budget |
|---|---|---|---|
| SMS | 100/sec | 1.50 EGP | 150,000 EGP |
| 1000/sec | 0.03 EGP | 15,000 EGP | |
| Push | 10,000/sec | Free | N/A |
| 50/sec | 0.60 EGP | 60,000 EGP |
Provider Failover
Environment Variables
bash
# Service Configuration
NOTIFICATION_SERVICE_PORT=8080
NOTIFICATION_LOG_LEVEL=info
# Redis Configuration
REDIS_HOST=redis.data-stack.svc.cluster.local
REDIS_PORT=6379
REDIS_PASSWORD=${REDIS_PASSWORD} # from Vault
# PostgreSQL
DB_HOST=postgresql.data-stack.svc.cluster.local
DB_PORT=5432
DB_NAME=notification_db
DB_USER=notification_service
DB_PASSWORD=${DB_PASSWORD} # from Vault
# SMS Providers
SMS_PRIMARY_PROVIDER=vodafone-egypt
SMS_VODAFONE_API_KEY=${SMS_VODAFONE_API_KEY} # from Vault
SMS_VODAFONE_SENDER_ID=HealthFlow
SMS_SECONDARY_PROVIDER=etisalat-egypt
SMS_ETISALAT_API_KEY=${SMS_ETISALAT_API_KEY} # from Vault
# Email Configuration
EMAIL_SMTP_HOST=smtp.gmail.com
EMAIL_SMTP_PORT=587
EMAIL_FROM=noreply@healthflow.eg
EMAIL_USERNAME=${EMAIL_USERNAME} # from Vault
EMAIL_PASSWORD=${EMAIL_PASSWORD} # from Vault
# Push Notifications
FCM_SERVER_KEY=${FCM_SERVER_KEY} # from Vault
APNS_CERT_PATH=/secrets/apns-cert.p12
APNS_CERT_PASSWORD=${APNS_CERT_PASSWORD} # from Vault
# WhatsApp Business API
WHATSAPP_BUSINESS_ID=${WHATSAPP_BUSINESS_ID}
WHATSAPP_API_KEY=${WHATSAPP_API_KEY} # from Vault
WHATSAPP_PHONE_NUMBER=+201234567890
# Rate Limiting
RATE_LIMIT_SMS_PER_SECOND=100
RATE_LIMIT_EMAIL_PER_SECOND=1000
RATE_LIMIT_PUSH_PER_SECOND=10000
# Cost Controls
DAILY_BUDGET_SMS=5000
DAILY_BUDGET_EMAIL=500
DAILY_BUDGET_WHATSAPP=2000
# Service Discovery
CONSUL_ADDRESS=consul.discovery-stack.svc.cluster.local:8500
CONSUL_SERVICE_NAME=notification-service
CONSUL_HEALTH_CHECK_INTERVAL=10sKubernetes Deployment
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: notification-service
namespace: app-stack
spec:
replicas: 3
selector:
matchLabels:
app: notification-service
template:
metadata:
labels:
app: notification-service
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
spec:
serviceAccountName: notification-service
containers:
- name: notification-service
image: healthflow/notification-service:v1.2.0
ports:
- containerPort: 8080
name: http
env:
- name: NOTIFICATION_SERVICE_PORT
value: "8080"
- name: REDIS_HOST
value: redis.data-stack.svc.cluster.local
- name: DB_HOST
value: postgresql.data-stack.svc.cluster.local
envFrom:
- secretRef:
name: notification-secrets
volumeMounts:
- name: apns-cert
mountPath: /secrets
readOnly: true
resources:
limits:
cpu: "1"
memory: 1Gi
requests:
cpu: "500m"
memory: 512Mi
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
volumes:
- name: apns-cert
secret:
secretName: apns-certificateDependencies
Internal Services
- Redis - Message queue and caching
- PostgreSQL - Notification history and templates
- Consul - Service discovery
- Vault - Secrets management
External Services
- Vodafone Egypt API - Primary SMS provider
- Etisalat Egypt API - Secondary SMS provider
- SendGrid / Local SMTP - Email delivery
- Firebase Cloud Messaging - Android push notifications
- Apple Push Notification Service - iOS push notifications
- WhatsApp Business API - WhatsApp messaging
Monitoring & Metrics
Key Metrics
promql
# Notification throughput
rate(notifications_sent_total[5m])
# Delivery success rate
rate(notifications_delivered_total[5m]) / rate(notifications_sent_total[5m])
# Average delivery time
histogram_quantile(0.95, rate(notification_delivery_duration_seconds_bucket[5m]))
# Queue depth by priority
notification_queue_depth{priority="critical"}
# Daily cost by channel
sum(increase(notification_cost_total[24h])) by (channel)Alerts
yaml
groups:
- name: notification_alerts
rules:
- alert: HighNotificationFailureRate
expr: rate(notifications_failed_total[5m]) > 0.1
for: 5m
labels:
severity: warning
annotations:
summary: "High notification failure rate"
description: "{{ $value }}% of notifications are failing"
- alert: SMSBudgetExceeded
expr: sum(increase(notification_cost_total{channel="sms"}[24h])) > 5000
labels:
severity: critical
annotations:
summary: "Daily SMS budget exceeded"
- alert: NotificationQueueBacklog
expr: notification_queue_depth > 10000
for: 10m
labels:
severity: warning
annotations:
summary: "Notification queue has significant backlog"Security
Authentication
- API Key - For service-to-service communication
- JWT - For user-facing endpoints
- mTLS - For external provider connections
Data Protection
- All PII (phone numbers, emails) encrypted at rest
- Notification content encrypted in transit
- Message history retention: 90 days
- Auto-purge of sensitive data after delivery
Compliance
- GDPR-compliant opt-out management
- Egypt Data Protection Law compliance
- Audit logging of all notifications
- Consent tracking for marketing messages
Troubleshooting
Issue: SMS Not Being Delivered
bash
# Check service status
kubectl logs -n app-stack deployment/notification-service
# Check Redis queue
kubectl exec -n data-stack redis-0 -- redis-cli LLEN notification:queue:high
# Check provider status
curl -H "Authorization: Bearer <token>" \
https://api.healthflow.eg/notification/v1/providers/statusIssue: High Delivery Latency
bash
# Check worker count
kubectl get pods -n app-stack -l app=notification-service
# Check queue depth
kubectl exec -n data-stack redis-0 -- redis-cli INFO
# Scale up workers
kubectl scale deployment notification-service --replicas=6 -n app-stackBest Practices
Always set priority correctly
- Critical: Drug interaction alerts
- High: Prescription ready
- Normal: Refill reminders
- Low: Marketing/surveys
Use templates for consistency
- Maintain bilingual templates (Arabic/English)
- Test RTL rendering
- Include unsubscribe links
Implement retry logic
- Max 3 retries with exponential backoff
- Fallback to alternative channels if primary fails
Monitor costs
- Track daily spend per channel
- Set budget alerts
- Optimize message content to reduce SMS segments
Next Steps
- Prescription Service - Triggers notifications
- Dispense Service - Pickup notifications
- CDSS - Critical safety alerts
- Architecture Review - Healthcare compliance