Nov 23, 202610 min read

Build a Secure Patient Messaging Backend

Design the backend for patient to care team messaging: threads tied to a care team, access checks on every read, an audit trail of who opened what, private attachments behind short-lived links, and notifications that never carry the message, with a Go example.

Illustration for Build a Secure Patient Messaging Backend

Secure messaging between patients and their care team looks like a chat feature with a database table. The differences are in who can read a thread, what gets recorded when they do, and what leaves the system in a notification.

This guide covers the data model, authorization, audit logging, attachments and notifications for a patient messaging backend, with Go code using Encore.

The Messaging Backend at a Glance

PieceWhat it doesBuilt with
ThreadsOne conversation between a patient and a care teamPostgres
MessagesText and an optional attachment keyPostgres
Access logWho read, sent or downloaded what, and whenPostgres
AttachmentsFiles behind short-lived signed URLsObject storage
NotifierEmails "you have a new message" without contentPub/Sub

What Do the Regulations Ask of a Messaging Backend?

In the US, the HIPAA Security Rule technical safeguards list access control, audit controls, integrity, authentication and transmission security. For a messaging backend that becomes concrete: only the patient and their care team can open a thread, every access is recorded, and traffic is encrypted in transit.

For notifications, HHS guidance on email allows providers to email patients with reasonable safeguards, such as limiting the information an unencrypted email discloses. A notification that only says a message is waiting fits that, while a copy of the message in the email does not. Confirm the details for your product with your compliance team, since requirements depend on your role and jurisdiction.

The Data Model

-- messaging/migrations/1_create_messaging.up.sql CREATE TABLE care_team_members ( care_team_id text NOT NULL, user_id text NOT NULL, PRIMARY KEY (care_team_id, user_id) ); CREATE TABLE user_contacts ( user_id text PRIMARY KEY, email text NOT NULL ); CREATE TABLE threads ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, patient_id text NOT NULL, care_team_id text NOT NULL, subject text NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE messages ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, thread_id bigint NOT NULL REFERENCES threads (id), sender_id text NOT NULL, sender_role text NOT NULL CHECK (sender_role IN ('patient', 'staff')), body text NOT NULL, attachment_key text, created_at timestamptz NOT NULL DEFAULT now() ); CREATE INDEX messages_thread ON messages (thread_id, id); CREATE TABLE access_log ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, user_id text NOT NULL, thread_id bigint NOT NULL, action text NOT NULL CHECK (action IN ('read', 'send', 'download')), at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE notifications ( message_id bigint NOT NULL, user_id text NOT NULL, PRIMARY KEY (message_id, user_id) );

Threads belong to a care team rather than a single clinician, so a message to the clinic still reaches someone when one person is away, and adding a nurse to the team gives access without touching old threads. The access log is append-only from the application's side, and its index needs (by user, by thread, by time) depend on how your audits are run.

Building It with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the database, the private attachments bucket, the notification topic and the email provider key below are declared in Go, encore run starts them locally, and deploying creates them in your own AWS or GCP account.

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

Run in your terminal to get started locally.

Authorization and the Access Log

Every endpoint starts from the same check: is the caller the thread's patient or a member of its care team. A thread the caller cannot access returns "not found", so the API does not confirm that a thread exists.

// messaging/access.go package messaging import ( "context" "errors" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("messaging", sqldb.DatabaseConfig{ Migrations: "./migrations", }) var errNotFound = &errs.Error{Code: errs.NotFound, Message: "thread not found"} // access returns the caller's ID and role in the thread ("patient" or // "staff"), and records the action in the access log. func access(ctx context.Context, threadID int64, action string) (string, string, error) { uid, ok := auth.UserID() if !ok { return "", "", &errs.Error{Code: errs.Unauthenticated, Message: "sign in required"} } var role string err := db.QueryRow(ctx, ` SELECT CASE WHEN t.patient_id = $2 THEN 'patient' WHEN EXISTS ( SELECT 1 FROM care_team_members m WHERE m.care_team_id = t.care_team_id AND m.user_id = $2 ) THEN 'staff' ELSE '' END FROM threads t WHERE t.id = $1`, threadID, string(uid)).Scan(&role) if errors.Is(err, sqldb.ErrNoRows) || role == "" { return "", "", errNotFound } if err != nil { return "", "", err } if _, err := db.Exec(ctx, `INSERT INTO access_log (user_id, thread_id, action) VALUES ($1, $2, $3)`, string(uid), threadID, action); err != nil { return "", "", err } return string(uid), role, nil }

