Nov 23, 20269 min read

Build a Medication Reminder Backend

How to schedule medication reminders across time zones and daylight saving changes, send each one exactly once, track taken and missed doses and escalate, built with Encore cron, Pub/Sub and Postgres.

Illustration for Build a Medication Reminder Backend

A reminder app looks like a list of times and a scheduler until a patient flies to another country, the clocks change, or a message goes out twice at 3 a.m. Each of those is a support ticket, and a late or duplicated reminder is worse than none in a health product.

This guide designs the scheduling model first, expanding regimens into dated doses, and then builds it with Encore.

The reminder backend at a glance

JobPatternWhat goes wrong without it
ScheduleLocal times plus an IANA zone, expanded into dated dosesReminders drift after daylight saving
ExpansionHourly job that inserts the next 48 hoursMissed reminders when a run fails
SendingTopic and an idempotent consumerDuplicate texts after retries
TrackingDose status: pending, reminded, taken, missedNo adherence data
EscalationSweep for doses still open after an hourNobody notices a missed dose
ContentGeneric wording, details behind loginMedication names on a lock screen

How do you model a regimen?

A regimen is a set of local clock times, such as 08:00 and 20:00, in the patient's time zone, with a start and end date. Store the IANA zone name and not a UTC offset, because the offset changes twice a year in many countries and the patient can change zone when they travel.

Expand each regimen into dose rows with absolute timestamps for the next day or two, and let the reminders work only from those rows. A dose row is easy to query, easy to mark as taken, and its history is the adherence record. The sending path never needs to understand time zones.

What happens at daylight saving changes?

A local time can be skipped or repeated, and Go's time.Date documents that it returns a time correct in one of the two zones involved without guaranteeing which. For a 02:30 dose on the night the clocks jump forward, the result is still a valid instant, so the dose lands near the intended time rather than being lost.

Store timestamps as timestamptz, which PostgreSQL stores as UTC, and compare doses to now() without converting. Containers without a time zone database make time.LoadLocation fail, so import time/tzdata in the service to embed one.

How do you send each reminder once?

Both the sweep and the queue can repeat work, so the consumer is the place to be strict. A table keyed by dose and kind records each notification, and the consumer inserts the key before sending. When the insert conflicts, the message was already handled and the consumer returns without sending. See idempotent message consumers for the general pattern.

How do you build it with Encore?

Encore

Encore works alongside your existing scheduling code, and the reminder service declares its Postgres database, a Pub/Sub topic for reminders and two cron jobs as ordinary package-level variables. Encore provisions the database and topic in your AWS or GCP account.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create meds --example=hello-world$ cd meds && mkdir -p meds/migrations

The schema

-- meds/migrations/1_create_meds.up.sql CREATE TABLE regimens ( id BIGSERIAL PRIMARY KEY, patient_id TEXT NOT NULL, label TEXT NOT NULL, -- internal code, not shown in notifications tz TEXT NOT NULL, -- IANA name, for example Europe/Vienna starts_on DATE NOT NULL, ends_on DATE ); CREATE TABLE regimen_times ( regimen_id BIGINT NOT NULL REFERENCES regimens(id), local_time TEXT NOT NULL, -- HH:MM PRIMARY KEY (regimen_id, local_time) ); CREATE TABLE doses ( id BIGSERIAL PRIMARY KEY, regimen_id BIGINT NOT NULL REFERENCES regimens(id), due_at TIMESTAMPTZ NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | reminded | taken | missed UNIQUE (regimen_id, due_at) ); CREATE INDEX doses_open ON doses (due_at) WHERE status IN ('pending', 'reminded'); CREATE TABLE sent_notifications ( dose_id BIGINT NOT NULL REFERENCES doses(id), kind TEXT NOT NULL, -- due | missed sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (dose_id, kind) );

The service

