Nov 18, 202611 min read

Telehealth Visit Backend: Scheduling, Waiting Room, Join Tokens and Visit Notes

Model a virtual visit as a state machine, admit only the right patient and clinician to the video room, keep PHI out of events and logs, mark no-shows on a schedule, and lock notes once they are signed.

Illustration for Telehealth Visit Backend: Scheduling, Waiting Room, Join Tokens and Visit Notes

A telehealth visit looks like a video call with a calendar invite. The backend behind it carries more weight than that: it decides who gets into a room with a patient, tracks whether the visit happened, holds the clinician's notes and hands the result to billing and follow-up. Most of that data is protected health information, so the rules about who can read what apply to every table, queue and log line.

This guide models the visit lifecycle, then builds it in Go: a visit state machine, a waiting room, short-lived join tokens, a no-show job, signed notes and a PHI-free event for downstream services. It does not cover the media layer, which can come from a video provider or an open source media server.

The Visit Lifecycle at a Glance

StateEntered whenAllowed next states
scheduledVisit bookedwaiting, cancelled, no_show
waitingPatient checks inin_progress, cancelled
in_progressClinician admits the patientcompleted
completedClinician ends the visit(notes signed separately)
no_showPatient did not check in 15 minutes after startnone
cancelledEither side cancels before it startsnone

What the Backend Has to Get Right

Transitions are conditional. "Admit patient" should only work from waiting, and "end visit" only from in_progress. Writing each transition as UPDATE visits SET status = $new WHERE id = $id AND status = $expected and checking the affected row count means a double click, a retry or two devices acting at once cannot skip a state.

Room access is checked on every join. The video link should not be the credential. The patient's and clinician's apps ask the backend for a join token, the backend checks that the caller is a participant and the visit is in a joinable state, and the token it returns names the room and the person and expires in minutes. JWTs as defined in RFC 7519 are the usual format, and many video providers accept a token signed with your API secret in a shape they document.

PHI stays in the database. Events carry the visit ID and nothing else. A billing or follow-up consumer that needs the diagnosis code reads it from the database through an endpoint that checks access. Queue messages, dead-letter queues and logs are then not additional stores of PHI, which simplifies the access review the HIPAA Security Rule expects.

Notes lock when signed. A clinician can draft and edit notes during and after the visit. Signing records who signed and when, and after that the note is append-only: corrections are addenda, not edits.

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 visit path against those lists, and get a BAA from every vendor that handles PHI, including the video provider and any email or SMS provider. Infrastructure choices support compliance work. They do not replace it.

How Do You Build It by Hand on AWS?

The pieces are an RDS for PostgreSQL database in private subnets with encryption at rest, an SNS topic for visit events with an SQS queue and dead-letter queue per consumer, an EventBridge Scheduler rule for the no-show job, Secrets Manager for the video API secret, a container service for the API, and IAM policies scoped so each service reads only its own secret and queue. Each of those also needs a staging copy, and the review of who can read PHI has to cover all of them.

How Do You Build It with Encore?

Encore

Encore is a backend framework with built-in infrastructure. The visits database, the topic for ended visits, the no-show cron job and the video API secret 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 and Secrets Manager on AWS, or Cloud SQL, Pub/Sub and Secret Manager on GCP, and Encore provisions an IAM role for the service, or a service account on GCP. The secret's production value is set with encore secret set and is not in the repository, so an AI coding agent working in the repo cannot read that value. A local override in .secrets.local.cue is readable if it is present. Cron jobs are managed by the Encore platform and do not run locally or in preview environments.

Set Up the App

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

Run in your terminal to get started locally.

-- visits/migrations/1_visits.up.sql CREATE TABLE visits ( id TEXT PRIMARY KEY, patient_id TEXT NOT NULL, clinician_id TEXT NOT NULL, scheduled_at TIMESTAMPTZ NOT NULL, status TEXT NOT NULL DEFAULT 'scheduled' CHECK (status IN ('scheduled', 'waiting', 'in_progress', 'completed', 'no_show', 'cancelled')), checked_in_at TIMESTAMPTZ, started_at TIMESTAMPTZ, ended_at TIMESTAMPTZ ); CREATE INDEX visits_due ON visits (scheduled_at) WHERE status = 'scheduled'; CREATE TABLE visit_notes ( visit_id TEXT PRIMARY KEY REFERENCES visits (id), body TEXT NOT NULL, signed_by TEXT, signed_at TIMESTAMPTZ, updated_at TIMESTAMPTZ NOT NULL DEFAULT now() );

Authenticate Patients and Clinicians

The auth handler resolves the session token to a user ID and a role. Replace lookupSession with your identity provider.

// visits/auth.go package visits import ( "context" "encore.dev/beta/auth" "encore.dev/beta/errs" ) type UserData struct { Role string // "patient" or "clinician" } //encore:authhandler func AuthHandler(ctx context.Context, token string) (auth.UID, *UserData, error) { userID, role, ok := lookupSession(ctx, token) if !ok { return "", nil, &errs.Error{Code: errs.Unauthenticated, Message: "invalid session"} } return auth.UID(userID), &UserData{Role: role}, nil } // lookupSession validates the token with your identity provider. func lookupSession(ctx context.Context, token string) (userID, role string, ok bool) { return "", "", false }

