Ingest device readings once, open an alert when a reading crosses the clinician's thresholds, escalate unacknowledged alerts, and count monitoring days in the patient's time zone.

A remote patient monitoring program looks simple from the clinic: a connected cuff sends blood pressure readings, and someone is supposed to notice when a number is dangerous. The backend has to ingest each reading once even when the vendor retries, compare it to the clinician's thresholds, and open an alert when a reading crosses them.
When an alert sits unacknowledged, it has to escalate. Billing staff also need a count of distinct days with readings, in the patient's own time zone, for the period their program uses.
This guide builds that path in Go for blood pressure: idempotent ingest, threshold alerts, a 30-minute escalation job, and a monitoring-day count. It is not a device vendor, an EHR, or a billing system, and it is not a compliance program.
Ingest is idempotent. Device vendors redeliver. The primary key is the vendor's reading ID, and a second insert with that ID changes nothing, so a retry cannot open a second alert for the same reading.
The threshold check happens in the same transaction as the insert. If the insert commits and the alert write fails, a dangerous reading can sit unnoticed. Doing both in one transaction, and only after the insert landed, means a retried delivery does not create a second alert and a failed alert write rolls back the reading so the vendor can retry.
Events and logs carry the alert ID, not the patient or the reading. A consumer that needs the systolic value or the patient identifier reads it from the database through an endpoint that checks access. Queue messages, dead-letter queues and log pipelines are then not additional stores of protected health information, which simplifies the access review the HIPAA Security Rule expects.
Unacknowledged alerts escalate on a clock, not on hope. A clinician acknowledges an alert. A job periodically marks alerts still open after a grace period, for example 30 minutes, and republishes them as escalations for the on-call path. The job must be safe to run twice: a second pass finds no remaining rows.
Monitoring days are counted in the patient's time zone. US reimbursement programs often need a count of distinct days with readings in a period, usually 30 days, and the number of days required depends on the billed code. Medicare describes those rules on its remote patient monitoring page and in the HHS telehealth billing guide. The backend returns the count. Billing and compliance staff map it to the codes that apply, and those rules change. The figures in this article are illustrative.
Every read of patient data is logged. That is its own topic, covered in the PHI audit log guide. The endpoints below are the places to call it.
Compliance stays with your team and the cloud provider. AWS and Google Cloud both sign Business Associate Agreements and publish which of their services are covered, on the AWS HIPAA eligible services list and the Google Cloud HIPAA page. Those BAAs cover the provider's own services, not Encore. Encore holds no HIPAA certification or attestation. Check every service in the reading and alerting path against those lists, and get a BAA from every vendor that handles PHI, including the device vendor and any paging or SMS provider. Infrastructure choices support compliance work. They do not replace it.
Encore is a backend framework with built-in infrastructure. The readings database, the topic for alerts and the escalation cron job are declared in Go next to the handlers. encore run starts Postgres and an in-memory Pub/Sub locally. A deploy to your own account creates RDS, SNS with SQS on AWS, or Cloud SQL and Pub/Sub on GCP, and Encore provisions an IAM role for the service, or a service account on GCP. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so you call the escalation endpoint directly when testing.

