How to build a waitlist that offers cancelled appointment slots to the right patients in priority order, with expiring offers, no double booking and notifications that carry no clinical details, with a Go example on Encore.

Cancelled appointments are lost capacity unless someone fills them. A review of 105 studies put the average no-show rate at around 23%, while the same clinics have patients waiting weeks for an earlier visit.
A waitlist that offers freed slots automatically fills those gaps without front desk calls. This guide covers matching, fair ordering, expiring offers and double booking, and builds it in Go on Postgres.
Match on what makes the slot usable: the same provider or any provider in the practice the patient accepted, the visit type and its duration, the patient's earliest and latest acceptable dates, and the location. Order the matches by clinical priority set by staff, then by how long the patient has waited. Keep the priority as a small integer the clinic controls, so urgent cases go first without the backend encoding any clinical judgment itself.
Sequential offers respect the order: the first patient gets the slot for a fixed window, for example 15 minutes, and the next patient gets it only after a decline or timeout. That is fair, but a slot opening at 07:00 for 09:00 cannot wait through four timeouts. A common rule is sequential offers for slots more than a day away and a broadcast to the top few matches, first to accept wins, for same-day slots. The example below implements sequential offers, and the broadcast variant reuses the same accept path, which already handles races.
Two things can race: an offer being accepted while it expires, and the scheduling system booking the slot directly while it is on offer. Lock the slot row with SELECT ... FOR UPDATE in every transaction that changes it, and make each state change conditional on the current state, for example accepting only an offer that is still pending and unexpired. When the waitlist and a front desk user act at the same moment, one of them gets a clear "no longer available" instead of two patients holding the same time.
Notifications travel over SMS and email, show on lock screens and sit in shared family inboxes. Send the minimum: an earlier appointment is available, reply by a time, and a link that opens the offer after the patient signs in. Leave out the visit reason, the specialty and anything else that reveals health information, in line with the minimum necessary standard that HIPAA applies to disclosures of protected health information. The patient sees the details in the authenticated app.
Each offer has an expires_at. A job runs every minute, marks pending offers past their deadline as expired and moves each affected slot on to the next patient. Declines take the same path immediately. Keep every offer row with its outcome, since "why did patient X not get the 10:30 slot" is a question the clinic will ask, and the answer is in the offer history.
Encore is a backend framework with built-in infrastructure, and the waitlist's database, its slot events and its expiry schedule are declared in the Go service below. Slots, entries and offers live in an Encore Postgres database, opened slots go through a Pub/Sub topic so offers are made off the request path, and an Encore cron job expires offers every minute. The cron job is managed by the Encore platform, and Encore provisions the database and topic in your own AWS or GCP account, so patient data stays in infrastructure you control.
Run in your terminal to get started locally.
-- waitlist/migrations/1_create_waitlist.up.sql
CREATE TABLE slots (
id BIGSERIAL PRIMARY KEY,
provider_id TEXT NOT NULL,
visit_type TEXT NOT NULL,
starts_at TIMESTAMPTZ NOT NULL,
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'offered', 'booked')),
patient_id TEXT
);
CREATE TABLE waitlist_entries (
id BIGSERIAL PRIMARY KEY,
patient_id TEXT NOT NULL,
provider_id TEXT, -- NULL means any provider
visit_type TEXT NOT NULL,
earliest DATE NOT NULL,
latest DATE NOT NULL,
priority INT NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'waiting' CHECK (status IN ('waiting', 'booked', 'removed')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX waitlist_match ON waitlist_entries (visit_type, priority DESC, created_at)
WHERE status = 'waiting';
CREATE TABLE offers (
id BIGSERIAL PRIMARY KEY,
slot_id BIGINT NOT NULL REFERENCES slots (id),
entry_id BIGINT NOT NULL REFERENCES waitlist_entries (id),
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'accepted', 'declined', 'expired')),
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (slot_id, entry_id)
);
CREATE INDEX offers_pending ON offers (expires_at) WHERE status = 'pending';
// waitlist/waitlist.go
package waitlist
import (
"context"
"errors"
"fmt"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("waitlist", sqldb.DatabaseConfig{Migrations: "./migrations"})
type SlotOpened struct {
SlotID int64
}
var SlotsOpened = pubsub.NewTopic[*SlotOpened]("slots-opened", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
// OfferMade goes to the notification service, which sends a message without clinical details.
type OfferMade struct {
OfferID int64
PatientID string
}
var OffersMade = pubsub.NewTopic[*OfferMade]("offers-made", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
// ReleaseSlot is called by the scheduling service when an appointment is cancelled.
//
//encore:api private method=POST path=/slots/:slotID/release
func ReleaseSlot(ctx context.Context, slotID int64) error {
_, err := db.Exec(ctx, `UPDATE slots SET status = 'open', patient_id = NULL WHERE id = $1`, slotID)
if err != nil {
return err
}
// Old offers for the slot die here, so none can be accepted over a later booking.
_, err = db.Exec(ctx, `UPDATE offers SET status = 'expired' WHERE slot_id = $1 AND status = 'pending'`, slotID)
if err != nil {
return err
}
_, err = SlotsOpened.Publish(ctx, &SlotOpened{SlotID: slotID})
return err
}
var _ = pubsub.NewSubscription(SlotsOpened, "offer-next-patient", pubsub.SubscriptionConfig[*SlotOpened]{
Handler: func(ctx context.Context, e *SlotOpened) error { return offerNext(ctx, e.SlotID) },
})
func offerNext(ctx context.Context, slotID int64) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
var status, provider, visitType string
err = tx.QueryRow(ctx, `SELECT status, provider_id, visit_type FROM slots
WHERE id = $1 AND starts_at > now() FOR UPDATE`, slotID).Scan(&status, &provider, &visitType)
if errors.Is(err, sqldb.ErrNoRows) {
return nil // slot is in the past
} else if err != nil {
return err
}
if status != "open" {
return nil // already offered or booked, a duplicate event is a no-op
}
var entryID int64
var patientID string
err = tx.QueryRow(ctx, `
SELECT e.id, e.patient_id FROM waitlist_entries e, slots s
WHERE s.id = $1 AND e.status = 'waiting' AND e.visit_type = $2
AND (e.provider_id IS NULL OR e.provider_id = $3)
AND s.starts_at::date BETWEEN e.earliest AND e.latest
AND NOT EXISTS (SELECT 1 FROM offers o WHERE o.slot_id = s.id AND o.entry_id = e.id)
ORDER BY e.priority DESC, e.created_at
LIMIT 1
FOR UPDATE OF e SKIP LOCKED`, slotID, visitType, provider).Scan(&entryID, &patientID)
if errors.Is(err, sqldb.ErrNoRows) {
return tx.Commit() // nobody left to offer it to, the slot stays open for normal booking
} else if err != nil {
return err
}
var offerID int64
if err := tx.QueryRow(ctx, `
INSERT INTO offers (slot_id, entry_id, expires_at)
VALUES ($1, $2, now() + interval '15 minutes') RETURNING id`, slotID, entryID).Scan(&offerID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE slots SET status = 'offered' WHERE id = $1`, slotID); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
_, err = OffersMade.Publish(ctx, &OfferMade{OfferID: offerID, PatientID: patientID})
return err
}
type RespondParams struct {
PatientID string // set by the API layer from the signed-in patient
Accept bool
}
//encore:api private method=POST path=/offers/:offerID/respond
func Respond(ctx context.Context, offerID int64, p *RespondParams) error {
tx, err := db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback()
var slotID, entryID int64
err = tx.QueryRow(ctx, `
SELECT o.slot_id, o.entry_id FROM offers o
JOIN waitlist_entries e ON e.id = o.entry_id
JOIN slots s ON s.id = o.slot_id
WHERE o.id = $1 AND e.patient_id = $2 AND o.status = 'pending' AND o.expires_at > now()
AND s.status = 'offered'
FOR UPDATE OF o, s`, offerID, p.PatientID).Scan(&slotID, &entryID)
if errors.Is(err, sqldb.ErrNoRows) {
return &errs.Error{Code: errs.FailedPrecondition, Message: "this offer is no longer available"}
} else if err != nil {
return err
}
if p.Accept {
if _, err := tx.Exec(ctx, `UPDATE offers SET status = 'accepted' WHERE id = $1`, offerID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE slots SET status = 'booked', patient_id = $2 WHERE id = $1`, slotID, p.PatientID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE waitlist_entries SET status = 'booked' WHERE id = $1`, entryID); err != nil {
return err
}
return tx.Commit()
}
if _, err := tx.Exec(ctx, `UPDATE offers SET status = 'declined' WHERE id = $1`, offerID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE slots SET status = 'open' WHERE id = $1`, slotID); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
_, err = SlotsOpened.Publish(ctx, &SlotOpened{SlotID: slotID})
return err
}
var _ = cron.NewJob("expire-offers", cron.JobConfig{
Title: "Expire unanswered waitlist offers",
Every: 1 * cron.Minute,
Endpoint: ExpireOffers,
})
//encore:api private
func ExpireOffers(ctx context.Context) error {
rows, err := db.Query(ctx, `
WITH expired AS (
UPDATE offers SET status = 'expired'
WHERE status = 'pending' AND expires_at <= now()
RETURNING slot_id)
UPDATE slots SET status = 'open'
WHERE id IN (SELECT slot_id FROM expired) AND status = 'offered'
RETURNING id`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var slotID int64
if err := rows.Scan(&slotID); err != nil {
return err
}
if _, err := SlotsOpened.Publish(ctx, &SlotOpened{SlotID: slotID}); err != nil {
return fmt.Errorf("republish slot %d: %w", slotID, err)
}
}
return rows.Err()
}
Every path that hands a slot to the next patient goes through the same slots-opened event, whether the trigger was a cancellation, a decline or an expiry, so there is one place where matching and ordering happen. Duplicate events are harmless: the subscriber locks the slot and does nothing unless it is still open. SKIP LOCKED on the waitlist row keeps two slots opening at once from offering both to the same patient in parallel, and the UNIQUE (slot_id, entry_id) constraint means nobody is offered the same slot twice.
Respond is private, so the patient app's API layer authenticates the patient and passes the patient ID in, and the query checks that the offer belongs to that patient. The notification service subscribes to offers-made and sends a message with a link to the offer and nothing about the visit.
The expiry job does not run under encore run or in preview environments, so locally you call ExpireOffers from the development dashboard after an offer's deadline, and watch the slot move to the next patient in the local trace. When the clinic asks for a same-day broadcast rule, an agent can add it to offerNext and replay cancel, decline and expiry against the local database in the same change.
Best fit: Clinics and healthtech teams that want cancelled appointments refilled automatically in a fair, auditable order, with patient data kept in their own cloud account.
When a slot opens, the backend finds waiting patients whose provider, visit type and date window match, offers the slot to the highest priority one with a short deadline, and moves to the next patient when the offer is declined or expires. Accepting books the slot and removes the patient from the waitlist.
Offering to one patient at a time respects clinical priority and avoids patients accepting a slot that is already gone. Broadcasting to several fills slots faster for same-day openings. Many clinics offer sequentially with a short deadline and switch to broadcast when the slot is only hours away.
As little as possible: that an earlier appointment is available and a link to view it after signing in. Leave out diagnoses, visit reasons and provider specialties, since SMS and email previews are visible to anyone holding the phone.
Keep slots, waitlist entries and offers in an Encore Postgres database, publish a Pub/Sub event when a slot opens, make the offer in a subscriber with row locks, and run an Encore cron job every minute that expires unanswered offers and moves the slot to the next patient.
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.