Monitoring Position
Use AMCDR monitoring to check service health, schema readiness, dependencies, request performance, search indexes and cache warmup. These endpoints help operators investigate problems without exposing clinical content.
Redis supports caching and coordination, while OpenSearch supports search. Monitor both alongside the application. In production, collect AMCDR metrics with Prometheus or a compatible collector, display trends in Grafana, and alert on readiness, latency, error rates, dependency failures and indexing drift.
Live health
GET /health confirms service health, schema revision alignment, and enabled runtime services.
Performance readiness
GET /performance/readiness reports database, schema, Redis, OpenSearch, cache warmup, and probe latency status.
Prometheus metrics
GET /metrics exposes Prometheus text metrics for platform health, request latency, dependencies, and projection state.
Dashboards and alerts
Use Grafana dashboards and Prometheus alert rules for operational visibility, trend analysis, and incident response.
Security Boundary
Monitoring endpoints expose route names, dependency status, deployment settings and performance details. Keep /metrics authenticated and restrict it to the internal scrape network or trusted monitoring proxy.
| Route | Audience | Exposure rule |
|---|---|---|
GET /health | Load balancer, deployment scripts, operators | May be reachable at the API edge if it does not expose secrets or patient data. |
GET /performance/readiness | Authenticated platform operators | Keep authenticated; use for operational diagnosis and deployment verification. |
GET /metrics | Prometheus or compatible scraper | Keep authenticated and network-restricted. Do not expose publicly. |
| Grafana | Platform operators and administrators | Protect with SSO, strong local credentials, and role-based dashboard access. |
| Prometheus | Monitoring administrators | Keep private. Store only operational metrics, not clinical payloads. |
Core Monitoring Flow
Metrics Surface
The /metrics endpoint returns aggregate operational metrics in Prometheus text format. It excludes patient identifiers, composition content and raw payloads.
| Metric family | What it shows | Operational use |
|---|---|---|
amcdr_platform_info | Static platform metadata. | Confirm scrape target identity and version labels. |
amcdr_http_requests_total | Request counts by route template, method, and status class. | Detect 4xx/5xx spikes and high-traffic routes. |
amcdr_http_requests_in_flight | Current in-flight HTTP requests. | Detect saturation or slow downstream calls. |
amcdr_http_request_duration_seconds_bucket | Request duration histogram buckets. | Track p95/p99 latency by route and status. |
amcdr_performance_readiness_state | Readiness state: ok, degraded, not_ready, or unknown. | Primary platform readiness alert signal. |
amcdr_dependency_ready | Readiness gauges for schema, database, Redis, OpenSearch, and optional accelerators. | Identify which runtime dependency degraded platform readiness. |
amcdr_dependency_probe_latency_seconds | Measured dependency probe duration. | Detect slow database, Redis, OpenSearch, or cache calls before hard failure. |
amcdr_ehr_records | Authoritative count of openEHR EHR records in the database. | Track actual CDR EHR containers independently of patient and OpenSearch projection counts. |
amcdr_repository_records | Authoritative database counts by repository resource, including patients, EHRs, compositions, templates, template versions, visible templates, visible template versions, and forms. | Track repository state independently of OpenSearch projection indexes. Template uploads with the same template key increase version counts, while new template keys increase template counts. The visible template metrics apply the same default repository visibility rules as the UI and exclude hidden system templates. |
amcdr_clinical_metric_value | Governed aggregate clinical metric values from the Clinical Metrics Registry. | Track approved clinical aggregates such as active alerts, open encounters, reportable counts, or saved-query indicators. |
amcdr_clinical_metric_status | Latest sample state for each registered clinical metric. | Detect suppressed, failed, stale, or missing clinical metric samples before dashboards mislead operators. |
amcdr_clinical_metric_updated_age_seconds | Age of the latest stored sample. | Alert when a clinical metric has not refreshed within its expected interval. |
amcdr_opensearch_scope_active | OpenSearch projection availability by scope. | Confirm patient, composition, template, and other projection aliases are usable. |
amcdr_opensearch_scope_documents | Projection document counts by scope. | Detect indexing drift, empty indexes, or failed rebuilds. |
amcdr_cache_warmup_owner_active | Cache warmup owner state. | Confirm one backend instance owns periodic warmup work. |
Clinical Metrics Registry
The Clinical Metrics Registry publishes approved clinical aggregates to Prometheus. Define metrics using built-in counters, AQL or saved queries. The registry stores the definitions and latest aggregate samples, which Prometheus collects.
Configuration is available in the application under Analytics → HMIS → Definitions. See the Clinical Metrics Registry guide for the full operator workflow.
Prometheus reads stored aggregate samples without executing AQL. Its metric labels must never contain patient identifiers, MRNs, EHR IDs, composition UIDs, encounter IDs, raw query text or clinical data rows.
Prometheus labels are determined by policy, not by arbitrary query output. AMCDR always adds the metric key and unit, and administrators may add bounded metric labels such as domain=laboratory or indicator_set=hmis. The registry rejects unsafe label keys such as patient, EHR, encounter, visit, MRN, accession, and composition identifiers.
| Registry area | Behavior | Production rule |
|---|---|---|
| Definitions | Clinical metric key, display name, source kind, refresh interval, unit, static safe labels, sensitivity, and minimum group size. | Use lowercase snake_case keys and bounded labels only. |
| Sources | builtin, aql, or saved_query. | AQL and saved-query metrics must return one numeric aggregate as the first result value. |
| Samples | Stored aggregate value, sample status, result metadata, sampled time, and error state. | Dashboards read samples; they do not query clinical tables directly. |
| Suppression | Definitions set minimum_group_size where suppression is required. Small non-zero values below the threshold are suppressed. | Use suppression for sensitive domains such as HIV, pregnancy, safeguarding, genetics, mental health, and rare events. |
| Scheduler | A lightweight backend runtime processes due active definitions on AMCDR_CLINICAL_METRICS_POLL_SECONDS. | Keep scheduler enabled for production dashboards; keep refresh intervals realistic for database load. |
Metric Definition Patterns
Built-in collectors cover a small set of platform-wide counters that remain consistent across deployments. Programme indicators such as births, newborns, deaths, surveillance counts, and HMIS KPIs must be registry definitions backed by AQL or saved queries so the definition, template IDs, labels, refresh interval, and suppression policy are governed without code changes.
| Metric key | Source kind | Meaning | Typical display |
|---|---|---|---|
active_patients | builtin | Active, non-merged patient records. | KPI and trend |
open_encounters | builtin | Open or in-progress encounter records. | KPI and trend |
open_lab_critical_alerts | builtin | Open laboratory critical alerts. | KPI, alert, and trend |
birth_records | aql | Birth-event composition count by configured birth template ID. | KPI and trend |
newborn_records | aql | Newborn assessment or newborn registration composition count by configured newborn template ID. | KPI and trend |
death_notification_records | aql | Death notification composition count by configured death template ID. | KPI and trend |
weekly_reportable_positive_tests | saved_query | Reviewed surveillance or HMIS aggregate maintained as a saved query. | KPI, trend, and alert |
Sample AQL-backed registry definitions are provided in examples/clinical_metrics/clinical_metric_definitions.json. They are draft definitions by default; review template IDs and labels before activating them in production.
Registry API
Clinical metric management is an administrator function. Use these routes for definition governance and operational refresh. The standard Prometheus scrape remains GET /metrics.
| Route | Purpose |
|---|---|
GET /clinical-metrics/builtin | List built-in aggregate collectors available for registration as definitions. |
GET /clinical-metrics/definitions | List configured metric definitions and latest sample summary. |
POST /clinical-metrics/definitions | Create a governed definition. |
PATCH /clinical-metrics/definitions/{metric_key} | Update source, labels, sensitivity, interval, status, or metadata. |
POST /clinical-metrics/definitions/{metric_key}/refresh | Run a manual refresh for one definition. |
GET /clinical-metrics/definitions/{metric_key}/samples | Review recent samples and failure/suppression state. |
POST /clinical-metrics/process-due | Process due active definitions immediately. |
GET /clinical-metrics/prometheus-preview | Preview the same registry metric lines that are included in /metrics. |
Example Definition Patterns
| Metric | Source | Key fields | Labels |
|---|---|---|---|
| Birth records | AQL | Metric key birth_records; parameter birth_template_id=neonatal_birth_record.v1; unit count; refresh every 300 seconds. | domain=vital_events; indicator_set=civil_registration |
| Open laboratory critical alerts | Built-in | Metric key open_lab_critical_alerts; built-in source open_lab_critical_alerts; unit count; refresh every 60 seconds. | domain=laboratory |
| Weekly reportable positive tests | Saved query | Metric key weekly_reportable_positive_tests; saved query key with the same name; sensitive metric; minimum group size 5; refresh every 300 seconds. | domain=surveillance |
Use saved queries for clinical indicators that need review, versioning, and reuse in HMIS or reporting. Use registry definitions to decide which reviewed aggregates become operational telemetry.
CQL and Clinical Intelligence Monitoring
When CQL is enabled, monitor it as part of the clinical intelligence runtime. Translation failures affect library import and compilation. Evaluation failures affect guardrails, safety checks, and Clinical Assistant passive indicators. These services should be observable without exposing patient facts, CQL source containing sensitive local policy, or raw ELM payloads in metric labels.
| Check | Command or signal | Expected result |
|---|---|---|
| Translator service | curl -fsS http://127.0.0.1:8089/health or the deployment-specific translator health route. | Service responds before CQL import or compile workflows are demonstrated. |
| Evaluator service | curl -fsS http://127.0.0.1:8090/health for the AMCDR evaluator route. | Service responds and accepts the configured API key or internal credential. |
| Compiled libraries | AMCDR CQL library state and ELM artifact path. | compiler_state=compiled_external and backend cqframework_translation_service for externally translated libraries. |
| Clinical Assistant status | Patient workspace Clinical Intelligence Engine panel. | Shows synchronized context, guardrails active when configured, available checks, and safety items without automatically generating AI recommendations. |
For a VPS deployment with the CQL compose profile enabled, use the same compose stack as the backend so the service names resolve inside Docker networking.
docker compose \
-f docker-compose.yml \
-f docker-compose.dependencies.yml \
-f docker-compose.vps.yml \
-f docker-compose.cql.yml \
up -d cql-translator cql-evaluator
Performance Readiness
/performance/readiness is the operator-facing diagnosis endpoint. It performs lightweight probes and returns structured readiness details. The endpoint supports deployment verification after migrations, cache changes, search index rebuilds, and optional service changes.
| Status | Meaning | Required action |
|---|---|---|
ok | Schema, database, Redis, OpenSearch, projections, and cache warmup are healthy for high-performance traffic. | Continue standard operation. |
degraded | The clinical API remains available, but a performance dependency or projection requires attention. | Review Redis, OpenSearch, warmup ownership, projection aliases, and probe latency. |
not_ready | The database or schema state is not safe for clinical traffic. | Stop rollout, run migrations, check database connectivity, and verify schema revision. |
unknown | The monitoring collector did not determine runtime readiness. | Inspect backend logs and retry the readiness endpoint. |
Local Monitoring Stack
The repository includes an auxiliary compose stack for local Prometheus and Grafana testing. The Grafana datasource and AMCDR Platform Monitoring dashboard are provisioned from infra/grafana. For local development, generate a short-lived monitoring token and provide it to Prometheus through a mounted secret file or a developer-only override file. Do not commit bearer tokens or production scrape credentials.
docker compose \
-f docker-compose.aux.yml \
-f /tmp/amcdr-monitoring/docker-compose.monitoring.override.yml \
up -d prometheus grafana
| Service | Local URL | Purpose |
|---|---|---|
| Prometheus | http://127.0.0.1:9090 | Scrapes the authenticated backend /metrics endpoint and stores local time series. |
| Grafana | http://127.0.0.1:3000 | Provides dashboards for readiness, dependency state, request rate, latency, and errors. |
| AMCDR backend | http://127.0.0.1:8009 | Serves health, readiness, and metrics for the local stack. |
Use the same monitoring controls in development and production: authenticate metrics requests, keep dashboards outside the clinical request path and exclude patient content from labels.
OpenSearch projection health panels use two different metrics: amcdr_opensearch_scope_active is a boolean active flag where 1 means the projection is usable, while amcdr_opensearch_scope_documents is the projection document count for patients, compositions, and templates.
Grafana Folder Model
Grafana dashboards are provisioned into separate folders so operational runtime monitoring and governed clinical aggregate visibility remain clearly separated.
| Folder | Dashboard | Purpose |
|---|---|---|
| AMCDR / HIS - Platform | AMCDR Platform Monitoring | Runtime health, readiness, HTTP traffic, latency, dependency state, EHR count, Redis/cache warmup, and OpenSearch projection health. |
| AMCDR / HIS - Clinical | AMCDR Clinical Metrics | Governed clinical aggregate samples from the Clinical Metrics Registry, including metric values, sample status, and sample age. |
The clinical folder must use registry-exported aggregate metrics only. It must not contain dashboards that query patient-level data, raw AQL rows, composition payloads, MRNs, EHR identifiers, encounter identifiers, or accession numbers.
VPS Monitoring Startup
Prometheus and Grafana are isolated in docker-compose.monitoring.yml for production-style VPS deployments. They are not created by the core VPS compose command unless this monitoring file is included. Create them with the same AMCDR project name so they join the backend network and resolve backend:8000.
docker compose \
-f docker-compose.yml \
-f docker-compose.dependencies.yml \
-f docker-compose.vps.yml \
-f docker-compose.monitoring.yml \
-f docker-compose.monitoring.auth.yml \
up -d prometheus grafana
Before starting the authenticated VPS monitoring stack, generate AMCDR_METRICS_BEARER_TOKEN if it is not already set, then create the Prometheus bearer-token file from the same value used by the backend.
TOKEN="$(grep '^AMCDR_METRICS_BEARER_TOKEN=' .env | cut -d= -f2-)"
if [ -z "$TOKEN" ]; then
TOKEN="$(openssl rand -hex 32)"
if grep -q '^AMCDR_METRICS_BEARER_TOKEN=' .env; then
sed -i "s|^AMCDR_METRICS_BEARER_TOKEN=.*|AMCDR_METRICS_BEARER_TOKEN=$TOKEN|" .env
else
printf '\nAMCDR_METRICS_BEARER_TOKEN=%s\n' "$TOKEN" >> .env
fi
fi
mkdir -p infra/prometheus/secrets
printf '%s\n' "$TOKEN" > infra/prometheus/secrets/amcdr_metrics_bearer.token
chmod 600 infra/prometheus/secrets/amcdr_metrics_bearer.token
| Setting | Production guidance |
|---|---|
AMCDR_PROMETHEUS_HOST_BIND | Keep 127.0.0.1 unless a private monitoring network or protected Nginx location is configured. |
AMCDR_GRAFANA_HOST_BIND | Keep 127.0.0.1 unless Grafana is protected by SSO, VPN, or an internal-only proxy. |
GRAFANA_ADMIN_PASSWORD | Set a strong password before first start. Do not use the development default on VPS. |
AMCDR_PROMETHEUS_RETENTION | Default is 15d; increase only when disk capacity is planned. |
The monitoring compose file sets restart: unless-stopped and uses persistent Prometheus and Grafana volumes. After the services have been created once, Docker will restart them automatically after a container, Docker daemon, or host reboot.
Grafana Proxy Environment
Put Grafana proxy settings in the VPS environment file at /opt/amcdr/repo/.env. Compose reads this file and passes the referenced Grafana variables into the container.
AMCDR_GRAFANA_HOST_BIND=127.0.0.1
GRAFANA_ADMIN_PASSWORD=replace-with-strong-password
GF_SERVER_DOMAIN=grafana.sandbox.hygeoniq.com
GF_SERVER_ROOT_URL=https://grafana.sandbox.hygeoniq.com/
GF_SECURITY_COOKIE_SECURE=true
GF_USERS_ALLOW_SIGN_UP=false
After changing Grafana environment values, recreate only Grafana so the new settings are applied.
docker compose \
-f docker-compose.yml \
-f docker-compose.dependencies.yml \
-f docker-compose.vps.yml \
-f docker-compose.monitoring.yml \
-f docker-compose.monitoring.auth.yml \
up -d --force-recreate grafana
Prometheus Scrape Configuration
Use service discovery or static targets depending on the deployment model. The example below shows a single backend target. Production deployments must store credentials in the platform secret store or Prometheus secret files.
Set AMCDR_METRICS_BEARER_TOKEN on the backend and put the same value in the Prometheus credentials_file. This keeps /metrics authenticated without using an expiring user session token.
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: amcdr-backend
metrics_path: /metrics
authorization:
type: Bearer
credentials_file: /etc/prometheus/secrets/amcdr_metrics_bearer.token
static_configs:
- targets:
- backend:8000
Kubernetes Automatic Discovery
AMCDR Kubernetes Services and backend pods include standard Prometheus scrape annotations. Run scripts/k8s/enable-monitoring.sh after the backend is deployed. The command checks that AMCDR is running on Kubernetes before making changes.
When Prometheus Operator CRDs are available, the command automatically applies k8s/optional/monitoring, identifies the active Prometheus custom resource, copies its ServiceMonitor, rule and namespace selector labels, opens the namespace-labelled NetworkPolicy path, and publishes amcdr-platform-monitoring.json as a Grafana dashboard ConfigMap. This avoids hard-coding a Helm release name or monitoring namespace selector.
# Default: select the first Prometheus custom resource
scripts/k8s/enable-monitoring.sh
# Cluster with more than one Prometheus instance
AMCDR_PROMETHEUS_NAMESPACE=monitoring \
AMCDR_PROMETHEUS_NAME=kube-prometheus-stack-prometheus \
scripts/k8s/enable-monitoring.sh
kubectl get servicemonitor,prometheusrule -n amcdr
kubectl get networkpolicy allow-prometheus-metrics -n amcdr
If Prometheus Operator is absent, the activator leaves annotation discovery enabled and exits successfully. Configure standalone in-cluster Prometheus with infra/prometheus/prometheus.kubernetes.yml and mount the dedicated token at /etc/prometheus/secrets/amcdr_metrics_bearer.token.
AMCDR_METRICS_BEARER_TOKEN into Secret amcdr-secrets through External Secrets, Secrets Store CSI, or the approved production secret workflow. Do not apply the example secret unchanged and do not use a staff session token.Recommended Grafana Panels
Platform Monitoring Folder
| Panel | PromQL example | Purpose |
|---|---|---|
| Performance readiness | amcdr_performance_readiness_state{state="ok"} | Show whether the platform is fully ready. |
| HTTP request rate | sum by (route, method) (rate(amcdr_http_requests_total[5m])) | Track traffic by route family. |
| HTTP 5xx rate | sum(rate(amcdr_http_requests_total{status_code=~"5.."}[5m])) | Detect backend errors rapidly. |
| p95 latency | histogram_quantile(0.95, sum by (le, route) (rate(amcdr_http_request_duration_seconds_bucket[5m]))) | Show slow routes and regressions. |
| Dependency readiness | amcdr_dependency_ready{dependency!="cache_warmup"} | Display core schema, database, Redis, and OpenSearch state. |
| EHRs | max(amcdr_ehr_records) | Show authoritative openEHR EHR container count. |
| Templates / versions | max(amcdr_repository_records{resource="templates_visible"}) and max(amcdr_repository_records{resource="template_versions_visible"}) | Show user-visible template keys and uploaded visible template versions. Use templates and template_versions for raw database totals. |
| Requests in flight | amcdr_http_requests_in_flight | Show current backend request pressure. |
Clinical Metrics Folder
| Panel | PromQL example | Purpose |
|---|---|---|
| Clinical KPI values | amcdr_clinical_metric_value | Show the current value of each registered clinical aggregate as stat KPIs. |
| Clinical metric values | amcdr_clinical_metric_value | Show governed aggregate clinical indicators by metric key. |
| Clinical metric status | amcdr_clinical_metric_status{sample_status!="completed"} == 1 | Detect suppressed, failed, stale, or missing samples. |
| Clinical metric sample age | amcdr_clinical_metric_updated_age_seconds | Detect metrics that are not refreshing on schedule. |
Use stat panels for current totals, such as open encounters, pending MPI reviews or programme activity. Use time-series panels to follow changes, investigate spikes or compare activity before and after a workflow change.
Recommended Alerts
| Alert | Condition | Operator response |
|---|---|---|
| AMCDRNotReady | amcdr_performance_readiness_state{state="not_ready"} == 1 for more than one scrape window. | Block rollout, inspect migrations, database connectivity, and schema revision. |
| AMCDRDegraded | amcdr_performance_readiness_state{state="degraded"} == 1 for 2-5 minutes. | Review dependencies and projection health before clinical users report slowness. |
| AMCDRHighErrorRate | 5xx request rate exceeds the accepted operational threshold. | Inspect backend logs, recent deployment changes, and failing route families. |
| AMCDRHighLatency | p95 latency exceeds the route-specific SLO. | Check database, Redis, OpenSearch, CQL, terminology, and external service latency. |
| AMCDRDependencyDown | amcdr_dependency_ready{dependency!="cache_warmup"} == 0 for a critical dependency. | Restore the dependency or fail over according to the deployment runbook. |
| AMCDRSearchProjectionEmpty | Expected OpenSearch projection document count is zero after warmup or reindex. | Run search status checks and rebuild the affected projection scope. |
| AMCDRClinicalMetricFailed | amcdr_clinical_metric_status{sample_status="failed"} == 1 for a registered metric. | Review the definition, saved query or AQL, source tables, and backend logs. |
| AMCDRClinicalMetricStale | amcdr_clinical_metric_status{sample_status="stale"} == 1 or sample age exceeds the definition interval target. | Check the clinical metrics scheduler and database query latency. |
Operational Checks After Deployment
- Confirm
GET /healthreturnsstatus=okand the schema revision matches the application. - Run
GET /performance/readinesswith an authenticated operator token and confirmstatus=ok. - Confirm Prometheus target
amcdr-backendisupand the last scrape has no authentication error. - Open Grafana and confirm the AMCDR platform dashboard shows readiness, request rate, dependency state, and OpenSearch projection state.
- If clinical metrics are configured, run
POST /clinical-metrics/process-dueor wait for the scheduler, then confirmamcdr_clinical_metric_statusis visible in Prometheus. - Verify Redis and OpenSearch exporter targets if infrastructure exporters are enabled.
- Trigger a low-risk authenticated request and confirm HTTP request counters and latency histograms update.
- Review backend logs for migration, cache warmup, OpenSearch, terminology, CQL, MediServe, and sidecar connectivity warnings.
Production Guidance
- Keep monitoring outside the clinical request path. Scraping and dashboards must not slow patient workflows.
- Keep metric labels bounded. Do not add patient identifiers, composition UIDs, raw query text, or clinical values as labels.
- Use the Clinical Metrics Registry for aggregate clinical telemetry. Do not make Prometheus run AQL directly and do not export row-level clinical data into monitoring systems.
- Monitor Redis and OpenSearch capacity and availability alongside application performance.
- Use dashboard trends to validate that new releases remain fast after migrations, template imports, reindexing, and cache warmup.
- Use alert thresholds that match the deployment tier. A national or regional platform must use stricter latency and dependency targets than a development deployment.
- Keep monitoring credentials rotated and separate from user login credentials.