// meds/meds.go package meds import ( "context" "errors" "time" _ "time/tzdata" // embed the time zone database for slim container images "encore.dev/cron" "encore.dev/pubsub" "encore.dev/rlog" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("meds", sqldb.DatabaseConfig{ Migrations: "./migrations", }) type Reminder struct { DoseID int64 PatientID string Kind string // "due" or "missed" } var Reminders = pubsub.NewTopic[*Reminder]("medication-reminders", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) // Expand inserts doses for today and tomorrow in each patient's own zone. // It is safe to run repeatedly because (regimen_id, due_at) is unique. // //encore:api private method=POST path=/meds/expand func Expand(ctx context.Context) error { rows, err := db.Query(ctx, ` SELECT r.id, r.tz, t.local_time FROM regimens r JOIN regimen_times t ON t.regimen_id = r.id WHERE r.starts_on <= current_date + 1 AND (r.ends_on IS NULL OR r.ends_on >= current_date)`) if err != nil { return err } type slot struct { id int64 tz, clock string } var slots []slot for rows.Next() { var s slot if err := rows.Scan(&s.id, &s.tz, &s.clock); err != nil { rows.Close() return err } slots = append(slots, s) } rows.Close() for _, s := range slots { loc, err := time.LoadLocation(s.tz) if err != nil { rlog.Error("bad time zone", "regimen", s.id, "tz", s.tz) continue } clock, err := time.Parse("15:04", s.clock) if err != nil { continue } today := time.Now().In(loc) for d := 0; d < 2; d++ { day := today.AddDate(0, 0, d) due := time.Date(day.Year(), day.Month(), day.Day(), clock.Hour(), clock.Minute(), 0, 0, loc) // Only days inside the regimen's start and end dates get a dose. if _, err := db.Exec(ctx, ` INSERT INTO doses (regimen_id, due_at) SELECT id, $2 FROM regimens WHERE id = $1 AND starts_on <= $3::date AND (ends_on IS NULL OR ends_on >= $3::date) ON CONFLICT (regimen_id, due_at) DO NOTHING`, s.id, due, day.Format("2006-01-02")); err != nil { return err } } } return nil } // Sweep publishes reminders for due doses and flags doses still open after an hour. // //encore:api private method=POST path=/meds/sweep func Sweep(ctx context.Context) error { if err := publishFor(ctx, "due", `SELECT d.id, r.patient_id FROM doses d JOIN regimens r ON r.id = d.regimen_id WHERE d.status = 'pending' AND d.due_at <= now()`, `UPDATE doses SET status = 'reminded' WHERE id = $1 AND status = 'pending'`); err != nil { return err } return publishFor(ctx, "missed", `SELECT d.id, r.patient_id FROM doses d JOIN regimens r ON r.id = d.regimen_id WHERE d.status = 'reminded' AND d.due_at <= now() - interval '60 minutes'`, `UPDATE doses SET status = 'missed' WHERE id = $1 AND status = 'reminded'`) } func publishFor(ctx context.Context, kind, selectSQL, updateSQL string) error { rows, err := db.Query(ctx, selectSQL) if err != nil { return err } var batch []*Reminder for rows.Next() { r := &Reminder{Kind: kind} if err := rows.Scan(&r.DoseID, &r.PatientID); err != nil { rows.Close() return err } batch = append(batch, r) } rows.Close() for _, r := range batch { // Publish first: a crash before the update repeats the message, and the // consumer drops repeats, so nothing is lost and nothing is sent twice. if _, err := Reminders.Publish(ctx, r); err != nil { return err } if _, err := db.Exec(ctx, updateSQL, r.DoseID); err != nil { return err } } return nil } var _ = pubsub.NewSubscription(Reminders, "send-reminder", pubsub.SubscriptionConfig[*Reminder]{ Handler: func(ctx context.Context, r *Reminder) error { // The marker commits only after the send, so a failed send rolls back and the retry sends it. tx, err := db.Begin(ctx) if err != nil { return err } defer tx.Rollback() var id int64 err = tx.QueryRow(ctx, ` INSERT INTO sent_notifications (dose_id, kind) VALUES ($1, $2) ON CONFLICT DO NOTHING RETURNING dose_id`, r.DoseID, r.Kind).Scan(&id) if errors.Is(err, sqldb.ErrNoRows) { return nil // already sent } if err != nil { return err } // Call your SMS or push provider here with generic wording such as // "A dose is due. Open the app for details." Keep medication names out, // and return its error so the message is retried. rlog.Info("reminder sent", "dose", r.DoseID, "kind", r.Kind) return tx.Commit() }, }) // MarkTaken records a dose as taken. Put your own authenticated endpoint in front of it. // //encore:api private method=POST path=/doses/:id/taken func MarkTaken(ctx context.Context, id int64) error { _, err := db.Exec(ctx, ` UPDATE doses SET status = 'taken' WHERE id = $1 AND status IN ('pending', 'reminded', 'missed')`, id) return err } // Managed by the Encore platform in deployed environments. These do not run // under `encore run`, so call Expand and Sweep directly when testing locally. var _ = cron.NewJob("expand-doses", cron.JobConfig{ Title: "Expand regimens into doses", Every: 1 * cron.Hour, Endpoint: Expand, }) var _ = cron.NewJob("sweep-doses", cron.JobConfig{ Title: "Send due and missed dose reminders", Every: 5 * cron.Minute, Endpoint: Sweep, })

