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

  1. 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 ms and booking p99 < 1 s on 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,000 seats across 250 clinics, 3,000,000 eligible residents).
  2. 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,000 doses; 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 at 1,000/s.
  3. 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_FULL
    

    Three 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, targeting apt_52 sees "already CANCELLED" and never touches Patient B's apt_64.
    • Vaccine holds request (clinic_id, day), not 10: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.
  4. Data model and database-enforced overlap protection

    Every time range is stored as a half-open interval [start, end)—meaning start is included and end is 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 if checks, 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 same resource_id can ever have overlapping tstzrange intervals:

    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 placing kind = 'BLOCK' into the exact same table means the single no_double_booking constraint automatically stops patients from booking during a doctor's lunch break and stops staff from accidentally blocking over an existing confirmed patient.

  5. 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]
    
  6. Deep dive 1: Atomic booking, multi-resource rooms, and race conditions

    PostgreSQL index predicates cannot call now() directly because now() changes every millisecond. That means an abandoned 'HELD' row past hold_expires_at still blocks no_double_booking until its status flips to 'EXPIRED'. Rather than waiting for a slow background cron job, POST /v1/holds lazily expires any stale conflicting holds right inside the booking transaction!

    To prevent deadlocks when two transactions touch appointments and reservations concurrently, every write path follows one global lock order: lock appointments (ordered by appointment_id) first, then reservations (ordered by resource_id). And when trying candidate exam rooms ("any free exam room in Clinic 9"), each room attempt wraps in a SAVEPOINT—a lightweight checkpoint inside a SQL transaction that lets us roll back a single failed room INSERT without 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: Confirm runs UPDATE appointments SET status = 'CONFIRMED', hold_expires_at = NULL WHERE appointment_id = :appt AND status = 'HELD' AND hold_expires_at > now(), followed by updating reservations. Because both Confirm and lazy expiry lock the appointments row first and re-evaluate WHERE status = 'HELD', strictly one wins.
    • Cancel racing a new booking: Cancel locks appointments then marks appointments and reservations 'CANCELLED'. A racing Hold arriving mid-cancel waits on the active reservation's GiST lock and succeeds right after Cancel commits (unless a waitlist patient exists—in which case Cancel atomically inserts a 30-minute 'HELD' reservation for the top waitlisted patient in the same transaction so nobody snipes the slot!).
  7. Deep dive 2: Fast search with event-driven availability bitmaps

    To serve 3,600 calendar views/second without touching PostgreSQL, Redis stores one 36-byte bitmap (288 bits = 288 five-minute slices of a 1,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_2 into a single clinic-wide bitmap first, bits 0–2 from room_1 plus bits 3–5 from room_2 would 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 bitwise AND operations.

    Keeping bitmaps fresh without dual-write bugs: Every committed booking, cancel, or block writes a row to outbox inside 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 (~20 rows) and updates avail:<resource_id>:<utc_date> in Redis if its monotonic version is newer (< 2 s lag). Even if Redis lags, stale cache data never causes a double booking because POST /v1/holds checks PostgreSQL's no_double_booking constraint, not Redis.

  8. Deep dive 3: Fair virtual waiting room for the vaccine spike

    When 500,000 people gather before the 09:00:00 vaccine 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:

    1. Pre-open lottery (< 09:00:00): Verified accounts (one entry per verified phone/patient, deduplicated across browser tabs) join a waiting pool. At 09:00:00, a worker shuffles those early joiners using a reproducible cryptographic seed (logged for public audit) into positions 1..N. Arriving 20 minutes early and arriving 5 seconds early give the exact same random odds.
    2. Post-open FIFO (>= 09:00:00): Anyone joining after 09:00:00 gets N + INCR(late_counter) behind the pre-open pool.
    3. Stateless HMAC queue tokens: The server returns position wrapped 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.
    4. 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 with Cache-Control: public, max-age=2 turns 150,000 requests/second into < 5 origin hits/second!
    5. Closed-loop admission controller: Every second, a controller advances now_serving based on live PostgreSQL commit latency (p99 < 150 ms -> step up; p99 > 250 ms -> back off), active 10-minute session_token count, and remaining seats. Once position <= now_serving, the client exchanges its queue_token for one short-lived session_token required by the vaccine hold API.
  9. Deep dive 4: Hot-slot partitioning (`SKIP LOCKED`), load shedding, and reconciliation

    Even among the 1,000 admitted 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 LOCKED tells 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_at and 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):
      1. Keep Confirmations alive first (dropping a confirm wastes an already-held seat and frustrates a user at step 2);
      2. Keep Cancellations second (they return inventory to the pool);
      3. Shed New Holds third;
      4. 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 freezes now_serving automatically.
    • Waiting-room Redis crash: Users keep their places because queue_tokens are HMAC-signed! now_serving and late_counter checkpoint to PostgreSQL every second, so a replacement Redis resumes safely from saved_counter + 5000 while 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).
  10. 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 min TTL) 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 min regular, 3 min immunization) 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/s read spikes off PostgreSQL in ~1.1 GB of RAM, trading 1–2 seconds of display staleness that occasionally yields a polite 409 SLOT_TAKEN on hold.
  • Edge waiting room + admission control vs. massive write-tier scaling: When 3M patients chase 200,000 fixed doses, throttling entry to 1,000 users/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:00 neutralizes automated scripts and millisecond ping advantages, while switching to FIFO after 09:00:00 respects latecomers' arrival order; pure FIFO is slightly simpler to explain but turns launch second 09:00:00 into a bot war.
  • Pre-generated seat rows (SKIP LOCKED) + (clinic, day) selection vs. exact-minute counter rows: Pre-inserting 200,000 vaccine_seats rows 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 of appointment_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 until ROLLBACK—so looping to try room_2 after room_1 fails crashes unless wrapped in SAVEPOINT try_room.
  • Locking resources in inconsistent order (deadlocks): If Transaction 1 locks exam_room then clinician while Transaction 2 locks clinician then exam_room (or one path locks reservations before appointments while another locks appointments before reservations), concurrent bookings deadlock under load.
  • Aggregating clinic rooms into one "any room free" bitmap for search: Combining room_1 free 10:00-10:15 with room_2 free 10:15-10:30 advertises a 10:00-10:30 slot that no single physical room can host uninterrupted.
  • Per-user uncached waiting-room polling (GET /queue/status?user_id=123): Putting user_id in the status URL bypasses the CDN and slams origin servers with 150,000 requests/second; publishing one shared { now_serving, admit_per_s } JSON lets every browser compute its own ETA locally from its signed position.

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 the EXCLUDE 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 clean 409 SLOT_TAKEN response 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 get N + INCR in FIFO order, all encoded inside stateless HMAC-signed queue tokens. Clients poll a single user-agnostic, 2-second CDN-cached GET /queue/status endpoint ({ now_serving, sold_out, admit_per_s }), and a feedback controller advances now_serving each 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? Cancel runs a single transaction locking the appointments row and setting both appointments and reservations to 'CANCELLED' for that specific appointment_id. If a new Hold arrives a millisecond before Cancel locks the row, Hold immediately hits the still-active reservation and gets 409 SLOT_TAKEN (the slot then reappears in search ~2 seconds later); if Hold hits the GiST index while Cancel is in flight, PostgreSQL pauses Hold until Cancel commits and then lets Hold succeed cleanly with zero overlap. Because Cancel targets the old appointment_id rather than the timestamp, a late network retry of Cancel sees "already CANCELLED" and cannot touch the new booking—and if a waitlist has priority, the Cancel transaction 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_type lists its required resource kinds (such as the chosen clinician plus one 'exam_room' in that clinic), and a single Hold transaction inserts one reservations row per required resource so either all resources are reserved together or none are. To prevent deadlocks, every transaction locks clinician first and room second; 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 PostgreSQL SAVEPOINT (rolling back only to the savepoint if a concurrent booking just grabbed room_1, and immediately claiming room_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 room room_i.

Follow-up questions

Similar questions

More Garner Health interview questions

All 4 Garner Health questions →