State-Licensed Virtual Care Queue
Medium · System Design · Software Engineer · Onsite
Prompt
A national health plan offers its insured members round-the-clock, zero-cost virtual doctor visits accessible from both browser and mobile apps. Members request care from across dozens of U.S. states, and the insurer staffs its own roster of physicians to handle incoming visits. Under state medical board regulations, each physician holds active credentials in only a specific subset of states and is legally permitted to treat a patient only when certified for the state where that patient is physically located during the encounter.
For example, if Patient M-104 connects from Oregon (OR) while Patient M-209 connects from Florida (FL), a clinician licensed solely in {FL, GA} may serve M-209 right away, whereas M-104 must wait for a clinician whose active credentials include OR.
Architect the system that lets members enter the virtual waiting room and enables on-shift clinicians to claim, conduct, and resolve consultations swiftly, safely, and in full regulatory compliance.
Scope & Expectations
- Requirements & compliance boundaries: Clarify clinical triage, state-location rules, healthcare data-privacy obligations, and realistic traffic vs. staffing constraints.
- APIs & persistence schema: Define member, clinician, and operations endpoints alongside storage schemas for consultations, clinician credentials, and audit trails.
- Multi-state matching & concurrency: Detail how waiting requests are prioritized across overlapping state licenses without starving routine or small-state patients, and how concurrent claims prevent double-booking.
- Reliability, scaling & operations: Address real-time status updates, clinician or patient disconnects, license expiration/revocation edge cases, and live per-state coverage monitoring.
Step-by-step walkthrough
Clarify requirements, clinical safety, and scope
Traffic volume is not what makes this system hard—as we will calculate next, peak load is well below one new consultation per second. The real engineering challenges are legal compliance (never matching a patient to a physician unlicensed in the patient's current state), strict concurrency (never assigning one patient to two physicians or one physician to two live calls), fairness (keeping small states and routine cases from waiting forever), and health-privacy rules.
Functional requirements
- Members (or parents acting for a minor dependent) can request an on-demand 24/7 virtual visit from web or mobile after completing a brief intake: current physical state, visit category, symptoms, callback phone number, and clinical triage questions.
- Waiting members see live status updates and an estimated wait-time range, can cancel anytime, receive a push/SMS alert when their physician opens the room, and join the video call.
- Physicians sign in with multi-factor authentication (MFA), toggle availability, claim the next eligible patient, verify the patient's physical state on the call, and either complete the consult, return it to the queue without losing the patient's spot, or record a no-show.
- A match is allowed only when the physician holds an active, unexpired license for the US state where the patient is physically located during the visit.
- Operations staff monitor live wait times and licensed physician headcount per state and get paged whenever any state drops to zero coverage.
Non-functional requirements
- Regulatory compliance: Zero unlicensed matches. All PHI (Protected Health Information—any identifiable health or symptom record) is encrypted in transit and at rest, every read is audit-logged, and every external vendor handling PHI signs a BAA (Business Associate Agreement, a legally required privacy contract under US HIPAA healthcare law).
- Concurrency invariants: At most one active physician per consult; at most one active video visit per physician; at most one open consult per patient.
- Availability and durability:
99.95%uptime (~22 minutes/month budget) for 24/7 care, and zero lost requests once acknowledged (201 Created). - Latency and fairness: API p99 under
300 ms; status updates pushed to screens within2 seconds; urgent and scarce-state cases prioritized without letting routine requests starve indefinitely.
Clarifying assumptions confirmed up front
- Which state governs licensing—home address or current physical location? Current physical location during the call. US medical boards regulate care where the patient is physically sitting (for example, a New York resident vacationing in Florida needs a Florida-licensed physician). The member attests to their state at intake, and the physician verbally re-confirms it when the call connects.
- Visit categories and call media? Three categories—general urgent care, pediatrics, and behavioral health—each requiring matching physician qualifications. Video first (hosted by a HIPAA-eligible WebRTC vendor under a BAA), with phone call fallback.
- Emergencies? Intake answers matching red-flag symptoms (such as chest pain with shortness of breath or crisis thoughts) are never placed in a queue; the API immediately returns instructions to call
911or988. - Clinical notes and prescriptions? Handed off to the insurer's existing Electronic Health Record (EHR) and e-prescribing systems once a consult starts or completes. Assume coverage spans
20US states.
Back-of-the-envelope numbers and the small-state bottleneck
We use Little's law—a fundamental queueing rule stating that the average number of active items
Lequals the arrival ratelambdamultiplied by the average timeWeach item spends in the system (L = lambda * W).Consultation arrival rates (assumed for 3,000,000 insured members across 20 states) annual visits 3M members * 0.5 visits/year = 1,500,000 consults/year (~4,100/day) peak flu-season Monday 2.5x daily average = ~10,000 consults/day peak hour (10% of peak day) 1,000 consults/hour = ~0.28 requests/second quietest hour (3-4 AM) 1% of peak day = ~100 consults/hour Active physicians via Little's law (12 min video call + 3 min clinical charting = 15 min = 0.25 h) busy physicians at peak 1,000/h * 0.25 h = 250 physicians actively handling visits on-shift headcount (80% target utilization) = 250 / 0.80 = ~315 physicians (before state slack) busy physicians at 3 AM 100/h * 0.25 h = 25 physicians Queue size, live connections, and database load members waiting at peak 1,000/h * (10 min = 1/6 h average wait) = ~170 waiting patients concurrent WebSockets ~170 waiting + ~250 in calls + ~315 physicians = < 1,000 sockets database write rate 1,000 consults/h * ~20 state/audit/outbox writes = ~6 writes/second annual database growth 1.5M consults * ~15 KB = ~23 GB/yearWhy these numbers shape the entire architecture
Six database writes per second and a few hundred waiting rows fit comfortably inside one PostgreSQL primary with 100x headroom to spare. Introducing Kafka, Redis queues, or database sharding here would add split-brain failure modes for zero throughput benefit.
Instead, the real bottleneck is licensed physician capacity in small states:
Small state example (0.5% of membership): Peak hour: 1,000/h * 0.5% = 5 arrivals/hour. 1 physician handles 4 visits/hour (15 min each) -> utilization = 5/4 = 125% (queue explodes!) 2 physicians handle 8 visits/hour -> utilization = 5/8 = 63% (healthy) 3 AM night: 100/h * 0.5% = 0.5 arrivals/hour (1 patient every 2 hours), yet at least 1-2 physicians licensed in that state MUST still be awake on shift!Software cannot mint medical licenses, so our matching algorithm must protect scarce-state licenses from being tied up by states with plenty of doctors, and our ops service must surface per-state staffing gaps within seconds.
API design
Member endpoints (authenticated member session) POST /v1/consults Header: Idempotency-Key: <client-generated UUID> { "patient": "self" | { "dependent_id": "dep-17" }, "location_state": "FL", "location_attested": true, "visit_type": "general" | "pediatric" | "behavioral", "reason_code": "sinus_infection", "symptoms": "Sinus pressure and fever since last night", "triage_answers": { "chest_pain": false, "breathing_difficulty": false }, "callback_phone": "+13055550148" } -> 201 { "consult_id": "c-4a8", "status": "WAITING", "estimated_wait_min": [10, 20] } -> 200 same payload if retried with the same Idempotency-Key -> 409 OPEN_CONSULT_EXISTS (returns existing open consult_id) -> 422 EMERGENCY_SYMPTOMS (returns 911/988 guidance; never queued) -> 422 STATE_NOT_SERVED (insurer has zero physicians licensed there; offers nurse line) GET /v1/consults/{id} current status, wait range, assigned doctor, short-lived video token PATCH /v1/consults/{id} { "location_state": "GA" } (allowed while WAITING; keeps queue timestamp) POST /v1/consults/{id}/cancel WS /v1/consults/{id}/events pushes status transitions and refreshed wait estimates Physician endpoints (workforce SSO + MFA) PUT /v1/physicians/me/availability { "status": "AVAILABLE" | "OFFLINE" } POST /v1/physicians/me/claim-next -> 200 { consult + intake } | 204 (no eligible waiting patient) POST /v1/consults/{id}/ready creates video room, sets ready_at, alerts member ("Doctor ready") POST /v1/consults/{id}/confirm-location { "state": "FL" } (logged verbally at start of call) POST /v1/consults/{id}/release { "reason": "wrong_state" | "needs_specialist" } (keeps spot) POST /v1/consults/{id}/no-show POST /v1/consults/{id}/complete { "disposition": "treated" | "referred_in_person" } WS /v1/physicians/me/events 15s heartbeats + live waiting counts for licensed states Operations endpoint GET /v1/ops/coverage per state: waiting count, p90 wait, on-shift licensed doctorsWhy the API is shaped this way
- An
Idempotency-Key(a unique request token generated by the client before sending) ensures that if a patient's phone drops cell signal and retriesPOST /v1/consults, the server returns the original consult instead of putting them in line twice. claim-nextaccepts noconsult_id. Physicians pull work at their own pace, while the server chooses which patient comes next. Letting doctors pick from a waiting room list invites cherry-picking easy colds over complex cases and causes constant click races between doctors.- Wait-time ranges (
[10, 20]min) instead of queue numbers ("You are #4"). Because urgent cases and multi-state licensing let patients move at different speeds, a literal line number can jump backward from#4to#6, frustrating sick members.
- An
Data model and consult state machine
PostgreSQL is the single source of truth for queues, assignments, and licenses. We use partial unique indexes (database uniqueness rules applied only to rows matching a
WHEREfilter) so PostgreSQL itself makes double-booking physically impossible to store:CREATE TABLE physicians ( physician_id BIGINT PRIMARY KEY, npi TEXT UNIQUE NOT NULL, -- US National Provider Identifier display_name TEXT NOT NULL, visit_types TEXT[] NOT NULL, -- e.g., {'general', 'pediatric'} status TEXT NOT NULL, -- OFFLINE | AVAILABLE | IN_VISIT last_heartbeat TIMESTAMPTZ ); CREATE TABLE physician_licenses ( physician_id BIGINT NOT NULL REFERENCES physicians, state CHAR(2) NOT NULL, license_number TEXT NOT NULL, status TEXT NOT NULL, -- ACTIVE | EXPIRED | SUSPENDED | REVOKED expires_at TIMESTAMPTZ NOT NULL, verified_at TIMESTAMPTZ NOT NULL, -- last check against state medical board PRIMARY KEY (physician_id, state, license_number) ); CREATE TABLE consults ( consult_id UUID PRIMARY KEY, member_id BIGINT NOT NULL, patient_id BIGINT NOT NULL, -- member or minor dependent idempotency_key TEXT NOT NULL, location_state CHAR(2) NOT NULL, visit_type TEXT NOT NULL, urgency TEXT NOT NULL, -- ROUTINE | URGENT (set by clinical triage rules) intake_id UUID NOT NULL, -- points to field-encrypted symptom table status TEXT NOT NULL, -- WAITING | ASSIGNED | IN_PROGRESS | COMPLETED | CANCELLED | NO_SHOW modality TEXT NOT NULL DEFAULT 'video', queue_entered_at TIMESTAMPTZ NOT NULL, -- preserved if released back to WAITING! physician_id BIGINT REFERENCES physicians, assigned_at TIMESTAMPTZ, -- when physician claimed the consult ready_at TIMESTAMPTZ, -- when physician opened video room & paged member started_at TIMESTAMPTZ, -- when both sides connected (IN_PROGRESS) ended_at TIMESTAMPTZ, end_reason TEXT, version INT NOT NULL DEFAULT 0, -- optimistic concurrency counter for timer races UNIQUE (member_id, idempotency_key) ); -- Database-enforced invariants: impossible to violate even under application bugs or race conditions CREATE UNIQUE INDEX one_open_consult_per_patient ON consults (patient_id) WHERE status IN ('WAITING', 'ASSIGNED', 'IN_PROGRESS'); CREATE UNIQUE INDEX one_open_visit_per_physician ON consults (physician_id) WHERE status IN ('ASSIGNED', 'IN_PROGRESS'); CREATE INDEX waiting_by_state ON consults (location_state, queue_entered_at) WHERE status = 'WAITING'; CREATE TABLE consult_events ( -- append-only state audit trail event_id BIGSERIAL PRIMARY KEY, consult_id UUID NOT NULL, from_status TEXT, to_status TEXT NOT NULL, actor_type TEXT NOT NULL, -- member | physician | system | ops actor_id TEXT, at TIMESTAMPTZ NOT NULL DEFAULT now(), details JSONB ); CREATE INDEX consult_events_by_consult ON consult_events (consult_id, event_id); CREATE TABLE phi_access_log ( -- HIPAA audit log of every PHI read id BIGSERIAL PRIMARY KEY, actor_id TEXT NOT NULL, patient_id BIGINT NOT NULL, consult_id UUID, resource TEXT NOT NULL, purpose TEXT NOT NULL, at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE outbox ( -- transactional outbox for reliable side effects id BIGSERIAL PRIMARY KEY, topic TEXT NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), published_at TIMESTAMPTZ );Keeping
ready_atdistinct fromstarted_atavoids a subtle bug:ready_atstarts the 5-minute member-join countdown while the status is stillASSIGNED, whereasstarted_atrecords when both parties actually connect (IN_PROGRESS), soNO_SHOWvisits never look like started clinical encounters.Consult lifecycle state machine member cancels +------------------------------------+ | v [ WAITING ] --- physician claims ---> [ ASSIGNED ] --- 5m after ready_at, ---> [ NO_SHOW ] ^ ^ | | doctor online | | release / doctor offline | | | +-------------------------------+ | both join video (or phone fallback) | v +---- wrong state / specialist ---- [ IN_PROGRESS ] --- visit done -------> [ COMPLETED ] (preserves queue_entered_at!)High-level architecture
Member Web / Mobile App Physician Portal | HTTPS + WebSocket | HTTPS + WebSocket v v [ Load Balancer + API Gateway ] (Member Auth | Workforce SSO + MFA) | | | v v v [ Member Consult API ] [ Realtime Gateway ] [ Physician Queue API ] triage, create, cancel stateless WebSockets availability, claim-next, & 15s heartbeats ready, release, complete | ^ | | | Redis Pub/Sub fan-out | v | v [ PostgreSQL Primary ] === sync replication ===> [ Standby Primary (AZ 2) ] ---> [ Async Read Replica ] (consults, physicians, licenses, events, phi_access_log, outbox) | | | v v v [ Outbox Relay ] [ Timeout Reaper ] [ Coverage & Wait-Estimate Job ] ---> [ Ops Dashboard / Pager ] | +---> [ Push / SMS Service (zero PHI in message text) ] +---> [ Video Vendor API (creates HIPAA room + join tokens) ] +---> [ EHR Integration (creates clinical encounter) ] +---> [ Immutable WORM Audit Bucket ] [ Credentialing & State Board Sync ] ---> updates physician_licensesHow the pieces stay consistent
- Modular monolith or small stateless services over one database. All state changes commit in PostgreSQL first, replicated synchronously to a standby in a second availability zone so a machine crash loses zero committed consults.
- Transactional outbox pattern (writing outgoing notification/video jobs into an
outboxdatabase table inside the exact same SQL transaction as the status change, then having a background relay worker deliver them). This eliminates the classic dual-write bug where an SMS says "Your doctor is ready" after a database rollback, or a crash drops the SMS after committing. - Stateless WebSocket fan-out with pull-on-reconnect. Redis Pub/Sub only pushes lightweight wake-up events to open sockets. Whenever a mobile app reconnects after an elevator or tunnel drop, it immediately calls
GET /v1/consults/{id}so missed pub/sub messages never leave a screen stale.
Deep dive 1: Matching physicians to patients fairly without starvation
Step 1 — Hard legal eligibility filter. Physician
Pcan see waiting consultCif and only if: 1.P.status = 'AVAILABLE'andPholds no open visit; 2.C.visit_typeis inP.visit_types; and 3.Phas anACTIVElicense inC.location_statewhoseexpires_atis at least24 hoursin the future (a safety cushion so a call starting at11:50 PMacross US time zones never crosses midnight into an expired license).Step 2 — Priority score in "effective wait minutes". Pure first-in-first-out (FIFO) makes urgent fevers wait behind mild rashes, while strict urgency priority causes starvation (routine patients waiting forever during a busy surge). Instead, every waiting consult earns
1 point per minute waited, plus bounded minute bonuses: -+30 minutesforURGENTtriage -+10 minutesfor a scarce state (<= 2physicians currently on shift licensed for that state)URGENT_BONUS_MIN = 30.0 SCARCE_STATE_BONUS_MIN = 10.0 SCARCE_DOCTOR_THRESHOLD = 2 def priority_score(consult, now, doctors_per_state: dict[str, int]) -> float: """Compute effective wait score in minutes; higher score is served first.""" waited_minutes = (now - consult.queue_entered_at).total_seconds() / 60.0 score = waited_minutes if consult.urgency == "URGENT": score += URGENT_BONUS_MIN # Protect small states: if <= 2 on-shift doctors hold this license, prioritize it # before a multi-state doctor gets tied up by a well-staffed state. if doctors_per_state.get(consult.location_state, 0) <= SCARCE_DOCTOR_THRESHOLD: score += SCARCE_STATE_BONUS_MIN return score def score_key(scored_item): return scored_item[0] def rank_eligible_consults(candidates, now, doctors_per_state: dict[str, int]): """Candidates arrive ordered by oldest queue_entered_at; stable sort breaks ties oldest-first.""" scored_pairs = [] for consult in candidates: scored_pairs.append((priority_score(consult, now, doctors_per_state), consult)) scored_pairs.sort(key=score_key, reverse=True) ordered = [] for pair in scored_pairs: ordered.append(pair[1]) return orderedTrace a concrete decision at
10:00for Dr. Nair, licensed in both Florida (24doctors on shift) and Oregon (1doctor on shift—Dr. Nair!):Consult Patient State Urgency Entered Waited Bonuses Effective Score C1 M-101 FL ROUTINE 09:42 18 min +0 18.0 C2 M-104 OR ROUTINE 09:50 10 min +10 (scarce) 20.0 C3 M-209 FL URGENT 09:58 2 min +30 (urgent) 32.0 Ranking: C3 (32.0) -> C2 (20.0) -> C1 (18.0)Notice why
C2(M-104in Oregon) beats the olderC1(M-101in Florida): 23 other doctors can pick upC1seconds later, whereas if Dr. Nair tookC1, nobody left on shift could help the Oregon patient for 15 minutes!Provable anti-starvation bound. Because the maximum bonus is
30 + 10 = 40 minuteswhile real wait time grows1 pointevery minute, no patient can ever be jumped by someone who arrived more than40 minutesafter them. And because totalWAITINGrows at peak are ~170, fetching eligible rows viawaiting_by_stateand sorting in Python takes< 1 msonce every ~3.5 seconds across the whole company.Wait-time range estimation. Every 30 seconds, for each state
S, divide the number of waiting consults inSscoring ahead of consultCby the rate at whichSconsults enteredIN_PROGRESSover the past 30 minutes, then display[0.7x, 1.5x]rounded to 5-minute steps (or"Longer than usual — offer SMS callback"when recent completions are zero).Deep dive 2: Race-free concurrency and reaper timeouts
When two physicians licensed in Florida click "Next Patient" at the exact same millisecond, how do we guarantee zero double-assignments and zero stale-license matches without Redis distributed locks?
Millisecond race trace inside PostgreSQL (Read Committed isolation) t = 0 ms: Consult c-4a8 (FL) has status = 'WAITING'. t = 1 ms: Dr. Brooks's transaction locks Dr. Brooks's physician row, then runs UPDATE consults ... WHERE consult_id='c-4a8' AND status='WAITING'. PostgreSQL acquires a row lock on c-4a8 for Dr. Brooks. t = 2 ms: Dr. Nair's transaction locks Dr. Nair's physician row, then runs UPDATE on the same c-4a8. PostgreSQL pauses Dr. Nair's UPDATE until Dr. Brooks's transaction finishes. t = 4 ms: Dr. Brooks commits! c-4a8 now has status = 'ASSIGNED', physician_id = Dr. Brooks. t = 5 ms: PostgreSQL wakes Dr. Nair, re-evaluates WHERE status = 'WAITING' on the committed row, sees status = 'ASSIGNED', updates 0 rows, and Dr. Nair's loop seamlessly claims M-104 (OR)!Crucially, we lock the
physiciansrow inside the transaction before updatingconsults, and verify the active license directly inside theUPDATEstatement so a license revoked milliseconds earlier cannot slip through:from datetime import timedelta LICENSE_EXPIRY_BUFFER = timedelta(hours=24) def claim_next(db, physician_id: int, now): """Atomically assign the highest-priority eligible waiting consult to physician_id.""" # Fast idempotent check: if a double-click or network retry arrives, return current visit. existing_visit = db.open_consult_for_physician(physician_id) if existing_visit is not None: return existing_visit # Read candidate snapshot outside the write lock to rank quickly in memory. physician_snapshot = db.get_physician(physician_id) if physician_snapshot.status != "AVAILABLE": return None min_license_expiry = now + LICENSE_EXPIRY_BUFFER valid_states = db.licensed_states(physician_id, valid_after=min_license_expiry) if not valid_states: return None candidates = db.waiting_consults(valid_states, physician_snapshot.visit_types) ranked = rank_eligible_consults(candidates, now, db.on_shift_count_per_state()) for candidate in ranked: with db.transaction(): # Lock Order Rule: ALWAYS lock physicians row BEFORE consults row -> zero deadlocks. physician = db.lock_physician_for_update(physician_id) if physician.status != "AVAILABLE": return db.open_consult_for_physician(physician_id) # Re-verify WAITING status, visit_type, AND live ACTIVE license inside the atomic UPDATE! rows_updated = db.execute( """ UPDATE consults c SET status = 'ASSIGNED', physician_id = %s, assigned_at = %s, version = version + 1 WHERE c.consult_id = %s AND c.status = 'WAITING' AND c.visit_type = ANY(%s) AND EXISTS ( SELECT 1 FROM physician_licenses pl WHERE pl.physician_id = %s AND pl.state = c.location_state AND pl.status = 'ACTIVE' AND pl.expires_at > %s ) """, (physician_id, now, candidate.consult_id, physician.visit_types, physician_id, min_license_expiry), ) if rows_updated == 0: # Another physician claimed it, member cancelled/moved, or license just expired. continue db.set_physician_status(physician_id, "IN_VISIT") db.insert_consult_event(candidate.consult_id, "WAITING", "ASSIGNED", "physician", physician_id) db.insert_outbox("consult.assigned", {"consult_id": str(candidate.consult_id)}) return db.get_consult(candidate.consult_id) return NoneTimeout reaper (runs every 30 seconds, locking
physiciansbeforeconsultswithWHERE version = :seen):AVAILABLEphysician with no WebSocket heartbeat for45 s-> flip toOFFLINEso we stop assigning to a closed laptop.ASSIGNEDwithready_at IS NULLand physician heartbeat older than60 s-> return consult toWAITINGkeeping originalqueue_entered_at; mark physicianOFFLINE.ASSIGNEDwithready_at IS NOT NULLfor> 5 min-> if physician heartbeat is fresh, markNO_SHOW(after push + SMS reminders at0and2 min) and free physician; if physician heartbeat is stale, return consult toWAITINGso a member is never blamed for a doctor's Wi-Fi drop.IN_PROGRESSwith physician disconnected> 5 min(or duration> 90 min) -> alert operations rather than auto-reassigning mid-exam, avoiding a second doctor barging into a recovering call.
Deep dive 3: State licensing, patient location, and HIPAA compliance
Continuous license verification (fail-closed). Fail-closed means that whenever license validity is expired, suspended, or uncertain, the system blocks the match rather than taking a legal chance. Credentialing syncs
physician_licensesnightly against state medical board feeds and alerts staff60 daysbefore any license expires. If a board suspends a license mid-shift, anyASSIGNED(not yet started) consult in that state is immediately returned toWAITINGwith its original spot preserved, andPOST /readyre-checks the license one final time before opening the video room.Two-step location verification. At intake the member explicitly selects and attests to
"Where are you physically located right now?"(defaulting to their last visit's state, not billing address). IP geolocation mismatches surface a soft prompt to double-check rather than a hard block because cellular gateways and VPNs frequently mislocate users across state borders. At the start of the call, the physician asks the patient's location and submitsconfirm-location; if the patient actually crossed into another state,release(reason="wrong_state")updateslocation_stateand puts them right back near the front of the new state's eligible pool using their originalqueue_entered_at.HIPAA privacy and audit controls
- Minimum necessary access: Waiting counts show zero patient names or symptoms; intake records unlock only to the single physician currently holding
physician_idon the consult, and every read writes an immutable row inphi_access_log(support "break-glass" lookups require a ticket reason and trigger a security alert). - Layered encryption & clean notifications: TLS 1.3 in transit, KMS disk/backup encryption, plus application-level envelope encryption on free-text
symptoms. Push notifications and SMS texts never mention symptoms or conditions ("Your telehealth doctor is ready — tap to join"), protecting lock-screen privacy. - Tamper-evident audit history: The application database user only has
INSERTandSELECTprivileges onconsult_eventsandphi_access_log(noUPDATEorDELETE), with daily exports to write-once-read-many (WORM) cloud storage.
- Minimum necessary access: Waiting counts show zero patient names or symptoms; intake records unlock only to the single physician currently holding
Scaling, staffing operations, failure handling, and trade-offs
Scaling data and staffing
- 10x traffic headroom: Even
60 writes/secand10,000WebSockets fit one PostgreSQL primary plus 3–4 stateless API/gateway instances; read-heavy ops dashboards query the async read replica, andconsult_events/phi_access_logare partitioned monthly. - Solving night-shift coverage with set multicover: Staffing 20 states at 3 AM with minimal idle cost is a set multicover problem (choosing the smallest team of physicians whose combined state licenses cover every state at least twice so one active call never leaves a state at zero). At 20 states, a simple greedy algorithm or tiny integer linear program builds optimal shift rosters and highlights which extra state licenses the company should sponsor next to merge isolated state pools.
Failure handling
Component failure Impact Automated or operational recovery API or WebSocket node crash Active sockets reconnect Load balancer drains failed node; clients retry idempotent endpoints and pull GET /consults/{id}PostgreSQL primary outage ~30-60s write pause Promote synchronous AZ-2 standby (RPO = 0, meaning zero committed data lost; RTO < 1 min, meaning recovery under a minute) Full cloud region outage Regional downtime Fail over to warm cross-region async replica (RPO seconds, RTO ~15 min); display nurse-line phone fallback Video vendor outage Video rooms fail to open Physician dials callback_phonedirectly and switches consult tomodality = 'phone'SMS/Push provider outage Delayed join alerts Secondary SMS carrier failover; reaper automatically extends 5-minute no-show grace timer Summary of key trade-offs
- Single PostgreSQL source of truth vs. distributed queue brokers: Gives rock-solid partial unique indexes and atomic conditional claims at
< 10 writes/sec, trading away horizontal write sharding we do not need. - Server-ranked pull (
claim-next) vs. physician pick-list: Prevents cherry-picking and double-click races while letting doctors pace charting breaks. - Bounded wait-minute bonuses (
+30urgent,+10scarce state) vs. strict priority: Prioritizes clinical urgency and small states while guaranteeing a40-minutemaximum overtake bound so routine patients never starve. - Fail-closed 24h license buffer & preserved
queue_entered_at: Never risks an unlicensed medical encounter, and never punishes honest patients when a doctor disconnects or a state mismatch is caught.
- 10x traffic headroom: Even
Intuition & how it works
Imagine an airport passport hall where travelers arrive from 20 different states, urgent medical travelers need fast help, and each officer at a counter is legally certified to stamp passports from only a specific subset of states (one officer holds Florida and Georgia stamps; another holds Florida, Oregon, and Ohio stamps). You cannot put travelers into 20 isolated single-file lines without forcing multi-state officers to guess which line to serve next, and you cannot let officers grab paper forms off a shared table without two officers grabbing the same traveler or skipping hard cases. Instead, all waiting travelers sit in one central ledger, and whenever an officer presses "Ready for Next", the desk computer filters down to travelers whose state matches that officer's active certificates, scores them by minutes waited plus small urgency and scarce-state bonuses, and hands over the top traveler in a single atomic database step.
Naive designs fail here in three common ways. First, building 20 isolated per-state FIFO (first-in, first-out) queues wastes multi-state doctors and lets routine patients in small states wait hours behind busy states—or conversely, strict urgency priority causes starvation (routine patients waiting indefinitely whenever urgent arrivals keep coming). Second, checking "is this patient still unassigned?" in application code before writing "assign to Dr. Brooks" creates a classic race condition (two simultaneous requests reading the same old state and overwriting each other), matching two doctors to one sick patient. Third, introducing distributed message brokers like Kafka or Redis lists for < 1 request/second splits state across two systems that can disagree whenever a network call fails.
Trace a concrete example at 10:00 with 3 waiting patients and 2 doctors (Dr. Nair licensed in FL, OR; Dr. Brooks licensed in FL, GA; OR currently has only 1 doctor on shift while FL has 24):
Waiting rows in PostgreSQL at 10:00:
M-101: state = FL, urgency = ROUTINE, waited = 18 min -> score = 18 + 0 + 0 = 18
M-104: state = OR, urgency = ROUTINE, waited = 10 min -> score = 10 + 0 + 10 (scarce OR) = 20
M-209: state = FL, urgency = URGENT, waited = 2 min -> score = 2 + 30 (urgent) + 0 = 32
Suppose Dr. Nair (FL, OR) and Dr. Brooks (FL, GA) both click "Next Patient" at 10:00:00.000:
1. Both rank their eligible patients:
- Dr. Nair's list: [M-209 (32), M-104 (20), M-101 (18)]
- Dr. Brooks's list: [M-209 (32), M-101 (18)] (Dr. Brooks lacks an OR license, so M-104 is excluded)
2. Both run: UPDATE consults SET status='ASSIGNED', physician_id=... WHERE consult_id='M-209' AND status='WAITING'
- Dr. Brooks wins the row lock by 1 ms -> updates 1 row -> Dr. Brooks gets M-209 (FL urgent)!
- Dr. Nair's UPDATE wakes up, sees M-209 is now 'ASSIGNED' -> updates 0 rows -> moves to item #2!
3. Dr. Nair immediately claims M-104 (OR routine, score 20) instead of M-101 (FL routine, score 18),
protecting the scarce Oregon patient that Dr. Brooks could never legally serve!
Key trade-offs
- One PostgreSQL database vs. distributed queue brokers (Kafka or Redis). At ~6 writes per second at peak, a single PostgreSQL primary with a synchronous standby gives ACID transactions, row-level locking, and partial unique indexes (uniqueness constraints enforced on a filtered subset of rows, such as
WHERE status IN ('WAITING', 'ASSIGNED', 'IN_PROGRESS')), making double-assignment impossible in storage. Adding a separate queue broker would introduce dual-write consistency bugs for throughput headroom we do not need, trading away horizontal write sharding in favor of strong correctness. - Server-selected pull (
claim-next) vs. physician pick-list or server push. Having physicians clickclaim-nextlets clinicians control their own pace between charting and breaks without needing a complex "offer-and-expire" push timer, while letting the server pick the patient prevents cherry-picking easy visits and avoids UI click races. - Additive minute bonuses vs. strict FIFO or strict priority. Adding
+30effective minutes for urgent cases and+10minutes for scarce states (<= 2licensed doctors on shift) moves high-priority cases ahead while preserving a hard40-minuteovertake ceiling: once a routine patient has waited 41 minutes longer than a new arrival, the routine patient's score is strictly higher, mathematically preventing starvation. - Preserving
queue_entered_aton release vs. sending to the back of the line. Keeping a patient's original arrival timestamp when a doctor disconnects or discovers a wrong state on the call is fair to patients who did nothing wrong, at the minor cost of auditing repeated manual state changes for abuse. - Fail-closed licensing vs. maximizing doctor utilization. Fail-closed means blocking a match whenever a license is expired, suspended, or within 24 hours of expiring—even if a state renewal is likely sitting in paperwork. In healthcare, a longer wait is vastly preferable to practicing medicine across state lines without an active license.
- Wait-time ranges vs. exact line positions. Showing
"10–20 minutes"instead of"You are #4 in line"feels slightly vaguer, but avoids the frustration of watching a position number move backward when an urgent case arrives or a single-state doctor claims someone behind you. - Transactional outbox vs. inline third-party API calls. A transactional outbox writes pending SMS, push, and video-room tasks into a database table inside the same commit as the consult status change, then relays them asynchronously. That adds a lightweight background worker, but guarantees notifications never fire for rolled-back transactions and never vanish if a server crashes right after commit.
Common mistakes
- Matching against the member's home billing address instead of where the patient is physically located during the video visit, which violates US state medical-licensing rules whenever members travel or attend college out of state.
- Checking licenses only at shift login or outside the database transaction, allowing a license that expires or gets suspended mid-shift to still claim patients.
- Enforcing "one doctor per consult" with an application read-then-write (
SELECTfollowed byUPDATEwithoutWHERE status = 'WAITING') or an unfenced Redis lock, both of which allow duplicate assignments under concurrent clicks or garbage-collection pauses. - Overloading one timestamp for both "doctor paged patient" and "call connected", which marks no-show visits as started encounters and makes it impossible to avoid blaming a patient as
NO_SHOWwhen the doctor's own connection dropped. - Putting PHI in SMS or lock-screen push notifications (PHI, or Protected Health Information, is any identifiable health detail protected under HIPAA law—for example writing
"Your behavioral health visit is ready"instead of a neutral"Your doctor is ready — open the app"). - Skipping upfront emergency triage, letting a patient reporting stroke or chest-pain symptoms sit quietly in a virtual waiting room instead of immediately directing them to
911. - Over-engineering infrastructure for imaginary traffic—spending interview time sharding databases for
0.3 requests/secondwhile ignoring the actual bottleneck: night-shift coverage in small states.
Follow-up questions
- How would you integrate pre-booked scheduled visits into the same clinician pool without starving or delaying on-demand patients? Add an
appointmentstable storingphysician_id,patient_id,location_state, andscheduled_at, validating at booking time that the physician's license in that state expires well after the appointment date. During shifts,claim-nextsuppresses on-demand matches for any physician who has a scheduled appointment starting within the next15 minutes(one average consult duration), preventing on-demand calls from making the doctor late while other available physicians continue serving the live queue. Exactly 15 minutes beforescheduled_at, a scheduler promotes the appointment into aconsultsrow assigned to that physician, reusing the exact same location confirmation, video room, BAA (Business Associate Agreement) vendor flow, and HIPAA audit tables. - Suppose at 3 AM the last on-shift clinician holding a sparsely populated state's license disconnects—how should the platform handle active and incoming patients there? Within 45 seconds of missed WebSocket heartbeats, the timeout reaper marks that physician
OFFLINE, returns any unstartedASSIGNEDconsult toWAITINGwith its originalqueue_entered_at, and the 10-second coverage job sees0on-shift doctors for that state and pages operations plus on-call physicians holding that license. UnlikeSTATE_NOT_SERVED(used when the company employs nobody licensed in a state), new and currently waiting patients in that state are immediately shown an honest"Longer than usual — waiting for a state-licensed physician"banner with three clear choices: request an automated SMS callback the moment a licensed doctor signs on, speak to the 24/7 triage nurse line, or visit in-person urgent care if symptoms worsen. - What changes if clinicians can conduct up to four asynchronous text-based consultations simultaneously instead of one live video visit? Replace the strict single-visit partial unique index with a
max_concurrent_chatscolumn onphysicians(for example4for chat,1for video) enforced insideclaim_next: becauseclaim_nextalready locks thephysiciansrow withSELECT ... FOR UPDATE, counting that physician's currently open chat consults inside the same transaction is completely race-free. Asynchronous chats also use longer inactivity timers (for example, 30 minutes to reply before pausing or closing) and calculate wait estimates from concurrent chat completion rates rather than 15-minute video slots, while keeping every state-license check and PHI access-logging rule identical.
Follow-up questions
- How would you integrate pre-booked scheduled visits into the same clinician pool without starving or delaying on-demand patients?
- Suppose at 3 AM the last on-shift clinician holding a sparsely populated state's license disconnects—how should the platform handle active and incoming patients there?
- What changes if clinicians can conduct up to four asynchronous text-based consultations simultaneously instead of one live video visit?
Similar questions
- Automated Patient Outreach Sequence Service
- Identify Clients Missing Nearby Specialty Care
- Morse Code Translation and Provider Proximity
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform