Healthcare Appointment Scheduling Architecture Under Flash-Crowd Traffic
Medium · System Design · Software Engineer · Technical Screen
Prompt
Design an online healthcare scheduling system that lets patients search for clinicians, inspect open calendar windows, book visits, and cancel existing reservations, while clinicians and authorized clinic staff configure working hours and unavailability blocks.
The platform must strictly prevent two patients from confirming the same appointment window. Once the everyday scheduling architecture is in place, extend your design to survive a scheduled public immunization launch where demand surges dramatically over a tiny, fixed supply of appointment slots within minutes.
Clarify your upfront engineering assumptions before diving into components: - Fixed-duration slots, arbitrary time intervals, recurring weekly templates, or a unified model - Multi-resource appointments requiring a clinician alongside shared clinic assets (such as an exam room or imaging equipment) - Acceptable staleness on calendar search reads versus strict confirmation guarantees on booking writes - Supporting workflows in or out of scope (waitlists, rescheduling, eligibility screening, reminders, payments) - Traffic multiplier and geographic concentration assumed during the immunization surge
Scope & Expectations
- Calendar Modeling & Conflict-Free Writes: Client/staff APIs, interval and schedule schemas, and database concurrency controls that prevent double-booking across single or multiple clinic resources.
- Read-Heavy Availability Caching: Serving low-latency provider searches and calendar views from cache without ever letting stale cache entries cause double bookings.
- Flash-Crowd Admission & Hot-Slot Contention: Fair virtual queuing, edge polling offload, contention-free slot claiming, load shedding, and bulkhead isolation so immunization spikes do not degrade everyday patient care.
- Race Conditions & Failure Recovery: Cleanly resolving concurrent holds, hold expirations, cancel-vs-book races, and cache or node failures.
Step-by-step walkthrough
Clarify requirements and the two operating modes
This problem combines two very different engineering challenges: a strict everyday reservation engine where two patients must never be double-booked onto the same clinician or room, and a 15x sudden-demand event (the vaccine launch) where millions of people compete for a fixed pool of seats at an announced minute.
Functional requirements
- Search and availability: Patients filter clinicians by specialty, location, insurance, and language, and view open appointment slots.
- Book, cancel, and reschedule: Patients place a short temporary hold while entering visit details, confirm the booking, cancel, or reschedule.
- Schedule management: Clinicians and staff configure recurring weekly hours and add one-off blocked intervals (vacations, meetings, emergencies).
- Multi-resource visits: Some visit types require both a specific clinician and a shared clinic resource (such as any open exam room or an MRI machine).
- Sudden vaccine demand: Support a scheduled regional vaccine release where demand exceeds supply by 10x–20x without starving regular sick visits.
Non-functional requirements
- Zero double bookings: Strongly consistent writes—once a patient receives
"CONFIRMED", that resource slice cannot be double-booked under retries, races, or cache lag. - Stale reads are fine; stale writes are forbidden: Search availability may lag by 1–3 seconds, but booking always checks the primary source of truth.
- Latency: Search p99
< 300 msand booking p99< 1 son normal days. - Fairness and survival under spikes: No bot advantage at launch time, graceful throttling, and strict isolation so everyday primary-care bookings keep working during the vaccine rush.
Explicit scope and modeling commitments
- Fixed slots, arbitrary ranges, or recurring templates? All three unified under one model: clinicians define recurring weekly templates (for example Mon–Fri 09:00–17:00 on a 15-minute grid), visit types define durations (15, 30, or 60 minutes), and every active hold, booking, or staff block is stored internally as a concrete
[start, end)time range. - Multiple resources? Yes—each visit type declares its required resource list (for example
clinician + 1 exam_room). - Supporting workflows? Waitlists, atomic rescheduling, basic age/tier immunization eligibility checks, and async SMS/email reminders are in scope; insurance claims processing and co-pay charging are out of scope.
- Flash-crowd traffic shape? Regional state-level immunization launch announced in advance (
200,000seats across250clinics,3,000,000eligible residents).
Back-of-the-envelope numbers
Normal everyday traffic Resources 100,000 clinicians + ~30,000 rooms across 10,000 clinics Daily slots offered ~20 slots/clinician/day -> ~2M slots/day (~120M over 60 days) Bookings ~1M/day -> ~12 writes/s average, ~60 writes/s Monday peak Searches & calendar views ~20 searches/booking -> ~1,200 searches/s & ~3,600 calendar views/s peak Availability bitmap cache 130,000 resources * 60 UTC days = 7.8M keys Each day = 288 five-minute bits (36 B); ~140 B/key incl. Redis overhead -> 7.8M * 140 B = ~1.1 GB total RAM Durable DB growth ~1 KB/booking incl. audit rows -> ~1 GB/day (~365 GB/year) Regional vaccine launch spike Supply (fixed!) 200,000 seats (250 clinics * 5 days * 160 doses/day) Demand 3,000,000 eligible people (500k waiting pre-open, 1M in first 5 min) Waiting-room status polls 1,500,000 browsers polling every 10 s = 150,000 GET req/s -> collapsed via 2-second CDN edge cache to < 5 origin req/s! Controlled admission rate 1,000 users/s admitted into booking (~25% drop-off -> sells out in ~4.5 min) Peak DB write load ~1,000 seat holds/s + ~750 confirmations/s (short single-row updates)Why these numbers shape the architecture:
- Everyday write load (
~60/s) fits comfortably on a single PostgreSQL primary, while everyday read load (~3,600/s) belongs in a ~1.1 GB Redis availability cache. - Scaling the database to 150,000 writes/second for the vaccine drop would be pure waste. There are only
200,000doses; letting all 3 million requests hit PostgreSQL would just burn massive compute to hand out 2.8 million"Sold Out"errors. Instead, a virtual waiting room absorbs the crowd at the CDN edge for pennies and meters users into the booking service at1,000/s.
- Everyday write load (
API design
Every state-changing endpoint requires an
Idempotency-Key—a client-generated UUID saved alongside the first committed response so network retries or double-taps replay the original receipt instead of creating duplicate holds.Everyday patient and staff APIs
GET /v1/providers?specialty=cardiology&near=37.78,-122.41&radius_km=10&insurance=horizon_ppo -> 200 [ { "provider_id": "prv_4", "clinic_id": "cln_6", "next_available": "2026-12-08T10:00Z" } ] GET /v1/providers/{provider_id}/availability?from=2026-12-07&to=2026-12-13&visit_type=vt_new -> 200 { "slots": [ { "start": "2026-12-08T10:00Z", "end": "2026-12-08T10:30Z" } ], "as_of": "..." } POST /v1/holds Header: Idempotency-Key: <uuid> Body: { "patient_id": "pat_8", "provider_id": "prv_4", "visit_type": "vt_new", "start": "2026-12-08T10:00Z" } -> 201 { "appointment_id": "apt_52", "status": "HELD", "expires_at": "2026-12-08T09:05Z" } -> 409 SLOT_TAKEN { "alternatives": [ ...3 nearest open slots... ] } POST /v1/appointments/{appointment_id}/confirm Header: Idempotency-Key: <uuid> Body: { "reason_for_visit": "Routine consult", "insurance_member_id": "..." } -> 200 { "status": "CONFIRMED" } | 410 HOLD_EXPIRED POST /v1/appointments/{appointment_id}/cancel Header: Idempotency-Key: <uuid> POST /v1/appointments/{appointment_id}/reschedule Body: { "new_appointment_id": "apt_61" } PUT /v1/providers/{provider_id}/schedule (recurring weekly hours) POST /v1/resources/{resource_id}/blocks Body: { "start": "...", "end": "...", "reason": "..." } -> 201 Created | 409 CONFLICTS_WITH_BOOKINGS (lists affected appointments for staff to move)Vaccine event APIs
POST /v1/events/{event_id}/queue -> 200 { "queue_token": "...", "position": 18450 } GET /v1/events/{event_id}/queue/status -> 200 { "now_serving": 11000, "sold_out": false, "admit_per_s": 1000 } (CDN-cached 2 s!) POST /v1/events/{event_id}/queue/enter Body: { "queue_token": "..." } -> 200 { "session_token": "...", "expires_at": "..." } POST /v1/events/{event_id}/holds Header: Authorization: Bearer <session_token> Body: { "clinic_id": "cln_6", "day": "2026-12-15" } -> 201 { "seat_id": "st_715", "window_start": "2026-12-15T10:20Z", "expires_at": "..." } -> 409 DAY_FULLThree deliberate API choices prevent classic bugs:
- Hold (
5 min), then confirm: Patients do not lose a slot on the final button click after spending 3 minutes typing insurance details, while abandoned forms auto-expire. - Cancel by
appointment_id, never by(provider_id, time): If Patient A cancels 10:00 AM, Patient B books 10:00 AM, and Patient A's phone retries its timed-out cancel request, targetingapt_52sees"already CANCELLED"and never touches Patient B'sapt_64. - Vaccine holds request
(clinic_id, day), not10:00 AM: Letting the server assign the next open window on that day eliminates 10,000 people fighting over the single 10:00 AM row.
- Hold (
Data model and database-enforced overlap protection
Every time range is stored as a half-open interval
[start, end)—meaningstartis included andendis excluded—so back-to-back appointments[10:00, 10:30)and[10:30, 11:00)touch cleanly with zero overlap:Timeline for resource res_dr_chen: 10:00 10:30 11:00 11:30 [--- apt_1 ----)[--- apt_2 ----) [--- vacation block ---) [--- apt_3 ----) <-- REJECTED by database GiST exclusion constraint!Instead of relying on application
ifchecks, we enforce non-overlap directly inside PostgreSQL using a GiST (Generalized Search Tree) exclusion constraint—a database index rule that guarantees no two active rows with the sameresource_idcan ever have overlappingtstzrangeintervals:CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE reservations ( reservation_id UUID PRIMARY KEY, resource_id TEXT NOT NULL, -- clinician, room, or equipment ID during TSTZRANGE NOT NULL, -- half-open [start_utc, end_utc) kind TEXT NOT NULL, -- 'APPOINTMENT' | 'BLOCK' appointment_id UUID NULL, status TEXT NOT NULL, -- 'HELD' | 'CONFIRMED' | 'CANCELLED' | 'EXPIRED' hold_expires_at TIMESTAMPTZ NULL, CONSTRAINT no_double_booking EXCLUDE USING gist (resource_id WITH =, during WITH &&) WHERE (status IN ('HELD', 'CONFIRMED')) );Supporting tables in PostgreSQL:
resources resource_id PK, clinic_id, kind (CLINICIAN | ROOM | EQUIPMENT), subtype ('exam_room') visit_types visit_type_id PK, provider_id, duration_min, required_subtypes[] (e.g. ['exam_room']) schedule_rules resource_id, weekday, start_local, end_local, slot_grid_min, clinic_tz appointments appointment_id PK, patient_id, provider_id, clinic_id, during tstzrange, status, hold_expires_at, version, created_at idempotency_keys (account_id, idem_key) PK, request_hash, response_json, created_at outbox event_id PK, topic, partition_key, payload_json, created_at, published_at vaccine_seats seat_id PK, event_id, clinic_id, day DATE, window_start TIMESTAMPTZ, status (OPEN | HELD | CONFIRMED), patient_id NULL, hold_expires_at NULL INDEX (event_id, clinic_id, day, status, window_start) UNIQUE (event_id, patient_id) WHERE status IN ('HELD', 'CONFIRMED')Why unify appointments and staff blocks in
reservations? Because placingkind = 'BLOCK'into the exact same table means the singleno_double_bookingconstraint automatically stops patients from booking during a doctor's lunch break and stops staff from accidentally blocking over an existing confirmed patient.High-level architecture
To ensure a vaccine spike never breaks everyday care, we isolate the two workloads into separate bulkheads—independent server deployments and database connection pools, named after watertight ship compartments so a flood in one compartment cannot sink the whole vessel:
[Patients & Browsers] [Clinic Staff] | | v v [CDN Edge] (static UI, waiting-room HTML, 2s cached /queue/status & clinic seat counts) | [API Gateway] (JWT auth, per-account/IP rate limits, priority load shedding) / | \ v v v [Search Service] [Regular Booking Pool] [Vaccine Spike Pool] (read-only) (dedicated DB conn pool) (Waiting-Room + Vaccine Hold API) | \ / | v v v v [Search Index + +------------------------------------+ [Waiting-Room Redis] Redis Bitmaps] | PostgreSQL Primary --sync--> Stby | (atomic queue counter, (~1.1 GB RAM) | (reservations, seats, outbox) | now_serving, session set) ^ +------------------------------------+ | | | rebuild resource-day bitmap | transactional outbox relay -> Kafka +--- [Availability Builder] <------+---> [Notification & Reconciliation Workers]Deep dive 1: Atomic booking, multi-resource rooms, and race conditions
PostgreSQL index predicates cannot call
now()directly becausenow()changes every millisecond. That means an abandoned'HELD'row pasthold_expires_atstill blocksno_double_bookinguntil itsstatusflips to'EXPIRED'. Rather than waiting for a slow background cron job,POST /v1/holdslazily expires any stale conflicting holds right inside the booking transaction!To prevent deadlocks when two transactions touch
appointmentsandreservationsconcurrently, every write path follows one global lock order: lockappointments(ordered byappointment_id) first, thenreservations(ordered byresource_id). And when trying candidate exam rooms ("any free exam room in Clinic 9"), each room attempt wraps in aSAVEPOINT—a lightweight checkpoint inside a SQL transaction that lets us roll back a single failed roomINSERTwithout aborting the whole transaction:BEGIN; -- 1. Idempotency guard: if key already exists, roll back and return stored response_json. INSERT INTO idempotency_keys (account_id, idem_key, request_hash) VALUES (:acct, :key, :hash) ON CONFLICT DO NOTHING; -- 2. Lazy-expire stale holds on the clinician, candidate rooms, or this patient. -- FOR UPDATE SKIP LOCKED + ORDER BY appointment_id prevents deadlocks between racers. WITH stale_appts AS ( SELECT a.appointment_id FROM appointments a WHERE a.status = 'HELD' AND a.hold_expires_at < now() AND (a.patient_id = :patient OR EXISTS (SELECT 1 FROM reservations r WHERE r.appointment_id = a.appointment_id AND r.resource_id = ANY(:clinician_and_candidate_rooms) AND r.during && :range)) ORDER BY a.appointment_id FOR UPDATE SKIP LOCKED ), flip_appts AS ( UPDATE appointments SET status = 'EXPIRED' WHERE appointment_id IN (SELECT appointment_id FROM stale_appts) AND status = 'HELD' AND hold_expires_at < now() RETURNING appointment_id ) UPDATE reservations SET status = 'EXPIRED' WHERE appointment_id IN (SELECT appointment_id FROM flip_appts) AND status = 'HELD'; -- 3. Create the HELD appointment record. INSERT INTO appointments (appointment_id, patient_id, provider_id, clinic_id, during, status, hold_expires_at, version) VALUES (:appt, :patient, :provider, :clinic, :range, 'HELD', now() + interval '5 minutes', 1); -- 4. Lock clinician first (always before rooms so two visits never deadlock in a cycle). INSERT INTO reservations (reservation_id, resource_id, during, kind, appointment_id, status, hold_expires_at) VALUES (gen_random_uuid(), :clinician_id, :range, 'APPOINTMENT', :appt, 'HELD', now() + interval '5 minutes'); -- On SQLSTATE 23P01 (exclusion_violation) -> ROLLBACK and return 409 SLOT_TAKEN + alternatives. -- 5. Pick one free exam room using SAVEPOINT so a room tie does not abort step 4. SAVEPOINT try_room; INSERT INTO reservations (reservation_id, resource_id, during, kind, appointment_id, status, hold_expires_at) VALUES (gen_random_uuid(), :candidate_room_id, :range, 'APPOINTMENT', :appt, 'HELD', now() + interval '5 minutes'); -- If 23P01 -> ROLLBACK TO SAVEPOINT try_room and loop next candidate room; if none left -> ROLLBACK, 409. -- 6. Record outbox event + idempotency response atomically in the same commit. INSERT INTO outbox (event_id, topic, partition_key, payload_json) VALUES (...); UPDATE idempotency_keys SET response_json = :resp WHERE account_id = :acct AND idem_key = :key; COMMIT;How every race resolves cleanly:
- Two patients click 09:00 AM at the same microsecond: Both reach step 4; PostgreSQL's GiST index blocks the second transaction until the first commits, then immediately fails the second with
23P01(409 SLOT_TAKEN). - Confirm vs. expiry at the 5-minute mark:
ConfirmrunsUPDATE appointments SET status = 'CONFIRMED', hold_expires_at = NULL WHERE appointment_id = :appt AND status = 'HELD' AND hold_expires_at > now(), followed by updatingreservations. Because bothConfirmand lazy expiry lock theappointmentsrow first and re-evaluateWHERE status = 'HELD', strictly one wins. - Cancel racing a new booking:
Cancellocksappointmentsthen marksappointmentsandreservations'CANCELLED'. A racingHoldarriving mid-cancel waits on the active reservation's GiST lock and succeeds right afterCancelcommits (unless a waitlist patient exists—in which caseCancelatomically inserts a 30-minute'HELD'reservation for the top waitlisted patient in the same transaction so nobody snipes the slot!).
- Two patients click 09:00 AM at the same microsecond: Both reach step 4; PostgreSQL's GiST index blocks the second transaction until the first commits, then immediately fails the second with
Deep dive 2: Fast search with event-driven availability bitmaps
To serve
3,600calendar views/second without touching PostgreSQL, Redis stores one36-byte bitmap (288bits =288five-minute slices of a1,440-minute UTC day; storing by UTC day avoids 23-hour and 25-hour Daylight Saving Time bugs!) per(resource_id, utc_date):5-min slices starting 10:00 UTC (1 = free, 0 = busy): Clinician prv_4: 1 1 1 1 1 1 0 0 0 0 0 0 (free 10:00-10:30, busy 10:30-11:00) Exam Room room_1: 1 1 1 0 0 0 1 1 1 1 1 1 (free 10:00-10:15 only) Exam Room room_2: 0 0 0 1 1 1 1 1 1 1 1 1 (free 10:15-10:30 only) Exam Room room_3: 1 1 1 1 1 1 0 0 0 0 0 0 (free full 10:00-10:30!) Check 30-min visit (6 contiguous bits): (prv_4 & room_1) -> only 3 bits (NOT enough!) (prv_4 & room_2) -> only 3 bits (NOT enough!) (prv_4 & room_3) -> 6 contiguous bits at 10:00 -> SHOW 10:00-10:30!Notice the critical trap that diagram prevents: if we merged
room_1 | room_2into a single clinic-wide bitmap first, bits 0–2 fromroom_1plus bits 3–5 fromroom_2would falsely claim a room is free from 10:00–10:30, forcing the patient to switch exam rooms mid-appointment! Keeping one 36-byte bitmap per individual room avoids that bug while still taking nanoseconds of bitwiseANDoperations.Keeping bitmaps fresh without dual-write bugs: Every committed booking, cancel, or block writes a row to
outboxinside the same PostgreSQL transaction (transactional outbox pattern, which guarantees we never commit a database change while dropping its Kafka message). An outbox relay publishes(resource_id, utc_date)to Kafka; the Availability Builder re-queries that resource's day from the primary (~20rows) and updatesavail:<resource_id>:<utc_date>in Redis if its monotonic version is newer (< 2 slag). Even if Redis lags, stale cache data never causes a double booking becausePOST /v1/holdschecks PostgreSQL'sno_double_bookingconstraint, not Redis.Deep dive 3: Fair virtual waiting room for the vaccine spike
When 500,000 people gather before the
09:00:00vaccine release, a naive "first HTTP packet wins" race rewards bots and low-ping fiber connections while melting login servers. Instead, our waiting room enforces pre-open lottery + post-open FIFO:- Pre-open lottery (
< 09:00:00): Verified accounts (one entry per verified phone/patient, deduplicated across browser tabs) join a waiting pool. At09:00:00, a worker shuffles those early joiners using a reproducible cryptographic seed (logged for public audit) into positions1..N. Arriving 20 minutes early and arriving 5 seconds early give the exact same random odds. - Post-open FIFO (
>= 09:00:00): Anyone joining after09:00:00getsN + INCR(late_counter)behind the pre-open pool. - Stateless HMAC queue tokens: The server returns
positionwrapped in an HMAC (Hash-based Message Authentication Code)—a tamper-proof cryptographic signature computed over(event_id, account_id, position, issued_at)using a server secret—so validating a user's place later requires zero database reads. - CDN-collapsed polling: All 1.5 million waiting browsers poll
GET /v1/events/{id}/queue/status, which has no user parameters and returns{ "now_serving": 42000, "sold_out": false, "admit_per_s": 1000 }. Caching that 80-byte JSON at the CDN edge withCache-Control: public, max-age=2turns150,000requests/second into< 5origin hits/second! - Closed-loop admission controller: Every second, a controller advances
now_servingbased on live PostgreSQL commit latency (p99 < 150 ms-> step up;p99 > 250 ms-> back off), active 10-minutesession_tokencount, and remaining seats. Onceposition <= now_serving, the client exchanges itsqueue_tokenfor one short-livedsession_tokenrequired by the vaccine hold API.
- Pre-open lottery (
Deep dive 4: Hot-slot partitioning (`SKIP LOCKED`), load shedding, and reconciliation
Even among the
1,000admitted users/second, almost everyone clicks the nearest downtown clinic on Day 1. Look at what happens under a naive counter row vs. pre-generated seat rows:Naive single-row counter (capacity_left = 160): Req 1 -> [LOCK clinic_9_day_1] --update--> commit Req 2 -> ........ waits on lock ........ -> [LOCK] --update--> commit Req 500 -> ...................... times out waiting in single-file line! Pre-generated vaccine_seats + FOR UPDATE SKIP LOCKED: Req 1 -> checks seat_1 (unlocked!) -> locks seat_1 & claims 09:00 immediately! Req 2 -> sees seat_1 locked -> SKIPS IT -> locks seat_2 & claims 09:00 immediately! Req 3 -> skips seat_1, seat_2 -> locks seat_3 & claims 09:05 immediately!FOR UPDATE SKIP LOCKEDtells PostgreSQL's index scan to step right past any row currently locked by another transaction and grab the next available seat with zero blocking:BEGIN; -- Clear this patient's own expired hold (if any) so UNIQUE(event_id, patient_id) stays satisfied. UPDATE vaccine_seats SET status = 'OPEN', patient_id = NULL, hold_expires_at = NULL WHERE event_id = :event AND patient_id = :patient AND status = 'HELD' AND hold_expires_at < now(); -- Atomically claim the earliest unlocked open (or expired-hold) seat on the chosen clinic + day. UPDATE vaccine_seats SET status = 'HELD', patient_id = :patient, hold_expires_at = now() + interval '3 minutes' WHERE seat_id = ( SELECT seat_id FROM vaccine_seats WHERE event_id = :event AND clinic_id = :clinic AND day = :day AND (status = 'OPEN' OR (status = 'HELD' AND hold_expires_at < now())) ORDER BY window_start LIMIT 1 FOR UPDATE SKIP LOCKED ) RETURNING seat_id, window_start; COMMIT;Throttling, load shedding, and autoscaling
- Pre-scaling vs. reactive autoscaling: Because container autoscaling lags by 1–3 minutes while database vertical scaling cannot happen mid-spike, we pre-warm stateless pods 30 minutes before
opens_atand rely on the admission controller as our millisecond shock absorber. - Priority load shedding (when approaching capacity, drop lowest-value work first with
503 Retry-After+ jittered client backoff):- Keep Confirmations alive first (dropping a confirm wastes an already-held seat and frustrates a user at step 2);
- Keep Cancellations second (they return inventory to the pool);
- Shed New Holds third;
- Shed Browse / Availability refreshes first.
Failure recovery and reconciliation
- Primary DB crash: Synchronous standby promotes with zero lost
'CONFIRMED'rows; during the ~10–20 second failover pause, the admission controller sees error rates spike and freezesnow_servingautomatically. - Waiting-room Redis crash: Users keep their places because
queue_tokens are HMAC-signed!now_servingandlate_countercheckpoint to PostgreSQL every second, so a replacement Redis resumes safely fromsaved_counter + 5000while the partial unique index(event_id, patient_id)prevents any double seat claim. - Continuous reconciliation jobs: Every 15 seconds reset approximate Redis clinic seat counters from
SELECT clinic_id, day, COUNT(*) FROM vaccine_seats WHERE status = 'OPEN' GROUP BY 1, 2; every 30 seconds sweep expired'HELD'rows to'EXPIRED'so search bitmaps refresh promptly; every hour assert zero invariant violations (zero overlapping active reservations, zero confirmed appointments missing reservation rows).
- Pre-scaling vs. reactive autoscaling: Because container autoscaling lags by 1–3 minutes while database vertical scaling cannot happen mid-spike, we pre-warm stateless pods 30 minutes before
Summary of key design choices
Challenge Mechanism Why It Works --------------------------------- ------------------------------------- ----------------------------------------- Never double-book any resource PostgreSQL GiST exclusion constraint Storage engine rejects any `[start, end)` overlap Clinician + "any exam room" Clinician-first lock + SAVEPOINT loop Deadlock-free atomic multi-resource claim 3,600/s fast calendar reads 36-byte UTC-day Redis bitmaps + outbox ~1.1 GB RAM; stale cache never decides writes 150,000/s waiting-room status Pre-open lottery + 2s CDN status JSON Fair against bots; < 5 origin reads/s 1,000/s hot clinic seat claims Pre-created seats + SKIP LOCKED Zero single-row lock queue; parallel claims Protect regular sick visits Bulkhead pools + priority load shed Vaccine rush cannot starve normal care
Intuition & how it works
Think of this system as a clinic front desk with one ironclad master ledger in the back office, a fast whiteboard in the lobby, and a velvet-rope ticket line outside for immunization launch days. In the back office, every doctor and exam room is guarded by a database exclusion constraint (a rule built into PostgreSQL's index engine that physically refuses to save two active bookings whose [start, end) minutes overlap), while the lobby whiteboard (Redis availability bitmaps, compact 36-byte arrays of 0s and 1s representing each 5-minute block of a day) handles thousands of searches per second even if it trails the ledger by two seconds. When an immunization drop brings 3 million anxious patients for 200,000 doses, the velvet-rope waiting room hands everyone a tamper-proof numbered ticket, displays one shared "Now Serving" sign on a CDN (Content Delivery Network) so 150,000 browsers can check progress without touching our servers, and admits patients 1,000 at a time to claim pre-printed seat rows in parallel using FOR UPDATE SKIP LOCKED (a SQL instruction that skips any seat currently being locked by another clerk instead of waiting in a single-file line).
Why do the naive approaches fail? Running SELECT in application code to check whether 10:00 AM is open and then running INSERT lets two simultaneous clicks both read "open" and double-book Dr. Chen milliseconds apart. Exposing the booking database directly to a 3-million-person flash-crowd rush saturates database connections in seconds—burning huge compute only to return 2.8 million errors because supply is fixed at 200,000 doses. Even with a waiting room, storing remaining_doses = 160 on a single row per clinic-morning forces hundreds of admitted users to queue single-file behind one database row lock.
Let's trace 4 concrete events around Dr. Chen's 10:00-10:30 slot (which also needs 1 of 2 exam rooms, room_1 or room_2):
1. Fast read from Redis bitmaps (t = 0.000 s):
- Patient Priya and Patient Marcus both load Dr. Chen's Tuesday calendar from Redis.
- Dr. Chen's 10:00-10:30 bits are 111111 (free) and room_1's bits are 111111 -> both see "10:00 Open".
2. Concurrent POST /v1/holds race (t = 1.200 s):
- Priya's transaction inserts (dr_chen, [10:00, 10:30), HELD) and (room_1, [10:00, 10:30), HELD) -> COMMITS!
- Marcus's transaction arrives 2 ms later for dr_chen [10:00, 10:30):
* PostgreSQL's GiST exclusion index immediately raises 23P01 (overlap violation).
* Marcus receives 409 SLOT_TAKEN + 3 nearby free slots [10:30, 11:15, 13:00]; zero double booking!
3. Outbox cache refresh (t = 1.600 s):
- Priya's committed outbox event triggers the Availability Builder -> flips dr_chen & room_1 10:00 bits to 0.
4. Multi-resource room tie at 10:30 (t = 4.000 s):
- Marcus books Dr. Chen at 10:30 while Dr. Ortiz's patient also tries to grab room_1 at 10:30.
- Marcus's transaction locks dr_chen [10:30, 11:00), opens SAVEPOINT try_room, hits 23P01 on room_1,
rolls back ONLY to try_room, inserts room_2 [10:30, 11:00), and COMMITS cleanly!
Key trade-offs
- Database GiST exclusion constraint vs. application/Redis distributed locks: Enforcing non-overlap inside PostgreSQL (
EXCLUDE USING gist (resource_id WITH =, during WITH &&)) protects every code path—holds, reschedules, and staff vacation blocks—and automatically handles arbitrary durations without risking lock-server drift. The trade-off is tying the reservation core to PostgreSQL (on databases without range exclusion constraints, you instead materialize one unique row per(resource_id, 5_min_bucket)). - Hold-then-confirm (
5 minTTL) vs. single-click booking: Temporary holds prevent the frustrating UX of losing an appointment after spending 3 minutes filling out insurance forms, at the cost of abandoned holds hiding slots briefly. Short TTLs (5 minregular,3 minimmunization) plus inline lazy expiry on conflicting holds minimize stranded inventory. - Event-driven availability bitmaps vs. live database calendar queries: Serving search from 36-byte Redis bitmaps rebuilt via a transactional outbox (an event table written in the same commit as the booking) keeps
3,600/sread spikes off PostgreSQL in ~1.1 GB of RAM, trading 1–2 seconds of display staleness that occasionally yields a polite409 SLOT_TAKENon hold. - Edge waiting room + admission control vs. massive write-tier scaling: When 3M patients chase 200,000 fixed doses, throttling entry to
1,000users/second while serving a 2-second CDN-cached status JSON keeps infrastructure small and responsive, whereas scaling database shards to 150k writes/s costs 100x more only to sell out in 2 seconds instead of 4 minutes. - Pre-open lottery + post-open FIFO vs. pure first-click FIFO: Randomly shuffling everyone present before
09:00:00neutralizes automated scripts and millisecond ping advantages, while switching to FIFO after09:00:00respects latecomers' arrival order; pure FIFO is slightly simpler to explain but turns launch second09:00:00into a bot war. - Pre-generated seat rows (
SKIP LOCKED) +(clinic, day)selection vs. exact-minute counter rows: Pre-inserting 200,000vaccine_seatsrows lets concurrent transactions claim distinct rows in parallel without lock queuing, trading away exact-minute picking on the initial click (patients can optionally swap to another open window on that day after securing a seat). - Workload bulkheads vs. shared server and DB pools: Dedicating separate service deployments and PostgreSQL connection pools to regular care vs. immunization events leaves a small slice of idle headroom on quiet days, but guarantees a regional demand frenzy never blocks a patient scheduling an urgent sick visit.
Common mistakes
- Read-then-write availability checks in application code (
if is_free(): insert()): Without a database exclusion/unique constraint or serializable lock, two concurrent requests read"free"at the same instant and double-book the clinician. - Consulting Redis or an async read replica to authorize a booking: Caches and replicas always lag slightly behind the primary; reading them inside the booking decision guarantees double bookings under load.
- Cancelling by
(provider_id, slot_time)instead ofappointment_id+Idempotency-Key: A delayed mobile retry of Patient A's cancellation will accidentally cancel Patient B's brand-new booking of that freed time. - Catching a room conflict inside PostgreSQL without a
SAVEPOINT: In PostgreSQL, any constraint violation puts the open transaction into an aborted state where all subsequent SQL commands fail untilROLLBACK—so looping to tryroom_2afterroom_1fails crashes unless wrapped inSAVEPOINT try_room. - Locking resources in inconsistent order (deadlocks): If Transaction 1 locks
exam_roomthenclinicianwhile Transaction 2 locksclinicianthenexam_room(or one path locksreservationsbeforeappointmentswhile another locksappointmentsbeforereservations), concurrent bookings deadlock under load. - Aggregating clinic rooms into one "any room free" bitmap for search: Combining
room_1free10:00-10:15withroom_2free10:15-10:30advertises a10:00-10:30slot that no single physical room can host uninterrupted. - Per-user uncached waiting-room polling (
GET /queue/status?user_id=123): Puttinguser_idin the status URL bypasses the CDN and slams origin servers with150,000requests/second; publishing one shared{ now_serving, admit_per_s }JSON lets every browser compute its own ETA locally from its signedposition.
Follow-up questions
- Why won't slightly outdated slot caches lead to two patients confirming the same appointment? Treat the Redis bitmap cache strictly as a read-only display hint and never consult it during
POST /v1/holds. Every hold goes directly to the PostgreSQL primary, where theEXCLUDE USING gist (resource_id WITH =, during WITH &&)constraint atomically rejects any overlap with an existing'HELD'or'CONFIRMED'reservation. If a cached calendar showed a slot that was taken one second earlier, the worst outcome is a clean409 SLOT_TAKENresponse returning three alternative nearby slots while the client refreshes that clinician-day, and staleness stays under ~2 seconds via transactional outbox events. - How would you design a bot-resistant virtual queue when millions of patients compete for a small batch of immunization slots? Require one authenticated, phone-verified patient per queue entry so opening 20 browser tabs yields the exact same ticket. Everyone joining before the announced opening timestamp enters a pre-open pool that is randomly shuffled at opening using an auditable seed into positions
1..N(eliminating bot and network-latency advantages), while post-opening arrivals getN + INCRin FIFO order, all encoded inside stateless HMAC-signed queue tokens. Clients poll a single user-agnostic, 2-second CDN-cachedGET /queue/statusendpoint ({ now_serving, sold_out, admit_per_s }), and a feedback controller advancesnow_servingeach second based on live database commit latency and remaining inventory—plus you can reserve dedicated seat pools (such as 15% for phone-in seniors or high-risk tiers) so digital speed never crowds out vulnerable groups. - How does the database behave when one patient cancels an appointment at the exact instant another patient tries to reserve that window?
Cancelruns a single transaction locking theappointmentsrow and setting bothappointmentsandreservationsto'CANCELLED'for that specificappointment_id. If a newHoldarrives a millisecond beforeCancellocks the row,Holdimmediately hits the still-active reservation and gets409 SLOT_TAKEN(the slot then reappears in search ~2 seconds later); ifHoldhits the GiST index whileCancelis in flight, PostgreSQL pausesHolduntilCancelcommits and then letsHoldsucceed cleanly with zero overlap. BecauseCanceltargets the oldappointment_idrather than the timestamp, a late network retry ofCancelsees"already CANCELLED"and cannot touch the new booking—and if a waitlist has priority, theCanceltransaction itself atomically inserts a 30-minute'HELD'reservation for the top waitlisted patient so a random racer cannot snipe the freed slot. - What schema and locking changes let a single visit atomically reserve both a specific physician and an available exam room? Each
visit_typelists its required resource kinds (such as the chosenclinicianplus one'exam_room'in that clinic), and a singleHoldtransaction inserts onereservationsrow per required resource so either all resources are reserved together or none are. To prevent deadlocks, every transaction locksclinicianfirst androomsecond; to resolve"any free exam room", the transaction queries candidate rooms in that clinic without overlapping active reservations and tries inserting them one by one inside a PostgreSQLSAVEPOINT(rolling back only to the savepoint if a concurrent booking just grabbedroom_1, and immediately claimingroom_2). On the search side, Redis stores a separate 36-byte daily bitmap for each individual room, and a 30-minute slot is displayed only if(clinician_bitmap & room_i_bitmap)contains 6 contiguous free 5-minute bits for at least one single roomroom_i.
Follow-up questions
- Why won't slightly outdated slot caches lead to two patients confirming the same appointment?
- How would you design a bot-resistant virtual queue when millions of patients compete for a small batch of immunization slots?
- How does the database behave when one patient cancels an appointment at the exact instant another patient tries to reserve that window?
- What schema and locking changes let a single visit atomically reserve both a specific physician and an available exam room?
Similar questions
- High-Concurrency Medical Appointment Scheduling System
- Navigating Technical Disagreements, Coaching, and Schedule Slips
- Balanced Bracket Delimiter Validation
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform