Operations

Platform Monitoring

Monitor service health, dependencies, performance, and clinical metrics with Prometheus, Grafana, and alerts.

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.

RouteAudienceExposure rule
GET /healthLoad balancer, deployment scripts, operatorsMay be reachable at the API edge if it does not expose secrets or patient data.
GET /performance/readinessAuthenticated platform operatorsKeep authenticated; use for operational diagnosis and deployment verification.
GET /metricsPrometheus or compatible scraperKeep authenticated and network-restricted. Do not expose publicly.
GrafanaPlatform operators and administratorsProtect with SSO, strong local credentials, and role-based dashboard access.
PrometheusMonitoring administratorsKeep private. Store only operational metrics, not clinical payloads.

Core Monitoring Flow

Production telemetry path
AMCDR backend/health, /performance/readiness, /metrics
->
PrometheusScrape, store, evaluate rules
->
GrafanaDashboards, trends, drill-down
->
AlertingDegraded readiness, latency, 5xx, dependency failures

Metrics Surface

The /metrics endpoint returns aggregate operational metrics in Prometheus text format. It excludes patient identifiers, composition content and raw payloads.

Metric familyWhat it showsOperational use
amcdr_platform_infoStatic platform metadata.Confirm scrape target identity and version labels.
amcdr_http_requests_totalRequest counts by route template, method, and status class.Detect 4xx/5xx spikes and high-traffic routes.
amcdr_http_requests_in_flightCurrent in-flight HTTP requests.Detect saturation or slow downstream calls.
amcdr_http_request_duration_seconds_bucketRequest duration histogram buckets.Track p95/p99 latency by route and status.
amcdr_performance_readiness_stateReadiness state: ok, degraded, not_ready, or unknown.Primary platform readiness alert signal.
amcdr_dependency_readyReadiness gauges for schema, database, Redis, OpenSearch, and optional accelerators.Identify which runtime dependency degraded platform readiness.
amcdr_dependency_probe_latency_secondsMeasured dependency probe duration.Detect slow database, Redis, OpenSearch, or cache calls before hard failure.
amcdr_ehr_recordsAuthoritative count of openEHR EHR records in the database.Track actual CDR EHR containers independently of patient and OpenSearch projection counts.
amcdr_repository_recordsAuthoritative 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_valueGoverned 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_statusLatest 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_secondsAge of the latest stored sample.Alert when a clinical metric has not refreshed within its expected interval.
amcdr_opensearch_scope_activeOpenSearch projection availability by scope.Confirm patient, composition, template, and other projection aliases are usable.
amcdr_opensearch_scope_documentsProjection document counts by scope.Detect indexing drift, empty indexes, or failed rebuilds.
amcdr_cache_warmup_owner_activeCache 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 areaBehaviorProduction rule
DefinitionsClinical 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.
Sourcesbuiltin, aql, or saved_query.AQL and saved-query metrics must return one numeric aggregate as the first result value.
SamplesStored aggregate value, sample status, result metadata, sampled time, and error state.Dashboards read samples; they do not query clinical tables directly.
SuppressionDefinitions 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.
SchedulerA 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 keySource kindMeaningTypical display
active_patientsbuiltinActive, non-merged patient records.KPI and trend
open_encountersbuiltinOpen or in-progress encounter records.KPI and trend
open_lab_critical_alertsbuiltinOpen laboratory critical alerts.KPI, alert, and trend
birth_recordsaqlBirth-event composition count by configured birth template ID.KPI and trend
newborn_recordsaqlNewborn assessment or newborn registration composition count by configured newborn template ID.KPI and trend
death_notification_recordsaqlDeath notification composition count by configured death template ID.KPI and trend
weekly_reportable_positive_testssaved_queryReviewed 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.

RoutePurpose
GET /clinical-metrics/builtinList built-in aggregate collectors available for registration as definitions.
GET /clinical-metrics/definitionsList configured metric definitions and latest sample summary.
POST /clinical-metrics/definitionsCreate a governed definition.
PATCH /clinical-metrics/definitions/{metric_key}Update source, labels, sensitivity, interval, status, or metadata.
POST /clinical-metrics/definitions/{metric_key}/refreshRun a manual refresh for one definition.
GET /clinical-metrics/definitions/{metric_key}/samplesReview recent samples and failure/suppression state.
POST /clinical-metrics/process-dueProcess due active definitions immediately.
GET /clinical-metrics/prometheus-previewPreview the same registry metric lines that are included in /metrics.

Example Definition Patterns

MetricSourceKey fieldsLabels
Birth recordsAQLMetric 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 alertsBuilt-inMetric key open_lab_critical_alerts; built-in source open_lab_critical_alerts; unit count; refresh every 60 seconds.domain=laboratory
Weekly reportable positive testsSaved queryMetric 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.

CheckCommand or signalExpected result
Translator servicecurl -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 servicecurl -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 librariesAMCDR CQL library state and ELM artifact path.compiler_state=compiled_external and backend cqframework_translation_service for externally translated libraries.
Clinical Assistant statusPatient 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.