Run in your terminal to get started locally.
Patients carry their time zone and the thresholds a clinician set. Readings are keyed by the vendor's ID. Each alert points at exactly one reading.
-- rpm/migrations/1_create_rpm.up.sql
CREATE TABLE patients (
id TEXT PRIMARY KEY,
timezone TEXT NOT NULL,
systolic_alert INTEGER NOT NULL DEFAULT 180,
diastolic_alert INTEGER NOT NULL DEFAULT 110
);
CREATE TABLE bp_readings (
reading_id TEXT PRIMARY KEY,
patient_id TEXT NOT NULL REFERENCES patients (id),
systolic INTEGER NOT NULL CHECK (systolic BETWEEN 60 AND 250),
diastolic INTEGER NOT NULL CHECK (diastolic BETWEEN 30 AND 150),
taken_at TIMESTAMPTZ NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX bp_readings_patient_idx ON bp_readings (patient_id, taken_at);
CREATE TABLE alerts (
id BIGSERIAL PRIMARY KEY,
patient_id TEXT NOT NULL REFERENCES patients (id),
reading_id TEXT NOT NULL UNIQUE REFERENCES bp_readings (reading_id),
opened_at TIMESTAMPTZ NOT NULL DEFAULT now(),
acknowledged_at TIMESTAMPTZ,
acknowledged_by TEXT,
escalated_at TIMESTAMPTZ,
escalation_claimed_at TIMESTAMPTZ,
escalation_claim TEXT
);
CREATE INDEX alerts_open_idx ON alerts (opened_at)
WHERE acknowledged_at IS NULL AND escalated_at IS NULL;
The device integration calls Ingest after it has verified the vendor's request. A webhook that does that verification belongs on a raw endpoint. The event published after commit carries only the alert ID.
// rpm/ingest.go
package rpm
import (
"context"
"errors"
"time"
"encore.dev/beta/errs"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("rpm", sqldb.DatabaseConfig{Migrations: "./migrations"})
type AlertRaised struct {
AlertID int64 `json:"alert_id"`
Escalated bool `json:"escalated"`
}
var Alerts = pubsub.NewTopic[*AlertRaised]("bp-alerts", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type Reading struct {
ReadingID string `json:"reading_id"`
PatientID string `json:"patient_id"`
Systolic int `json:"systolic"`
Diastolic int `json:"diastolic"`
TakenAt time.Time `json:"taken_at"`
}
type IngestResult struct {
Duplicate bool `json:"duplicate"`
AlertID *int64 `json:"alert_id,omitempty"`
}
//encore:api private method=POST path=/readings
func Ingest(ctx context.Context, r *Reading) (*IngestResult, error) {
tx, err := db.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
var duplicate bool
err = tx.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM bp_readings WHERE reading_id = $1)`,
r.ReadingID).Scan(&duplicate)
if err != nil {
return nil, err
}
if duplicate {
return &IngestResult{Duplicate: true}, nil
}
now := time.Now()
if r.Systolic < 60 || r.Systolic > 250 || r.Diastolic < 30 || r.Diastolic > 150 ||
r.TakenAt.After(now.Add(5*time.Minute)) || r.TakenAt.Before(now.Add(-24*time.Hour)) {
return nil, &errs.Error{Code: errs.InvalidArgument, Message: "implausible reading"}
}
res, err := tx.Exec(ctx, `
INSERT INTO bp_readings (reading_id, patient_id, systolic, diastolic, taken_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (reading_id) DO NOTHING`,
r.ReadingID, r.PatientID, r.Systolic, r.Diastolic, r.TakenAt)
if err != nil {
return nil, err
}
if res.RowsAffected() == 0 {
return &IngestResult{Duplicate: true}, nil
}
var alertID int64
err = tx.QueryRow(ctx, `
INSERT INTO alerts (patient_id, reading_id)
SELECT p.id, $2 FROM patients p
WHERE p.id = $1 AND ($3 >= p.systolic_alert OR $4 >= p.diastolic_alert)
RETURNING id`,
r.PatientID, r.ReadingID, r.Systolic, r.Diastolic).Scan(&alertID)
if err != nil && !errors.Is(err, sqldb.ErrNoRows) {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, err
}
if alertID == 0 {
return &IngestResult{}, nil
}
if _, err := Alerts.Publish(ctx, &AlertRaised{AlertID: alertID}); err != nil {
return nil, err
}
return &IngestResult{AlertID: &alertID}, nil
}
If Publish fails after the commit, the at-least-once subscription will not see that alert unless a later reconciliation finds open alerts with no delivery. A periodic sweep of unnotified open alerts covers that case; the escalation job below is a close cousin of that sweep.
The care team is paged for every new alert, and alerts still unacknowledged after 30 minutes are marked escalated and published again for the on-call path. The subscriber logs the alert ID only.
// rpm/escalate.go
package rpm
import (
"context"
"crypto/rand"
"encoding/hex"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/rlog"
)
var _ = pubsub.NewSubscription(Alerts, "notify-care-team",
pubsub.SubscriptionConfig[*AlertRaised]{Handler: notify})
func notify(ctx context.Context, a *AlertRaised) error {
// Send through your paging provider; return an error to retry.
rlog.Info("bp alert", "alert_id", a.AlertID, "escalated", a.Escalated)
return nil
}
var _ = cron.NewJob("escalate-alerts", cron.JobConfig{
Title: "Escalate alerts unacknowledged for 30 minutes",
Every: 5 * cron.Minute,
Endpoint: EscalateStale,
})
//encore:api private
func EscalateStale(ctx context.Context) error {
var tok [16]byte
if _, err := rand.Read(tok[:]); err != nil {
return err
}
claim := hex.EncodeToString(tok[:])
rows, err := db.Query(ctx, `
WITH claimed AS (
SELECT id FROM alerts
WHERE acknowledged_at IS NULL AND escalated_at IS NULL
AND opened_at < now() - interval '30 minutes'
AND (escalation_claimed_at IS NULL
OR escalation_claimed_at < now() - interval '5 minutes')
FOR UPDATE SKIP LOCKED
)
UPDATE alerts
SET escalation_claimed_at = now(), escalation_claim = $1
FROM claimed
WHERE alerts.id = claimed.id
RETURNING alerts.id`, claim)
if err != nil {
return err
}
var stale []*AlertRaised
for rows.Next() {
a := &AlertRaised{Escalated: true}
if err := rows.Scan(&a.AlertID); err != nil {
rows.Close()
return err
}
stale = append(stale, a)
}
rows.Close()
for _, a := range stale {
if _, err := Alerts.Publish(ctx, a); err != nil {
return err
}
if _, err := db.Exec(ctx, `
UPDATE alerts SET escalated_at = now()
WHERE id = $1 AND escalated_at IS NULL AND escalation_claim = $2`,
a.AlertID, claim); err != nil {
return err
}
}
return nil
}
type AckParams struct {
ClinicianID string `json:"clinician_id"`
}
//encore:api private method=POST path=/alerts/:id/ack
func Acknowledge(ctx context.Context, id int64, p *AckParams) error {
_, err := db.Exec(ctx, `
UPDATE alerts SET acknowledged_at = now(), acknowledged_by = $2
WHERE id = $1 AND acknowledged_at IS NULL`, id, p.ClinicianID)
return err
}
Billing staff ask for the number of distinct calendar days with at least one reading in a 30-day window, computed in the patient's time zone. They map that count to the codes that apply.
// rpm/days.go
package rpm
import (
"context"
"time"
)
type DaysParams struct {
Start time.Time `query:"start"`
}
type MonitoringDays struct {
PeriodStart time.Time `json:"period_start"`
Days int `json:"days"`
}
//encore:api private method=GET path=/patients/:patientID/monitoring-days
func GetMonitoringDays(ctx context.Context, patientID string, p *DaysParams) (*MonitoringDays, error) {
out := &MonitoringDays{PeriodStart: p.Start}
err := db.QueryRow(ctx, `
SELECT count(DISTINCT (r.taken_at AT TIME ZONE pt.timezone)::date)
FROM bp_readings r JOIN patients pt ON pt.id = r.patient_id
WHERE r.patient_id = $1
AND r.taken_at >= $2 AND r.taken_at < $2 + interval '30 days'`,
patientID, p.Start).Scan(&out.Days)
return out, err
}
A coding agent that adds a second vital, such as pulse oximetry, can copy the reading table, the threshold columns and the ingest transaction in the same change, then call Ingest and EscalateStale from the local dashboard to check the path before it reaches production.
Best fit: Teams that want the readings database, the alert topic and the escalation job declared in one Go service and deployed to their own AWS or GCP account, with compliance remaining their program.
If several services already write readings into the same database, a trigger can open the alert on any insert, regardless of which code path wrote the row. A worker then waits on a notification, or polls open alerts, and pages the care team.
CREATE FUNCTION open_bp_alert() RETURNS trigger AS $$
BEGIN
INSERT INTO alerts (patient_id, reading_id)
SELECT p.id, NEW.reading_id FROM patients p
WHERE p.id = NEW.patient_id
AND (NEW.systolic >= p.systolic_alert OR NEW.diastolic >= p.diastolic_alert);
IF FOUND THEN
PERFORM pg_notify('bp_alerts', NEW.reading_id);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER bp_readings_alert
AFTER INSERT ON bp_readings
FOR EACH ROW EXECUTE FUNCTION open_bp_alert();
The notification payload is the reading ID, not the patient ID. A missed notification is picked up by the worker's next poll of open alerts, which is the same idea as the escalation sweep. The unique constraint on alerts.reading_id still makes a retried insert a no-op for alerting, provided the original insert used ON CONFLICT DO NOTHING or the trigger runs only on a successful insert of a new row.
Best fit: A database already written by more than one service, where you want the alert rule in one place rather than in each writer.
Put the threshold check in the same transaction as the insert when one service owns ingest, so a failed alert write can retry with the reading. Use a trigger when several writers already share the table and you want the rule in the database. Keep protected health information out of events and logs in either design, and let billing staff map the monitoring-day count to the codes that apply. Pick Encore when you want the database, the topic and the escalation job declared in Go and provisioned in your own AWS or GCP account.
It has to ingest each device reading once even when the vendor retries, compare it to thresholds the clinician set, open an alert when a reading crosses them, escalate if nobody acknowledges the alert, and count distinct days with readings in the patient's time zone so billing staff can map that count to the codes that apply. The device vendor, the EHR and the billing system stay outside this service.
Give every reading the vendor's stable ID and insert it with ON CONFLICT DO NOTHING on that ID. A retried delivery becomes a no-op, and the threshold check runs only for the insert that landed, in the same database transaction.
No. Put the alert ID in events and log lines, and let consumers read the patient and the reading from the database under their own access checks. That keeps identifiers and physiologic values out of queue storage, dead-letter queues and log pipelines, which the HIPAA Security Rule's access review has to cover if they hold that data.
Count distinct calendar days, in the patient's own time zone, that have at least one reading in the period the program uses, often 30 days. Medicare describes day-count rules that vary by billed code in its remote patient monitoring page and in the HHS telehealth billing guide. The backend returns the count. Billing and compliance staff map it to the codes that apply.
With Encore, the readings database, the alerts topic and the escalation cron job are declared in Go next to the handlers. encore run starts Postgres and an in-memory Pub/Sub locally. A deploy creates RDS, SNS with SQS and the schedule in your own AWS account, or Cloud SQL and Pub/Sub on GCP. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so you call the escalation endpoint directly when testing.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.