Transitions and Join Tokens

transition is the only function that changes status, and it fails unless the visit is in the expected state. Join checks that the caller is a participant and the visit is joinable before signing a token that expires in five minutes.

// visits/visits.go package visits import ( "context" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "time" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/pubsub" "encore.dev/storage/sqldb" ) var db = sqldb.NewDatabase("visits", sqldb.DatabaseConfig{Migrations: "./migrations"}) var secrets struct { VideoAPISecret string // signs join tokens for the video provider } // VisitEnded carries only the visit ID, never PHI. type VisitEnded struct { VisitID string } var VisitEndedTopic = pubsub.NewTopic[*VisitEnded]("visit-ended", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type visit struct { PatientID, ClinicianID, Status string } func loadForCaller(ctx context.Context, visitID string) (*visit, string, error) { uid, _ := auth.UserID() var v visit err := db.QueryRow(ctx, ` SELECT patient_id, clinician_id, status FROM visits WHERE id = $1`, visitID, ).Scan(&v.PatientID, &v.ClinicianID, &v.Status) if errors.Is(err, sqldb.ErrNoRows) { return nil, "", &errs.Error{Code: errs.NotFound, Message: "visit not found"} } else if err != nil { return nil, "", err } if string(uid) != v.PatientID && string(uid) != v.ClinicianID { // Same answer as a missing visit, so IDs cannot be probed. return nil, "", &errs.Error{Code: errs.NotFound, Message: "visit not found"} } return &v, string(uid), nil } func transition(ctx context.Context, visitID, from, to, tsColumn string) error { res, err := db.Exec(ctx, ` UPDATE visits SET status = $3, `+tsColumn+` = now() WHERE id = $1 AND status = $2`, visitID, from, to) if err != nil { return err } if res.RowsAffected() != 1 { return &errs.Error{Code: errs.FailedPrecondition, Message: "visit is not " + from} } return nil } // CheckIn moves the patient into the waiting room. // //encore:api auth method=POST path=/visits/:id/check-in func CheckIn(ctx context.Context, id string) error { v, uid, err := loadForCaller(ctx, id) if err != nil { return err } if uid != v.PatientID { return &errs.Error{Code: errs.PermissionDenied, Message: "only the patient can check in"} } return transition(ctx, id, "scheduled", "waiting", "checked_in_at") } // Admit starts the visit. Only the clinician can admit. // //encore:api auth method=POST path=/visits/:id/admit func Admit(ctx context.Context, id string) error { v, uid, err := loadForCaller(ctx, id) if err != nil { return err } if uid != v.ClinicianID { return &errs.Error{Code: errs.PermissionDenied, Message: "only the clinician can admit"} } return transition(ctx, id, "waiting", "in_progress", "started_at") } // End completes the visit and notifies billing and follow-up. // //encore:api auth method=POST path=/visits/:id/end func End(ctx context.Context, id string) error { v, uid, err := loadForCaller(ctx, id) if err != nil { return err } if uid != v.ClinicianID { return &errs.Error{Code: errs.PermissionDenied, Message: "only the clinician can end the visit"} } if err := transition(ctx, id, "in_progress", "completed", "ended_at"); err != nil { return err } _, err = VisitEndedTopic.Publish(ctx, &VisitEnded{VisitID: id}) return err } type JoinResponse struct { Token string `encore:"sensitive"` ExpiresAt time.Time } // Join returns a short-lived token for the visit's video room. // //encore:api auth method=POST path=/visits/:id/join func Join(ctx context.Context, id string) (*JoinResponse, error) { v, uid, err := loadForCaller(ctx, id) if err != nil { return nil, err } joinable := v.Status == "in_progress" || (v.Status == "waiting" && uid == v.ClinicianID) if !joinable { return nil, &errs.Error{Code: errs.FailedPrecondition, Message: "visit is not open yet"} } exp := time.Now().Add(5 * time.Minute) token, err := signToken(map[string]any{"sub": uid, "room": "visit-" + id, "exp": exp.Unix()}) if err != nil { return nil, err } return &JoinResponse{Token: token, ExpiresAt: exp}, nil } // signToken builds an HS256 JWT. Shape the claims to what your video provider expects. func signToken(claims map[string]any) (string, error) { enc := base64.RawURLEncoding header := enc.EncodeToString([]byte(`{"alg":"HS256","typ":"JWT"}`)) body, err := json.Marshal(claims) if err != nil { return "", err } unsigned := header + "." + enc.EncodeToString(body) mac := hmac.New(sha256.New, []byte(secrets.VideoAPISecret)) mac.Write([]byte(unsigned)) return unsigned + "." + enc.EncodeToString(mac.Sum(nil)), nil }

The column name passed to transition comes from code, never from a request, which keeps the string concatenation safe. A clinician can join while the patient is still waiting, so they can check audio and video before admitting. The join token is tagged encore:"sensitive", which per the sensitive data docs redacts it from Encore's request traces. The tag is ignored in local development, so use synthetic visits under encore run.