StatusMeaningRequired action
okSchema, database, Redis, OpenSearch, projections, and cache warmup are healthy for high-performance traffic.Continue standard operation.
degradedThe clinical API remains available, but a performance dependency or projection requires attention.Review Redis, OpenSearch, warmup ownership, projection aliases, and probe latency.
not_readyThe database or schema state is not safe for clinical traffic.Stop rollout, run migrations, check database connectivity, and verify schema revision.
unknownThe 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
ServiceLocal URLPurpose
Prometheushttp://127.0.0.1:9090Scrapes the authenticated backend /metrics endpoint and stores local time series.
Grafanahttp://127.0.0.1:3000Provides dashboards for readiness, dependency state, request rate, latency, and errors.
AMCDR backendhttp://127.0.0.1:8009Serves 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.

FolderDashboardPurpose
AMCDR / HIS - PlatformAMCDR Platform MonitoringRuntime health, readiness, HTTP traffic, latency, dependency state, EHR count, Redis/cache warmup, and OpenSearch projection health.
AMCDR / HIS - ClinicalAMCDR Clinical MetricsGoverned 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
SettingProduction guidance
AMCDR_PROMETHEUS_HOST_BINDKeep 127.0.0.1 unless a private monitoring network or protected Nginx location is configured.
AMCDR_GRAFANA_HOST_BINDKeep 127.0.0.1 unless Grafana is protected by SSO, VPN, or an internal-only proxy.
GRAFANA_ADMIN_PASSWORDSet a strong password before first start. Do not use the development default on VPS.
AMCDR_PROMETHEUS_RETENTIONDefault 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.

Credential requirement. Provision 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

PanelPromQL examplePurpose
Performance readinessamcdr_performance_readiness_state{state="ok"}Show whether the platform is fully ready.
HTTP request ratesum by (route, method) (rate(amcdr_http_requests_total[5m]))Track traffic by route family.
HTTP 5xx ratesum(rate(amcdr_http_requests_total{status_code=~"5.."}[5m]))Detect backend errors rapidly.
p95 latencyhistogram_quantile(0.95, sum by (le, route) (rate(amcdr_http_request_duration_seconds_bucket[5m])))Show slow routes and regressions.
Dependency readinessamcdr_dependency_ready{dependency!="cache_warmup"}Display core schema, database, Redis, and OpenSearch state.
EHRsmax(amcdr_ehr_records)Show authoritative openEHR EHR container count.
Templates / versionsmax(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 flightamcdr_http_requests_in_flightShow current backend request pressure.

Clinical Metrics Folder

PanelPromQL examplePurpose
Clinical KPI valuesamcdr_clinical_metric_valueShow the current value of each registered clinical aggregate as stat KPIs.
Clinical metric valuesamcdr_clinical_metric_valueShow governed aggregate clinical indicators by metric key.
Clinical metric statusamcdr_clinical_metric_status{sample_status!="completed"} == 1Detect suppressed, failed, stale, or missing samples.
Clinical metric sample ageamcdr_clinical_metric_updated_age_secondsDetect 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

AlertConditionOperator response
AMCDRNotReadyamcdr_performance_readiness_state{state="not_ready"} == 1 for more than one scrape window.Block rollout, inspect migrations, database connectivity, and schema revision.
AMCDRDegradedamcdr_performance_readiness_state{state="degraded"} == 1 for 2-5 minutes.Review dependencies and projection health before clinical users report slowness.
AMCDRHighErrorRate5xx request rate exceeds the accepted operational threshold.Inspect backend logs, recent deployment changes, and failing route families.
AMCDRHighLatencyp95 latency exceeds the route-specific SLO.Check database, Redis, OpenSearch, CQL, terminology, and external service latency.
AMCDRDependencyDownamcdr_dependency_ready{dependency!="cache_warmup"} == 0 for a critical dependency.Restore the dependency or fail over according to the deployment runbook.
AMCDRSearchProjectionEmptyExpected OpenSearch projection document count is zero after warmup or reindex.Run search status checks and rebuild the affected projection scope.
AMCDRClinicalMetricFailedamcdr_clinical_metric_status{sample_status="failed"} == 1 for a registered metric.Review the definition, saved query or AQL, source tables, and backend logs.
AMCDRClinicalMetricStaleamcdr_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

  1. Confirm GET /health returns status=ok and the schema revision matches the application.
  2. Run GET /performance/readiness with an authenticated operator token and confirm status=ok.
  3. Confirm Prometheus target amcdr-backend is up and the last scrape has no authentication error.
  4. Open Grafana and confirm the AMCDR platform dashboard shows readiness, request rate, dependency state, and OpenSearch projection state.
  5. If clinical metrics are configured, run POST /clinical-metrics/process-due or wait for the scheduler, then confirm amcdr_clinical_metric_status is visible in Prometheus.
  6. Verify Redis and OpenSearch exporter targets if infrastructure exporters are enabled.
  7. Trigger a low-risk authenticated request and confirm HTTP request counters and latency histograms update.
  8. Review backend logs for migration, cache warmup, OpenSearch, terminology, CQL, MediServe, and sidecar connectivity warnings.

Production Guidance