How to build the backend that records patient consent and authorizations, versions consent documents, handles expiry and revocation, and enforces consent at the moment data is used or shared, with an audit trail for every decision.

A patient consent is easy to collect and hard to honor, because a checkbox on an intake form becomes a promise that every export job, partner integration and research pipeline must respect.
That includes after the patient changes their mind, and most consent bugs live in a batch job that never asked rather than in the form.
This guide covers the data model, revocation and enforcement for a consent backend.
Healthcare products usually handle several kinds of consent at once, each with different rules:
For HIPAA authorizations, 45 CFR 164.508 lists the core elements: what information, who discloses, who receives, the purpose, an expiration date or event, and a signature, together with statements on the right to revoke. Those fields map almost directly onto columns. Records covered by 42 CFR Part 2 carry additional requirements, so mark them with their own category and confirm the rules with counsel.
Model consent as an append-only series of events per patient and scope, not as a mutable row:
CREATE TABLE consent_documents (
id text PRIMARY KEY, -- e.g. 'insurer-share-v3'
version integer NOT NULL,
body_sha256 text NOT NULL, -- hash of the exact text the patient saw
published_at timestamptz NOT NULL
);
CREATE TABLE consent_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
patient_id uuid NOT NULL,
purpose text NOT NULL, -- 'share_insurer', 'research_study_42', 'sms_reminders'
recipient text NOT NULL DEFAULT '', -- who may receive the data, '' when not applicable
action text NOT NULL CHECK (action IN ('granted', 'revoked')),
document_id text REFERENCES consent_documents (id),
expires_at timestamptz,
recorded_at timestamptz NOT NULL DEFAULT now(),
source text NOT NULL -- 'portal', 'paper_scan', 'staff'
);
CREATE INDEX consent_events_lookup ON consent_events (patient_id, purpose, recipient, recorded_at DESC);
The current state is the latest event per patient, purpose and recipient, and a grant counts only if it has not expired. Keeping the document version and a hash of its text proves exactly what the patient agreed to, which matters when the wording changes later. The FHIR Consent resource uses similar concepts, such as scope, policy, provision periods and actors, so this model can be exposed as FHIR when an integration needs it.
Consent is only as good as the checks that read it. Put one check function in one service and call it at every point of use or disclosure: before an export file is written, before a partner API call, before a record is added to a research extract. Pass the purpose and recipient, never a generic "has consented" flag, and log every decision with the inputs, so an auditor can see that a given disclosure was checked and allowed.
A revocation is a new event rather than a delete, and it takes effect for future uses, so work already queued must re-check or be cancelled. Publishing a revocation event lets every service that holds pending work for that patient react, and a final consent check at the moment of sending catches anything the event missed.
Best fit: append-only consent events with document versions, one check called at every disclosure, and revocations broadcast as events.
Encore is a backend framework with built-in infrastructure, so the consent database, the revocation Pub/Sub topic and the check endpoint that other services call are declared in one Go service and provisioned in your own AWS or GCP account, where PHI stays under your account's controls. Fields marked encore:"sensitive" are redacted from traces, as described in the API definition docs:
Run in your terminal to get started locally.
package consent
import (
"context"
"errors"
"time"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("consent", sqldb.DatabaseConfig{Migrations: "./migrations"})
type Revoked struct {
PatientID string `json:"patient_id"`
Purpose string `json:"purpose"`
Recipient string `json:"recipient"`
}
var Revocations = pubsub.NewTopic[*Revoked]("consent-revoked", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type CheckParams struct {
PatientID string `json:"patient_id" encore:"sensitive"`
Purpose string `json:"purpose"`
Recipient string `json:"recipient"`
}
type CheckResponse struct {
Allowed bool `json:"allowed"`
}
// Check is called by any service before it uses or discloses data for a purpose.
//
//encore:api private method=POST path=/consent/check
func Check(ctx context.Context, p *CheckParams) (*CheckResponse, error) {
var action string
var expires *time.Time
err := db.QueryRow(ctx, `
SELECT action, expires_at FROM consent_events
WHERE patient_id = $1 AND purpose = $2 AND recipient = $3
ORDER BY recorded_at DESC, id DESC LIMIT 1`,
p.PatientID, p.Purpose, p.Recipient).Scan(&action, &expires)
if errors.Is(err, sqldb.ErrNoRows) {
return &CheckResponse{Allowed: false}, nil
} else if err != nil {
return nil, err
}
allowed := action == "granted" && (expires == nil || expires.After(time.Now()))
rlog.Info("consent check", "purpose", p.Purpose, "recipient", p.Recipient, "allowed", allowed)
return &CheckResponse{Allowed: allowed}, nil
}
type RevokeParams struct {
PatientID string `json:"patient_id" encore:"sensitive"`
Purpose string `json:"purpose"`
Recipient string `json:"recipient"`
Source string `json:"source"`
}
//encore:api auth method=POST path=/consent/revoke
func Revoke(ctx context.Context, p *RevokeParams) error {
if _, err := db.Exec(ctx, `
INSERT INTO consent_events (patient_id, purpose, recipient, action, source)
VALUES ($1, $2, $3, 'revoked', $4)`,
p.PatientID, p.Purpose, p.Recipient, p.Source); err != nil {
return err
}
_, err := Revocations.Publish(ctx, &Revoked{PatientID: p.PatientID, Purpose: p.Purpose, Recipient: p.Recipient})
return err
}
An export service calls consent.Check as a typed function before writing each file and subscribes to consent-revoked to cancel pending exports. encore run starts Postgres and the topic locally, so a test can grant, revoke and confirm that the export path stops, all against synthetic patients. Encore does not make an application HIPAA compliant on its own; what it gives you is infrastructure in your own cloud account, where your BAA with the provider and your own controls apply.
An AI coding agent adding a new integration can be told to call consent.Check with the integration's purpose and recipient, and the reviewer can verify that call in the diff rather than trusting that the agent remembered a policy document.
Best fit: healthtech teams on AWS or GCP that need one consent check enforced across services, with PHI kept in their own account.
List every purpose and recipient that data flows to, give each a consent document version, and store grants and revocations as events. Put one check in front of every disclosure path, broadcast revocations to services with pending work, and log each decision so the audit trail answers who saw what and why.
Under 45 CFR 164.508(c), a valid authorization describes the information to be disclosed, who may disclose it and who receives it, the purpose, an expiration date or event, and the individual's signature and date, plus statements about the right to revoke and the potential for redisclosure.
Record the revocation as a new event with a timestamp rather than deleting the consent, make every consent check read the latest state, and notify downstream services so queued exports or shares stop. Disclosures made before the revocation remain valid and stay in the audit log.
At the point of use or disclosure, in the service that shares or exports the data, by calling one consent check with the patient, purpose and recipient. Enforcing it only in the user interface leaves batch jobs, integrations and support tools unchecked.
Store consent events in an Encore Postgres database, expose a private Check endpoint that other services call before sharing data, and publish a Pub/Sub event on revocation so subscribers cancel pending work. The database and topic run in your own AWS or GCP account.
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.