encore run starts a local Postgres, applies the migration and serves the endpoints. The cron jobs are managed by the Encore platform and do not run locally or in preview environments, so locally you call Expand and Sweep from a test or the development dashboard. On deploy, the database runs on RDS or Cloud SQL and the topic on SNS and SQS or GCP Pub/Sub, with an IAM role provisioned for the service as the AWS infrastructure docs describe.

A coding agent adding an escalation to a caregiver subscribes a second consumer to medication-reminders in the same change and runs it locally, without creating a queue or editing permissions.

Best fit: Teams building reminders into a health app who want the scheduling logic, its tests and its infrastructure in one repository.

How would you build it by hand?

On AWS the same service needs an RDS database, a container deployment, EventBridge Scheduler rules for the two jobs, an SNS topic with an SQS queue for the consumer and IAM for each piece, usually in Terraform. The Go stays close to the code above. The extra work is the infrastructure definitions and a way to run the scheduler locally.

Things to decide early

  • Taken versus late. Decide how late a patient can log a dose and still have it count as taken, and keep the cutoff configurable per regimen.
  • Skipped doses. Record an explicit skip separately from a miss, because the two mean different things to a clinician.
  • Data location. Reminders and adherence records can be sensitive health data, so keep them in your own cloud account and review the rules for your market with counsel.
  • Quiet hours. Hold non-urgent notifications overnight, and expand doses so a quiet window never drops a dose silently.

Frequently asked questions

How do you schedule medication reminders across time zones?

Store the regimen as local clock times plus an IANA time zone name such as Europe/Vienna, and expand it into dated doses with absolute timestamps a day or two ahead. Do the expansion with a time zone library rather than fixed UTC offsets, so a 08:00 dose stays at 08:00 local time after a daylight saving change.

How do you stop a reminder from being sent twice?

Give every dose a unique row and record each notification in a table keyed by dose and kind with a unique constraint. Queues deliver at least once, so the consumer inserts the key first and only sends when the insert succeeds.

What should a reminder message contain?

Keep the text generic, such as a reminder that a dose is due, and put the medication name behind the login in the app. Text messages and push notifications can be read on a locked screen, so the least identifying wording is the safer default.

How do you build a medication reminder backend with Encore?

With Encore, declare the Postgres database, a Pub/Sub topic for reminders and two cron jobs next to the handlers. Encore provisions the database and topic in your AWS or GCP account, and the cron jobs are managed by the Encore platform.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders