How to build the backend behind patient referrals between clinics: a status machine kept in the database, an append-only history, documents in private storage with short-lived links, events that carry IDs instead of patient details, and nudges for referrals that stall.

A referral sends a patient from one clinic to another with the reason, the urgency and the documents the receiving office needs. The record is simple and the handoff is not: the receiving office may not respond, a referral can be cancelled while it is being accepted, and several systems want every status change.
This guide builds a referral backend in Go with Postgres, covering the status rules, the history, document handling and a job that nudges referrals that have gone quiet.
Referral screens usually show a status dropdown, and a backend that accepts any value lets a delayed request move a referral backwards or sideways. Two staff members acting at once, one cancelling and one accepting, can both succeed with a read-then-write implementation, and the receiving office then schedules a patient whose referral no longer exists.
Putting the allowed transitions in a table makes the rule data. A single UPDATE joins that table against the current status and locks the row, so the second of two competing requests re-reads the new status after the first commits and finds no allowed transition. If a cancel and an accept run at once, the row lock means one request commits and the other matches no row.
Encore is a backend framework with built-in infrastructure, and the referral service declares its Postgres database, a Pub/Sub topic for status changes, a private bucket for documents and a cron job for stalled referrals. Other services in the app call it as a typed service API.

Run in your terminal to get started locally.
The patient is an opaque patient_ref that points into your patient system, so the referral tables hold no name or birth date. The history table refuses updates and deletes through a trigger:
-- referrals/migrations/1_create_referrals.up.sql
CREATE TABLE referrals (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
from_org TEXT NOT NULL,
to_org TEXT NOT NULL,
patient_ref TEXT NOT NULL, -- an opaque ID, not a name or birth date
specialty TEXT NOT NULL,
urgency TEXT NOT NULL DEFAULT 'routine' CHECK (urgency IN ('routine', 'urgent')),
status TEXT NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft', 'sent', 'accepted', 'declined', 'scheduled', 'completed', 'cancelled')),
status_at TIMESTAMPTZ NOT NULL DEFAULT now(),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Which status may follow which. The database holds the state machine.
CREATE TABLE referral_transitions (
from_status TEXT NOT NULL,
to_status TEXT NOT NULL,
PRIMARY KEY (from_status, to_status)
);
INSERT INTO referral_transitions VALUES
('draft', 'sent'), ('draft', 'cancelled'),
('sent', 'accepted'), ('sent', 'declined'), ('sent', 'cancelled'),
('accepted', 'scheduled'), ('accepted', 'cancelled'),
('scheduled', 'completed'), ('scheduled', 'cancelled');
-- Append-only history: who moved the referral, from where, to where.
CREATE TABLE referral_events (
id BIGSERIAL PRIMARY KEY,
referral_id UUID NOT NULL REFERENCES referrals(id),
from_status TEXT NOT NULL,
to_status TEXT NOT NULL,
actor TEXT NOT NULL,
note TEXT,
at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE FUNCTION referral_events_append_only() RETURNS trigger AS $$
BEGIN
RAISE EXCEPTION 'referral_events is append-only';
END $$ LANGUAGE plpgsql;
CREATE TRIGGER referral_events_no_change BEFORE UPDATE OR DELETE ON referral_events
FOR EACH ROW EXECUTE FUNCTION referral_events_append_only();
CREATE TABLE referral_documents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
referral_id UUID NOT NULL REFERENCES referrals(id),
object_key TEXT NOT NULL UNIQUE,
filename TEXT NOT NULL,
stored_at TIMESTAMPTZ -- set once the upload is confirmed
);
CREATE TABLE referral_nudges (
referral_id UUID NOT NULL REFERENCES referrals(id),
status TEXT NOT NULL,
PRIMARY KEY (referral_id, status) -- one nudge per referral and status
);
Move is the only way status changes. The conditional UPDATE and the history insert share one transaction, and the event is published after the commit:
// referrals/referrals.go
package referrals
import (
"context"
"encore.dev/beta/errs"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("referrals", sqldb.DatabaseConfig{Migrations: "./migrations"})
// StatusChanged carries IDs and statuses only. Subscribers that need
// clinical content call the service and pass the same access checks.
type StatusChanged struct {
ReferralID string `json:"referral_id"`
From string `json:"from"`
To string `json:"to"`
}
var StatusTopic = pubsub.NewTopic[*StatusChanged]("referral-status-changed", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type CreateParams struct {
FromOrg string `json:"from_org"`
ToOrg string `json:"to_org"`
PatientRef string `json:"patient_ref"`
Specialty string `json:"specialty"`
Urgency string `json:"urgency"`
}
type Referral struct {
ID string `json:"id"`
}
//encore:api private method=POST path=/referrals
func Create(ctx context.Context, p *CreateParams) (*Referral, error) {
var id string
err := db.QueryRow(ctx, `
INSERT INTO referrals (from_org, to_org, patient_ref, specialty, urgency)
VALUES ($1, $2, $3, $4, COALESCE(NULLIF($5, ''), 'routine'))
RETURNING id`, p.FromOrg, p.ToOrg, p.PatientRef, p.Specialty, p.Urgency).Scan(&id)
if err != nil {
return nil, err
}
return &Referral{ID: id}, nil
}
type MoveParams struct {
To string `json:"to"`
Actor string `json:"actor"`
Note string `json:"note"`
}
// Move changes the status if the table of allowed transitions says it may,
// and records the change in the same transaction. A stale request, such as
// accepting a referral that was cancelled a second ago, matches no row.
//
//encore:api private method=POST path=/referrals/:id/move
func Move(ctx context.Context, id string, p *MoveParams) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
var from string
err = tx.QueryRow(ctx, `
UPDATE referrals r
SET status = $2, status_at = now()
FROM referral_transitions t, (SELECT status FROM referrals WHERE id = $1 FOR UPDATE) old
WHERE r.id = $1 AND t.from_status = old.status AND t.to_status = $2
RETURNING old.status`, id, p.To).Scan(&from)
if err != nil {
return &errs.Error{Code: errs.FailedPrecondition, Message: "that status change is not allowed"}
}
_, err = tx.Exec(ctx, `
INSERT INTO referral_events (referral_id, from_status, to_status, actor, note)
VALUES ($1, $2, $3, $4, NULLIF($5, ''))`, id, from, p.To, p.Actor, p.Note)
if err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
_, _ = StatusTopic.Publish(ctx, &StatusChanged{ReferralID: id, From: from, To: p.To})
return nil
}
The event carries the referral ID and the two statuses and nothing else. Both endpoints are private, so only other services in the app can call them; the clinic-facing API in front of them is where authentication and per-organization access checks belong.
Referral letters, imaging reports and lab results go straight from the sender to the bucket through a signed upload URL. FinishUpload marks the document stored only after confirming that the object exists, and the receiving office downloads through a link that lasts five minutes:
// referrals/documents.go
package referrals
import (
"context"
"errors"
"fmt"
"time"
"encore.dev/beta/errs"
"encore.dev/storage/objects"
)
// Private by default. Files are reached only through short-lived signed URLs.
var Documents = objects.NewBucket("referral-documents", objects.BucketConfig{Versioned: true})
type UploadResponse struct {
DocumentID string `json:"document_id"`
URL string `json:"url"`
}
//encore:api private method=POST path=/referrals/:id/documents
func StartUpload(ctx context.Context, id string, p *struct{ Filename string }) (*UploadResponse, error) {
var docID string
key := fmt.Sprintf("referrals/%s/%d", id, time.Now().UnixNano())
err := db.QueryRow(ctx, `
INSERT INTO referral_documents (referral_id, object_key, filename)
VALUES ($1, $2, $3) RETURNING id`, id, key, p.Filename).Scan(&docID)
if err != nil {
return nil, err
}
u, err := Documents.SignedUploadURL(ctx, key, objects.WithTTL(10*time.Minute))
if err != nil {
return nil, err
}
return &UploadResponse{DocumentID: docID, URL: u.URL}, nil
}
// FinishUpload marks the document stored only if the object exists.
//
//encore:api private method=POST path=/referral-documents/:docID/finish
func FinishUpload(ctx context.Context, docID string) error {
var key string
if err := db.QueryRow(ctx, `SELECT object_key FROM referral_documents WHERE id = $1`, docID).Scan(&key); err != nil {
return &errs.Error{Code: errs.NotFound, Message: "no such document"}
}
if _, err := Documents.Attrs(ctx, key); errors.Is(err, objects.ErrObjectNotFound) {
return &errs.Error{Code: errs.FailedPrecondition, Message: "the file has not been uploaded"}
} else if err != nil {
return err
}
_, err := db.Exec(ctx, `UPDATE referral_documents SET stored_at = COALESCE(stored_at, now()) WHERE id = $1`, docID)
return err
}
type DownloadResponse struct {
URL string `json:"url"`
}
// Download hands out a link that expires in five minutes.
//
//encore:api private method=GET path=/referral-documents/:docID/link
func Download(ctx context.Context, docID string) (*DownloadResponse, error) {
var key string
if err := db.QueryRow(ctx, `
SELECT object_key FROM referral_documents WHERE id = $1 AND stored_at IS NOT NULL`, docID).Scan(&key); err != nil {
return nil, &errs.Error{Code: errs.NotFound, Message: "no such document"}
}
u, err := Documents.SignedDownloadURL(ctx, key, objects.WithTTL(5*time.Minute))
if err != nil {
return nil, err
}
return &DownloadResponse{URL: u.URL}, nil
}
Bucket versioning keeps an overwritten file recoverable, and the signed URLs are the only way in. For logging each read of a document, see the PHI audit log guide, which writes the log row in the same transaction as the read.
A referral sitting in sent for three days (one day if urgent) is queued for a nudge to the receiving office:
// referrals/nudges.go
package referrals
import (
"context"
"encore.dev/cron"
"encore.dev/pubsub"
)
type Nudge struct {
ReferralID string `json:"referral_id"`
ToOrg string `json:"to_org"`
Status string `json:"status"`
}
var NudgeTopic = pubsub.NewTopic[*Nudge]("referral-nudge", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
var _ = cron.NewJob("stale-referrals", cron.JobConfig{
Title: "Nudge receiving offices about stale referrals",
Schedule: "0 7 * * *",
Endpoint: NudgeStale,
})
// NudgeStale finds referrals that sat in "sent" for 1 day (urgent) or 3 days
// (routine) and queues one nudge for each. The primary key on referral_nudges
// makes the job safe to run twice.
//
//encore:api private
func NudgeStale(ctx context.Context) error {
rows, err := db.Query(ctx, `
SELECT id, to_org FROM referrals
WHERE status = 'sent'
AND status_at < now() - CASE urgency WHEN 'urgent' THEN interval '1 day' ELSE interval '3 days' END`)
if err != nil {
return err
}
var due []Nudge
for rows.Next() {
n := Nudge{Status: "sent"}
if err := rows.Scan(&n.ReferralID, &n.ToOrg); err != nil {
rows.Close()
return err
}
due = append(due, n)
}
rows.Close()
if err := rows.Err(); err != nil {
return err
}
for _, n := range due {
res, err := db.Exec(ctx, `
INSERT INTO referral_nudges (referral_id, status) VALUES ($1, $2)
ON CONFLICT DO NOTHING`, n.ReferralID, n.Status)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
continue // already nudged for this status
}
if _, err := NudgeTopic.Publish(ctx, &n); err != nil {
_, _ = db.Exec(ctx, `DELETE FROM referral_nudges WHERE referral_id = $1 AND status = $2`, n.ReferralID, n.Status)
return err
}
}
return nil
}
encore run starts Postgres locally and applies the migration. The cron job is Encore platform Managed, so it does not run under encore run or in preview environments, and because NudgeStale is a plain function, a Go test can call it directly. The unique key on referral_nudges means a second run queues nothing for the same status, and a failed publish removes the claim so the next run retries.
On deploy, Encore creates the database, topic and bucket in your own AWS or GCP account and provisions an IAM role for the service, or a service account on GCP. The health data stays in infrastructure you control, and the agreements and controls your compliance program requires remain with your team.
When the clinic adds a status such as "awaiting authorization", a coding agent adds a migration row and the transitions in one diff and tests the change against the local database, with no separate infrastructure change.
The schema, the transitions join and the append-only trigger are ordinary Postgres, so the same design works anywhere. You then provision the database and bucket, run migrations in CI, set up a queue and a scheduler, and manage credentials for every environment yourself. Keep status changes in one service either way, so no other code path writes the status column directly.
Use Encore if you want the referral service, its database, bucket, event topic and stalled-referral job declared together and running locally and in your own cloud account from the first commit. Build on plain Postgres and your existing queue and scheduler if those are in place and the team already runs migrations and infrastructure per environment. A hosted referral platform fits when you need a ready-made clinician interface and payer integrations more than a backend you control.
Keep the statuses and the allowed transitions in the database, for example a transitions table with a from and a to status, and change status with one conditional UPDATE that joins it. A request that arrives after the referral has already moved, such as accepting a cancelled referral, then matches no row and fails instead of overwriting the newer state. Record each change in an append-only history table in the same transaction.
No. Publish the referral ID, the old status and the new status, and let subscribers fetch anything else from the referral service, where the same access checks and logging apply. Events are copied to queues, logs and dead-letter storage, so the less they carry the fewer places hold patient data.
Store each file in a private bucket under a key tied to the referral and hand out signed download links that expire after a few minutes. The sender uploads straight to the bucket through a signed upload URL, and the document only counts as stored after the backend confirms that the object exists.
Declare the Postgres database, a status topic, a private bucket and a daily cron job in Go next to the endpoints. A transition endpoint updates the status and writes the history row in one transaction, then publishes the change, and the cron job claims a row per stalled referral before it publishes a nudge. Encore provisions an IAM role for the service, or a service account on GCP.
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.