Writing the log row before returning data means a failed audit write fails the request, which is the safer direction when the log is what an auditor will ask for.

Sending and Reading Messages

// messaging/messages.go package messaging import ( "context" "fmt" "strings" "time" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/storage/objects" ) var attachments = objects.NewBucket("message-attachments", objects.BucketConfig{}) type MessageSent struct { ThreadID int64 MessageID int64 SenderRole string } var MessagesSent = pubsub.NewTopic[*MessageSent]("message-sent", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type SendParams struct { Body string AttachmentKey string `json:"attachmentKey,omitempty"` } type Message struct { ID int64 SenderID string SenderRole string Body string AttachmentKey string CreatedAt time.Time } //encore:api auth method=POST path=/threads/:threadID/messages func Send(ctx context.Context, threadID int64, p *SendParams) (*Message, error) { uid, role, err := access(ctx, threadID, "send") if err != nil { return nil, err } body := strings.TrimSpace(p.Body) if body == "" || len(body) > 10000 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "message must be 1 to 10000 characters"} } // Accept only keys under this thread and sender, the prefix the upload URL is issued for. if p.AttachmentKey != "" && !strings.HasPrefix(p.AttachmentKey, fmt.Sprintf("threads/%d/%s/", threadID, uid)) { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "attachment does not belong to this thread"} } m := &Message{SenderID: uid, SenderRole: role, Body: body, AttachmentKey: p.AttachmentKey} err = db.QueryRow(ctx, ` INSERT INTO messages (thread_id, sender_id, sender_role, body, attachment_key) VALUES ($1, $2, $3, $4, NULLIF($5, '')) RETURNING id, created_at`, threadID, uid, role, body, p.AttachmentKey).Scan(&m.ID, &m.CreatedAt) if err != nil { return nil, err } _, err = MessagesSent.Publish(ctx, &MessageSent{ThreadID: threadID, MessageID: m.ID, SenderRole: role}) return m, err } type ListResponse struct { Messages []*Message } //encore:api auth method=GET path=/threads/:threadID/messages func List(ctx context.Context, threadID int64) (*ListResponse, error) { if _, _, err := access(ctx, threadID, "read"); err != nil { return nil, err } rows, err := db.Query(ctx, ` SELECT id, sender_id, sender_role, body, COALESCE(attachment_key, ''), created_at FROM messages WHERE thread_id = $1 ORDER BY id`, threadID) if err != nil { return nil, err } defer rows.Close() resp := &ListResponse{} for rows.Next() { m := &Message{} if err := rows.Scan(&m.ID, &m.SenderID, &m.SenderRole, &m.Body, &m.AttachmentKey, &m.CreatedAt); err != nil { return nil, err } resp.Messages = append(resp.Messages, m) } return resp, rows.Err() } type DownloadResponse struct { URL string } //encore:api auth method=GET path=/threads/:threadID/messages/:messageID/attachment func Attachment(ctx context.Context, threadID, messageID int64) (*DownloadResponse, error) { if _, _, err := access(ctx, threadID, "download"); err != nil { return nil, err } var key string err := db.QueryRow(ctx, ` SELECT COALESCE(attachment_key, '') FROM messages WHERE id = $1 AND thread_id = $2`, messageID, threadID).Scan(&key) if err != nil || key == "" { return nil, &errs.Error{Code: errs.NotFound, Message: "no attachment"} } signed, err := attachments.SignedDownloadURL(ctx, key, objects.WithTTL(5*time.Minute)) if err != nil { return nil, err } return &DownloadResponse{URL: signed.URL}, nil }

The bucket is private by default, so the only way to an attachment is through Attachment, which checks the thread and writes a download row first. The object storage docs cover signed URLs, including signed upload URLs for letting the client upload a file before it sends the message. Issue those for keys under threads/<threadID>/<userID>/, which is the prefix Send checks, so nobody can attach an object from another thread.

Notifications Without Content

