Licensed-Clinician Matching Queue for a Virtual Care Service
System DesignModel answerLast updated
Design a 24/7 virtual-care intake system that routes waiting patients to clinicians licensed in the patient's current state, with safe concurrent claiming, auditing and compliance.
A health insurer offers its members free, around-the-clock virtual doctor visits through a website and a mobile app. Members live across many U.S. states. The insurer employs physicians who each hold medical licenses in only some states, and a physician may treat a patient only if licensed in the state where that patient currently is.
Design the backend that lets members ask for a virtual visit and lets physicians pick up those requests promptly, safely and in compliance with regulations.
Your answer should cover:
- Functional and non-functional requirements, plus a rough scale estimate
- Public APIs for members and physicians
- Data model and the lifecycle of a consultation request
- Queueing and matching logic, including fairness when some states have few licensed physicians
- Concurrency control (two physicians claiming at once, a patient cancelling during a claim, double clicks, client retries)
- Scalability, reliability and failure handling
- Security, privacy and audit needs, and operational monitoring
State your assumptions explicitly, and explain which pieces you would deliberately keep simple.
Hints
Hint 1
Start with the scale estimate. Work out requests per second before choosing technology; the answer should shape how heavy your queue infrastructure needs to be.
Hint 2
Think about which location governs licensing (where the patient is right now) and where the license check must be enforced so that a stale UI list can never cause a violation.
Hint 3
Let physicians ask the server for the next eligible patient instead of browsing. Consider a row-level locking approach that lets simultaneous claimers receive different rows without blocking, plus database constraints and idempotency keys for the remaining races.
Hint 4
Plain first-come-first-served can starve states with few licensed physicians. Consider a scarcity-aware ranking with a hard wait-time override, and think about what happens when a physician claims a patient and then disappears.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The load is small; the difficulty is correctness. The guarantees that matter are: no patient is treated by an unlicensed physician, no patient is claimed twice, no request is silently lost, and every action is auditable. I would say this up front and size the system accordingly.
Requirements
Functional
- A member submits a request with their current physical state (licensure follows location, not home address), reason for visit and callback preference. Red-flag symptoms are screened first and redirected to emergency services before queuing.
- The member sees position and estimated wait, can cancel, and is notified when a physician is ready.
- A physician sets availability (available, break, off), sees counts of eligible waiting patients, claims the next patient, then starts, completes or releases the visit.
- Ops can manage licenses (effective and expiry dates), view per-state waits and reassign stuck consults.
Non-functional
- License enforcement is server-side at claim time.
- A consult has at most one active physician; a physician has at most one active consult (configurable).
- 99.95% availability on the queue path, claim latency under about 300 ms, status updates to members within about 2 s.
- PHI encrypted in transit and at rest, full audit trail, and a business associate agreement with every vendor touching PHI (video, SMS).
Scale estimate
Assume 5M members, 1% use the service monthly, about 1.3 visits each: roughly 65k consults per month, around 2k per day. With a 5x peak that is about 1 request/s, and about 10/s even with 10x growth. There are a few hundred physicians on shift and about 1k members waiting with open connections. One well-run Postgres primary with a synchronous standby in another zone handles this comfortably. Sharded per-state streaming queues would add failure modes without solving a real problem, so I would not use them as the core store.
API
POST /consults {state, reason, symptoms[], callback} -> {id, position, etaMin}
GET /consults/{id} -> status, eta, physician when assigned
POST /consults/{id}/cancel
WS /consults/{id}/events (fallback: push/SMS)
POST /physicians/me/shift {status}
GET /physicians/me/queue-summary
POST /physicians/me/claim-next -> consult | 204 if none
POST /consults/{id}/start | complete | release
All mutating calls take an idempotency key, since mobile clients retry. Physicians use claim-next rather than choosing from a list; this prevents cherry-picking and keeps fairness on the server.
Data model (Postgres)
physician,license(physician_id, state, valid_from, valid_to, status)synced from the credentialing system,physician_session(status, last_heartbeat)consult(id, member_id, patient_state, priority, status, enqueued_at, assigned_physician_id, assigned_at, lease_expires_at, version)consult_eventas an append-only audit log, written in the same transaction as every transitionoutboxfor reliable event publishing
Key indexes:
- Partial index on
(patient_state, priority, enqueued_at) WHERE status='WAITING'for fast queue reads. - Unique partial index on
assigned_physician_id WHERE status IN ('ASSIGNED','IN_PROGRESS'), enforcing one active consult per physician in the database itself.
State machine: REQUESTED → WAITING → ASSIGNED → IN_PROGRESS → COMPLETED, with CANCELLED/EXPIRED from waiting, ASSIGNED → WAITING on release or lease timeout, and ABANDONED from in progress. Every transition is a conditional update (WHERE status = expected).
Architecture
- API gateway (auth, rate limiting, WAF) in front of a stateless, horizontally scaled Consult Service that owns all transitions.
- Postgres as the single source of truth.
- Outbox relay publishing to an event bus; consumers are notifications (WebSocket, push, SMS), the video service (room creation with a compliant vendor) and analytics/EHR integration.
- A sweeper job for expired claim leases, stale heartbeats and abandoned waits.
- Redis only for cached per-state counts and ETAs for cheap polling, never as the source of truth.
Matching and concurrency
claim-next runs in one transaction: select the best WAITING consult whose patient_state is in the physician's currently valid licenses, using FOR UPDATE SKIP LOCKED, then update it to ASSIGNED with a short lease (for example 2 minutes) guarded by WHERE status='WAITING'.
Why this is correct:
SKIP LOCKEDgives two simultaneous claimers different rows and they never block each other.- The license check is in the same transaction as the assignment, so a license that expired a minute ago cannot slip through. The UI list is a convenience only.
- A double click hits the unique partial index and fails cleanly; the idempotency key returns the original result.
- Cancel versus claim is settled by the status guard: exactly one wins, and the loser gets a clear response.
Fairness and scarcity. Pure FIFO across a physician's states can starve rare ones. If Dr. A is licensed in a crowded state and a scarce one, she should prefer the scarce-state patient. Rank by wait_time × priority_weight × scarcity_boost(state), where the boost grows as available licensed physicians per waiting patient falls. Add a hard override: anyone waiting beyond an SLA threshold (say 30 minutes) goes first among that physician's eligible patients, and alert ops if a state has waiting patients but zero licensed physicians on shift.
Reliability and failure handling
- Physician disappears after claiming: the lease expires without a start call, and the sweeper returns the consult to
WAITING, keeping its original enqueue time so the patient does not lose their place. - Patient disconnects: keep the request for a grace period using heartbeats, then expire it and notify by SMS.
- Mid-visit failures: mark
ABANDONEDand re-queue at elevated priority with a callback. - Database failover: synchronous replica, automatic promotion, and idempotent retries make the cutover safe. The outbox gives at-least-once event delivery; consumers dedupe by event id.
- Degraded mode: if Redis or the bus is down, the queue still works on Postgres; only cached ETAs and push latency suffer.
Security and compliance
- Encrypt PHI (field-level for sensitive columns), least-privilege access, short-lived tokens and MFA for physicians.
- Audit every read and write of PHI via the event log; make it immutable and retained per policy.
- Keep PHI out of push and SMS payloads (send "your doctor is ready", not details), and out of logs.
- License data is synced frequently from the credentialing system, and revocations take effect on the next claim because the check is transactional.
Operations
Track: p95 wait per state, count of waiting patients with no eligible physician, claim latency and conflict rate, lease expirations, abandonment rate and outbox lag. Alert on SLA breaches and scarcity. Run load tests at 10x peak and failover drills.
Common mistakes
- Using the patient's home state instead of current location.
- Checking licensure only in the UI or at enqueue time.
- Letting physicians browse and pick patients, which breaks fairness and creates races.
- Relying on in-memory or cache state for assignment.
- Over-engineering with per-state sharded streams for about 10 writes per second.
- Forgetting leases and sweepers, so a crashed client strands a patient.
- Putting PHI in notifications or logs.
Possible extensions
Multi-concurrent visits per physician, scheduled appointments, language or specialty matching, and multi-region deployment with state-aware data residency.