Mark No-Shows on a Schedule

Every 15 minutes, visits still in scheduled 15 minutes after their start time become no_show. The update is conditional on the status, so a patient checking in at the same moment either wins or loses cleanly.

// visits/noshow.go package visits import ( "context" "encore.dev/cron" ) var _ = cron.NewJob("mark-no-shows", cron.JobConfig{ Title: "Mark visits with no check-in as no-show", Every: 15 * cron.Minute, Endpoint: MarkNoShows, }) type NoShowResult struct { Marked int64 } //encore:api private func MarkNoShows(ctx context.Context) (*NoShowResult, error) { res, err := db.Exec(ctx, ` UPDATE visits SET status = 'no_show' WHERE status = 'scheduled' AND scheduled_at < now() - interval '15 minutes'`) if err != nil { return nil, err } return &NoShowResult{Marked: res.RowsAffected()}, nil }

Sign Notes

Drafts are upserts that only succeed while signed_at is null. Signing sets signed_by and signed_at in one conditional update, after which the draft endpoint no longer matches the row.

// visits/notes.go package visits import ( "context" "encore.dev/beta/errs" ) type NoteParams struct { Body string `encore:"sensitive"` } //encore:api auth method=PUT path=/visits/:id/notes func SaveNote(ctx context.Context, id string, p *NoteParams) error { v, uid, err := loadForCaller(ctx, id) if err != nil { return err } if uid != v.ClinicianID { return &errs.Error{Code: errs.PermissionDenied, Message: "only the clinician can write notes"} } res, err := db.Exec(ctx, ` INSERT INTO visit_notes (visit_id, body) VALUES ($1, $2) ON CONFLICT (visit_id) DO UPDATE SET body = EXCLUDED.body, updated_at = now() WHERE visit_notes.signed_at IS NULL`, id, p.Body) if err != nil { return err } if res.RowsAffected() == 0 { return &errs.Error{Code: errs.FailedPrecondition, Message: "note is signed; add an addendum instead"} } return nil } //encore:api auth method=POST path=/visits/:id/notes/sign func SignNote(ctx context.Context, id string) error { v, uid, err := loadForCaller(ctx, id) if err != nil { return err } if uid != v.ClinicianID || v.Status != "completed" { return &errs.Error{Code: errs.FailedPrecondition, Message: "only the clinician can sign, after the visit"} } res, err := db.Exec(ctx, ` UPDATE visit_notes SET signed_by = $2, signed_at = now() WHERE visit_id = $1 AND signed_at IS NULL`, id, uid) if err != nil { return err } if res.RowsAffected() != 1 { return &errs.Error{Code: errs.FailedPrecondition, Message: "no unsigned note to sign"} } return nil }

The note body is tagged encore:"sensitive" as well, so clinical text is redacted from traces in deployed environments. Call the access log from these endpoints as shown in the PHI audit log guide, rather than treating request traces as the audit trail. A billing service subscribes to visit-ended and reads what it needs through its own endpoint, with its own access checks and audit entries. A subscriber that keeps failing ends up in a dead-letter queue holding only visit IDs.

Things to Decide Early

  • Time zones. Store scheduled_at in UTC and render it in the patient's and clinician's zones. A visit across a state line can have two.
  • Licensure by state. Clinicians are usually licensed per state. Check the patient's location at booking and again at check-in.
  • Recording. Recording visits adds consent, storage and retention rules. Decide before launch whether you record at all.
  • Interpreters and guests. A third participant needs its own token and a role the join check understands.
  • Retention. Medical record retention periods vary by state and record type. Notes are kept far longer than visit metadata.

Frequently asked questions

What does a telehealth backend need besides video?

The video itself usually comes from a provider or a media server. The backend owns everything around it: scheduling, who is allowed into which room and when, the waiting room and visit status, clinical notes and their signing, no-show handling, events for billing and follow-up, and an access log for protected health information.

How do you control who can join a telehealth video room?

Issue a short-lived join token from your backend only after checking that the caller is the visit's patient or clinician and that the visit is in a joinable state. The token names the room and the participant and expires within minutes, so a forwarded link is useless once it lapses.

How should telehealth visit status be stored?

As an explicit state machine, for example scheduled, waiting, in progress, completed, no show and cancelled. Each transition is a conditional update that only succeeds from the expected previous state, so two clients acting at once cannot move the visit into an invalid state.

Should PHI go into queue messages and logs?

No. Keep it out where you can. Put the visit ID in events and let consumers read details from the database under their own access checks. That keeps PHI out of queue storage, dead-letter queues and log pipelines, which are easy to forget when reviewing who can see patient data.

How do I deploy a telehealth backend to my own AWS account without Terraform?

With Encore, the visits database, the visit-ended topic, the no-show cron job and the video API secret are declared in Go next to the handlers. encore run starts them locally, and a deploy creates RDS, SNS with SQS and Secrets Manager in your own AWS account, or Cloud SQL, Pub/Sub and Secret Manager 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.

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