// messaging/notify.go package messaging import ( "bytes" "context" "encoding/json" "fmt" "net/http" "encore.dev/pubsub" ) var secrets struct { EmailAPIKey string } var _ = pubsub.NewSubscription(MessagesSent, "notify-recipients", pubsub.SubscriptionConfig[*MessageSent]{ Handler: notify, }) func notify(ctx context.Context, m *MessageSent) error { // Staff messages notify the patient, patient messages notify the care team. query := ` SELECT c.user_id, c.email FROM threads t JOIN user_contacts c ON c.user_id = t.patient_id WHERE t.id = $1` if m.SenderRole == "patient" { query = ` SELECT c.user_id, c.email FROM threads t JOIN care_team_members tm ON tm.care_team_id = t.care_team_id JOIN user_contacts c ON c.user_id = tm.user_id WHERE t.id = $1` } rows, err := db.Query(ctx, query, m.ThreadID) if err != nil { return err } type recipient struct{ userID, email string } var recipients []recipient for rows.Next() { var r recipient if err := rows.Scan(&r.userID, &r.email); err != nil { rows.Close() return err } recipients = append(recipients, r) } rows.Close() if err := rows.Err(); err != nil { return err } for _, r := range recipients { // Skip recipients already notified by an earlier delivery. res, err := db.Exec(ctx, ` INSERT INTO notifications (message_id, user_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, m.MessageID, r.userID) if err != nil { return err } if res.RowsAffected() == 0 { continue } if err := sendEmail(ctx, r.email, m.ThreadID); err != nil { _, _ = db.Exec(ctx, `DELETE FROM notifications WHERE message_id = $1 AND user_id = $2`, m.MessageID, r.userID) return err } } return nil } // sendEmail sends a notification with no message text and no subject line, // only a link that requires signing in. func sendEmail(ctx context.Context, to string, threadID int64) error { body, err := json.Marshal(map[string]string{ "to": to, "subject": "You have a new secure message", "text": fmt.Sprintf("Sign in to read it: https://portal.example.com/messages/%d", threadID), }) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://email.example.com/v1/send", bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+secrets.EmailAPIKey) req.Header.Set("Content-Type", "application/json") resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode >= 300 { return fmt.Errorf("email provider returned %d", resp.StatusCode) } return nil }

The thread subject stays out of the email too, since "Question about my test results" is health information on its own. Publishing keeps sending out of the request path, the Pub/Sub docs describe the retries a failed email gets, and the notifications table stops a redelivered event from emailing the same person twice.

Running It

encore run starts Postgres, the bucket and the topic locally, so you can send a message as a patient, read it as a care team member and check access_log in the local database. Use rlog for operational logs with IDs only, never message bodies, in line with the OWASP logging guidance on keeping sensitive data out of logs.

On AWS, deploying creates RDS, an S3 bucket, SNS and SQS in your own account, and Encore provisions an IAM role for the service, or a service account on GCP, as the AWS infrastructure docs describe. The data stays in that account, under the agreements and controls you already have with your cloud provider. When the clinic asks for a "read by care team" indicator, a coding agent can add a table and a query to List and test it against the local database in the same change, with no new infrastructure to set up.

Best fit: healthtech teams building patient to care team messaging who want access checks, an audit trail and private attachments in their own AWS or GCP account.

Things to Decide Early

  • Retention. Messages are part of the record in many products, so agree on retention and deletion rules before the first message is stored.
  • Proxy access. Parents, caregivers and guardians may read a patient's threads, which needs its own role and audit entries.
  • Urgent messages. Messaging is not for emergencies, so show that before sending and decide how urgent keywords are handled.
  • Response times. Track time to first staff reply per care team, since patients judge the feature by it.
  • Encryption. Decide whether storage-level encryption is enough or bodies need application-level encryption with keys in a key management service.

Frequently asked questions

What makes patient messaging different from a normal chat feature?

Every message is health information, so access is limited to the patient and their care team, every read is logged for audits, attachments are never public, and notifications sent over email or SMS must not contain the message itself.

Can a patient portal send message notifications by email?

Yes. HHS guidance allows email with reasonable safeguards, such as limiting what the email discloses. The common pattern is a notification that says a new message is waiting, with a link to the portal, and no message text or subject.

How should a messaging backend log access for HIPAA audits?

Write an access log row for each read, send and attachment download, with the user, thread, action and time, in the same database as the messages. The HIPAA Security Rule lists audit controls as a technical safeguard, and application logs should not contain message bodies.

How do I store message attachments securely?

Keep them in a private object storage bucket, authorize the user against the thread on each request, log the access, and return a signed download URL that expires after a few minutes instead of a permanent link.

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