High-Concurrency Medical Appointment Scheduling System
Medium · System Design · Software Engineer · Technical Screen
Prompt
You are architecting the scheduling backend for a digital care-navigation service connecting 5,000,000 active patients with 50,000 active clinicians across diverse medical specialties and clinic sites. Whenever sought-after specialists publish new calendar blocks or peak daytime traffic hits, dozens of patients often click the exact same visit window at once over flaky mobile connections. Your design must make double-booking impossible while keeping calendar browsing snappy and maintaining a complete compliance history.
Support these product capabilities and operational targets:
- Open-slot discovery: Let patients query open visit windows filtered by clinician, medical specialty, geographic area, and target date window, keeping
p99query latency below150 ms. - Slot reservation & checkout holds: Allow a patient to claim an open time window (directly or via a temporary hold) with immediate confirmation. Duplicate submissions carrying the same client idempotency token must replay the original outcome without creating extra reservations.
- Cancellations & time changes: Enable either the patient or the clinic to cancel an existing visit or shift it onto another open time window.
- Off-path messaging: Dispatch booking confirmations, upcoming-visit reminders, and cancellation alerts over email and SMS asynchronously so third-party delivery never slows down reservation commits.
- Compliance history: Persist an immutable record for every lifecycle change across
AVAILABLE,HELD,BOOKED, andCANCELLED, capturing exact timestamps and who initiated the change. - Traffic & consistency profile: Read-heavy workload (~
50:1reads to writes) peaking around1,500 QPSfor availability lookups and50 QPSfor reservations and schedule updates, with strict serialization on writes so two competing requests for one slot can never both win.
Scope & Expectations
- API surface & retry safety: Define HTTP endpoints, headers, and request/response bodies for browsing slots, placing holds/bookings, canceling, and rescheduling idempotently.
- Schema & concurrency guarantees: Specify how bookable time windows and appointments are stored and how competing claims on a single slot are resolved without race conditions.
- Service topology & reliable async delivery: Lay out the read/write services, databases, caches, and event pipeline that decouple fast search reads and outbound notifications from transactional writes.
- Failure modes & edge cases: Address expired checkout holds, partial failures when moving an appointment to a new slot, and stale availability entries in the search layer.
Step-by-step walkthrough
Clarify requirements and system guarantees
At the heart of healthcare scheduling is one strict rule: two patients can tap the exact same
10:15 AMwindow in the same millisecond, mobile Wi-Fi can retry either request, and strictly one patient may walk away with that visit. Every other part of the system—fast search, checkout holds, rescheduling, email/SMS alerts, and compliance logs—must be built so that it never weakens that guarantee and never slows down the reservation commit.Functional requirements
- Open-slot discovery: Patients filter open visit windows by clinician, medical specialty, clinic area (or coordinate radius), and target dates, receiving matches grouped by clinician.
- Checkout hold & immediate booking: A patient can place a 10-minute hold while entering insurance details and then confirm, or reserve directly in a single step. Once the API returns
201 Created, the visit is durably theirs. Client retries carrying the same idempotency key (a unique client-generated request ID) replay the exact original response without creating duplicate bookings. - Cancellations & time changes: Either the patient or the clinic can cancel a booked visit or reassign it to another open time window. If claiming the target window fails during a reschedule, the patient's original visit must remain completely intact.
- Off-path notifications: Booking confirmations, 24-hour/2-hour reminders, and cancellation alerts (email/SMS) fire reliably after database commit so external vendor calls never add latency to reservation writes.
- Append-only compliance history: Every lifecycle step across
AVAILABLE,HELD,BOOKED, andCANCELLEDwrites an immutable audit entry containing timestamps, request ID, and initiating actor (PATIENT,PROVIDER,STAFF, orSYSTEM).
Non-functional requirements & explicit assumptions
- Zero double-booking (CP on writes): On the booking path, strict consistency beats availability—if the primary database is unreachable during failover, writes return
503 Service Unavailablerather than risking a split-brain double-booking. - Fast search (
p99 < 150 msat1,500 QPSpeak): Search reads may lag behind writes by ~1 second (eventual consistency), because every booking re-verifies truth on the primary database. - Zero data loss (
RPO = 0): Confirmed bookings survive a primary database crash via synchronous standby replication. - Healthcare privacy: Linking a patient to a specialist (for example, oncology or psychiatry) is protected health information (PHI under US HIPAA). Encrypt data in transit and at rest, and omit specialty/visit reasons from plain SMS text.
- Calendar assumptions: Providers publish weekly schedule templates with fixed slot lengths (
15,20,30, or60minutes) over a rolling 90-day horizon, and each patient may hold at most 2 active slots simultaneously to prevent hoarding.
Back-of-the-envelope capacity and contention math
Let's translate
50,000providers,5,000,000patients,1,500 QPSsearch peak, and50 QPSbooking peak into concrete row counts, RAM sizes, and database load:Category Back-of-the-envelope calculation Architectural takeaway ------------------ --------------------------------------------------------- ------------------------------------------- Slot inventory 50,000 providers x ~20 slots/day x ~64 working days ~19.2 GB total! Fits completely in RAM on (90-day horizon) (in 90 days) = 64,000,000 slot rows x ~300 B (w/ indexes) ONE PostgreSQL primary (no sharding needed) Daily horizon roll 50,000 providers x 20 slots = 1,000,000 new rows/night Easy nightly background batch (~12 rows/s) Write load 50 QPS peak x ~5 SQL statements/tx = ~250 statements/s Tiny (<5%) fraction of one Postgres primary; every booking can be one local ACID tx Search read load 1,500 QPS peak; 20 providers/page -> 30,000 schedule Serve from OpenSearch + Redis so read spikes range reads/s (30:1 peak read/write ratio; ~50:1 daily) never touch the transactional primary Audit & reminders <= 1M bookings/day x ~3 transitions = <= 3M rows/day ~1.5 GB/day (~550 GB/yr): partition monthly x ~500 B; ~3 notifications/booking = <= 3M msgs/day and archive old partitions to object storage Hot-slot rush Popular specialist opens 40 slots; 2,000 patients click Throughput (33 req/s) is tiny, but ROW LOCK in 60 s -> ~33 booking attempts/s on just 40 rows! contention is high -> fail losers in <5 msThree crucial design decisions fall right out of these numbers: 1. Do not shard the transactional database. At
50 QPSpeak and~19.2 GBof active slots, one PostgreSQL primary handles the write load effortlessly, letting us execute holds, bookings, and cross-provider reschedules inside single-node ACID transactions (database transactions that are Atomic, Consistent, Isolated, and Durable—meaning all steps succeed together or roll back together). 2. Contention on hot rows—not total write throughput—is the real engineering problem. When 50 people click one10:15 AMslot, 1 must win in milliseconds and 49 must fail immediately without holding long locks or retrying blindly. 3. Separate read infrastructure from write truth. Search runs against an index and cache designed for fast fan-out reads, while Postgres guards slot ownership.API design and idempotency contract
Every write request requires an
Authorizationbearer token (identifying the calleraccount_id) and a client-generatedIdempotency-KeyUUID header stored for 24 hours alongside a SHA-256 hash of the request payload:1. Availability Search (Read path — p99 < 150 ms) GET /v1/availability?specialty=dermatology&lat=41.88&lng=-87.63&radius_km=20 &from=2026-12-07&to=2026-12-21&limit=20&cursor=... -> 200 OK { "as_of": "2026-12-02T15:10:04Z", "providers": [ { "provider_id": 14, "name": "Dr. M. Lin", "distance_km": 2.4, "slots": [ { "slot_id": 4101, "start_at": "2026-12-09T10:15:00-06:00", "end_at": "2026-12-09T10:35:00-06:00", "location_id": 8 } ] } ], "next_cursor": "..." } 2. Place Temporary 10-Minute Hold POST /v1/holds Headers: Authorization, Idempotency-Key: <uuid> Body: { "slot_id": 4101 } -> 201 Created { "hold_id": "f47ac...", "slot_id": 4101, "expires_at": "2026-12-02T15:20:04Z" } -> 409 Conflict { "error": "SLOT_UNAVAILABLE", "alternatives": [ { "slot_id": 4102, ... } ] } 3. Confirm Booking (from an existing hold OR direct 1-step booking when hold_id is omitted) POST /v1/appointments Headers: Authorization, Idempotency-Key: <uuid> Body: { "slot_id": 4101, "hold_id": "f47ac...", "visit_reason": "annual-check", "insurance_id": "ins_41" } -> 201 Created { "appointment_id": 8204, "status": "BOOKED", "slot_id": 4101, "version": 1 } -> 409 Conflict { "error": "SLOT_UNAVAILABLE" | "HOLD_EXPIRED", "alternatives": [ ... ] } 4. Cancel or Reschedule (optimistic concurrency guard via If-Match version header) POST /v1/appointments/8204/cancel Headers: Authorization, Idempotency-Key, If-Match: "1" Body: { "reason": "patient_schedule_change" } -> 200 OK { "appointment_id": 8204, "status": "CANCELLED", "version": 2 } -> 412 Precondition Failed { "error": "STALE_APPOINTMENT_VERSION" } POST /v1/appointments/8204/reschedule Headers: Authorization, Idempotency-Key, If-Match: "1" Body: { "new_slot_id": 4180, "hold_id": "..." } -> 200 OK { "appointment_id": 8204, "old_slot_id": 4101, "new_slot_id": 4180, "version": 2 } -> 409 Conflict { "error": "NEW_SLOT_UNAVAILABLE", "alternatives": [ ... ] } (slot 4101 stays BOOKED!) 5. Audit History GET /v1/appointments/8204/history -> ordered list of state transitions + actor metadataKey API behaviors that prevent subtle bugs: - Exact response replay (including
409): Scoping keys by(account_id, idem_key)prevents collisions across users. Replaying the same key + same payload returns the stored status code and JSON body (both201and409), while reusing the same key with a different body returns422 Unprocessable Entity. Transient5xxdatabase errors roll back without saving the key so retries can succeed. - Fast UX recovery on contention: Returning 3–5 nearbyalternativesinside every409lets a patient who lost a race pick the10:35 AMslot in one tap instead of repeating a search. - Stableappointment_idacross reschedules: Updatingslot_idandversionon the existing appointment preserves audit history and calendar links, whileIf-Matchstops an old open browser tab from canceling an appointment the provider already rescheduled.Data model: pre-materialized slots vs. dynamic intervals
Should bookable slots exist as physical rows in the database ahead of time, or be computed on the fly by subtracting busy intervals from working-hour templates?
Dimension Pre-materialized slot rows (Chosen) Dynamic computation from busy intervals ------------------------ ---------------------------------------- --------------------------------------------- Storage footprint ~64M rows (~19.2 GB for 90-day horizon) Tiny (templates + active bookings only) Concurrency guard Atomic conditional UPDATE on 1 slot_id Range-overlap GiST exclusion constraint Availability search Fast indexed lookup; trivial Redis ZSET Must subtract intervals per provider on read Audit trail Direct state machine per slot_id Harder to audit unbooked "AVAILABLE" windows Variable visit durations Awkward (must lock N adjacent rows) Natural fit (any [start_at, end_at) range) Schedule template edits Regenerate future AVAILABLE rows Instant (unless conflicting w/ booked ranges)Because medical office visits follow fixed template durations per provider (
15/20/30min) and64Mrows take only~19.2 GB, pre-materialized slot rows give us one concreteslot_idto lock, cache, and audit. Better yet, we also attach a PostgreSQL exclusion constraint (a database index rule using Generalized Search Trees,GiST, that forbids any two non-cancelled rows for the sameprovider_idfrom having overlapping[start_at, end_at)time ranges) so a buggy schedule-template update can never publish a9:00–9:30slot on top of an already-booked9:20–9:40visit:PostgreSQL Schema (Primary Source of Truth) slots slot_id BIGINT PRIMARY KEY provider_id BIGINT NOT NULL location_id BIGINT NOT NULL start_at TIMESTAMPTZ NOT NULL -- always stored in UTC; materialized from local tz end_at TIMESTAMPTZ NOT NULL status TEXT CHECK (status IN ('AVAILABLE', 'HELD', 'BOOKED', 'CANCELLED')) claim_id UUID NULL -- active hold_id (or direct booking claim token) held_by BIGINT NULL -- patient_id holding or booking the slot hold_expires_at TIMESTAMPTZ NULL -- non-null only while status = 'HELD' appointment_id BIGINT NULL version INT NOT NULL DEFAULT 0 -- increments on EVERY state change (used by cache!) updated_at TIMESTAMPTZ NOT NULL -- Prevents overlapping live slots for the same doctor if templates change: EXCLUDE USING gist (provider_id WITH =, tstzrange(start_at, end_at) WITH &&) WHERE (status <> 'CANCELLED') -- Partial index covering open + potentially expired-hold slots per provider: INDEX slots_open_idx (provider_id, start_at) INCLUDE (end_at, location_id, status, hold_expires_at, version) WHERE status IN ('AVAILABLE', 'HELD') appointments appointment_id BIGINT PRIMARY KEY patient_id BIGINT NOT NULL slot_id BIGINT NOT NULL REFERENCES slots(slot_id) status TEXT CHECK (status IN ('BOOKED', 'CANCELLED', 'COMPLETED', 'NO_SHOW')) version INT NOT NULL DEFAULT 0 created_at TIMESTAMPTZ NOT NULL -- Belt-and-suspenders safety net: impossible for two active bookings to point to one slot_id! UNIQUE INDEX one_active_booking_per_slot ON appointments (slot_id) WHERE status = 'BOOKED' slot_events (append-only audit log, partitioned monthly by recorded_at; UPDATE/DELETE revoked) (event_id, recorded_at) PRIMARY KEY, slot_id, appointment_id NULL, from_status, to_status, action, actor_type, actor_id, request_id, occurred_at, recorded_at idempotency_keys (account_id, idem_key) PRIMARY KEY, request_hash BYTEA, status TEXT ('IN_PROGRESS' | 'COMPLETED'), response_code INT, response_body JSONB, created_at outbox (transactional event queue, partitioned daily by created_at, dropped after 7 days) (event_id, created_at) PRIMARY KEY, topic TEXT, partition_key TEXT, event_type TEXT, payload JSONBNotice the clean distinction on cancellations: when a patient cancels far enough in advance (
> 2 hoursbeforestart_at), theappointmentsrow becomesCANCELLEDand theslotsrow returns toAVAILABLEso another patient can book it; when a provider blocks off a clinic day, theslotsrow itself moves toCANCELLEDso nobody can book that time.High-level system architecture
Patients (Mobile / Web) & Provider Portal | v [ API Gateway: TLS, Auth, Rate Limits, Request-ID ] / \ Search Reads (1,500 QPS peak) Writes: Hold / Book / Cancel / Reschedule (50 QPS) / \ v v [ Search Service ] [ Booking Service ] | | | (1) Single local ACID tx (1) Geo +| |(2) Pipelined ZRANGE | (slots, appointments, specialty| | for top 20 providers | slot_events, idempotency, outbox) v v v [ OpenSearch ] [ Redis Cache ] <-----(2) best-effort---- + (50k provider avail:{prov_id} versioned Lua update | docs + open availv:{prov_id} v dates bitmap) ^ [ PostgreSQL Primary ] | | + 2 Sync Standbys (ANY 1 quorum, RPO=0) Cache miss -> | | + 2 Async Read Replicas (cache rebuilds) single-flight | | rebuild from | | Write-Ahead Log (WAL logical decoding) Read Replica | v | [ CDC Outbox Relay (Debezium) ] | | | v | [ Kafka Event Bus ] | - availability (key = provider_id) | - appointments (key = appointment_id) | / | \ +--- [ Cache Updater ] [ Notification Service ] [ Hold-Expiry Router ] (versioned Lua) - dedupe by (event_id,ch) - SQS 10-min Delay Queue - Email / SMS + Reminders - Expiry Worker -> PostgresWhy this separation works so well: - Zero external dependencies on the write critical path: A booking hits only API Gateway -> Booking Service -> PostgreSQL Primary -> HTTP response (
~5–12 ms). If Redis, Kafka, OpenSearch, or the SMS vendor is down, patients can still book appointments with zero double-bookings. - Zero primary-database load from search spikes: Search queries hit OpenSearch (50,000tiny provider metadata documents) and Redis (avail:{provider_id}sorted sets). Even cache misses rebuild from async PostgreSQL read replicas rather than the write primary.Deep dive 1: Zero double-booking under concurrency and retries
Let's compare the four standard ways engineers try to prevent double-booking when 50 requests race for
slot_id = 4101:Strategy How it works Why we accept or reject it ------------------------------- ------------------------------------------- --------------------------------------------- Distributed lock (Redis / ZK) Acquire ` SET lock:4101 NX EX 5 `, then REJECT: Extra network hop + failure mode. If write to Postgres JVM pauses 6s after acquiring a 5s lease, two writers hit Postgres at once unless Postgres checks a constraint anyway! Pessimistic SELECT FOR UPDATE `SELECT ... FOR UPDATE`, check status in ACCEPTABLE (needed for multi-slot reschedule), app code, then `UPDATE` but costs 2 SQL round trips for 1-slot claims. Optimistic version column Read `version = 4`, then `UPDATE ... WHERE SUBOPTIMAL on hot rows: losers only realize slot_id = 4101 AND version = 4` status changed after reading stale snapshots. Conditional atomic UPDATE Single `UPDATE slots SET status='BOOKED'... CHOSEN: 1 SQL statement inside the source of (Compare-And-Swap in SQL) WHERE slot_id=4101 AND status='AVAILABLE'` truth; Postgres serializes row locks cleanly!How PostgreSQL resolves a millisecond tie inside
READ COMMITTED: Suppose Nora and Devon both sendUPDATE slots SET status = 'BOOKED' ... WHERE slot_id = 4101 AND status = 'AVAILABLE'at11:00:00.001:Time Transaction 1 (Nora) Transaction 2 (Devon) ------------ --------------------------------------------- -------------------------------------------------- 11:00:00.001 Acquires row-level lock on slot 4101; Tries to update slot 4101 -> BLOCKED waiting on status is 'AVAILABLE' -> sets 'BOOKED' Transaction 1's row lock! 11:00:00.004 Inserts appointment, slot_event, outbox, and idempotency response -> COMMIT! Unblocks! Postgres re-reads latest committed row (status is now 'BOOKED'), re-evaluates WHERE clause 11:00:00.005 Receives 201 Created WHERE is FALSE -> updates 0 rows! Returns 409 fastHere is the complete single-transaction flow executed by
BookingServiceforPOST /v1/appointments(handling direct bookings, active holds owned by the caller, and taking over someone else's expired hold):BEGIN; -- Step 1: Claim idempotency key. Concurrent duplicate requests with the same key block -- on the PK index until this tx commits, then see 0 rows inserted and replay the saved response. INSERT INTO idempotency_keys (account_id, idem_key, request_hash, status) VALUES (:patient_id, :idem_key, :request_hash, 'IN_PROGRESS') ON CONFLICT (account_id, idem_key) DO NOTHING RETURNING idem_key; -- (If 0 rows returned: COMMIT/ROLLBACK, SELECT stored response; if request_hash != saved, return 422; -- else replay stored response_code and response_body!) -- Step 2: Lock the slot row so we can inspect its prior state for exact auditing AND claim it atomically. SELECT status, claim_id, held_by, hold_expires_at, version FROM slots WHERE slot_id = :slot_id FOR UPDATE; -- Application checks in-memory on the locked row: -- Can claim if: -- (a) status = 'AVAILABLE', OR -- (b) status = 'HELD' AND claim_id = :hold_id AND held_by = :patient_id, OR -- (c) status = 'HELD' AND hold_expires_at <= now() -- lazy expiry takeover! -- If NOT claimable -> save 409 response in idempotency_keys, COMMIT, and return 409 + alternatives. -- Step 3: Claim the slot and bump monotonic version. UPDATE slots SET status = 'BOOKED', claim_id = COALESCE(:hold_id, gen_random_uuid()), held_by = :patient_id, hold_expires_at = NULL, appointment_id = :appointment_id, version = version + 1, updated_at = now() WHERE slot_id = :slot_id; -- Step 4: Create the appointment (backed by partial unique index one_active_booking_per_slot). INSERT INTO appointments (appointment_id, patient_id, slot_id, status, version) VALUES (:appointment_id, :patient_id, :slot_id, 'BOOKED', 1); -- Step 5: Write immutable audit row(s) in the SAME transaction. -- (If case (c) took over another patient's expired hold, first insert a SYSTEM 'HELD' -> 'AVAILABLE' -- row with occurred_at = old.hold_expires_at, then insert the patient's 'AVAILABLE' -> 'BOOKED' row!) INSERT INTO slot_events (slot_id, appointment_id, from_status, to_status, action, actor_type, actor_id, request_id, occurred_at) VALUES (:slot_id, :appointment_id, :effective_from_status, 'BOOKED', 'BOOK', 'PATIENT', :patient_id, :request_id, now()); -- Step 6: Enqueue integration events in the transactional outbox. INSERT INTO outbox (topic, partition_key, event_type, payload) VALUES ('appointments', :appointment_id::text, 'AppointmentBooked', :appt_payload_jsonb), ('availability', :provider_id::text, 'SlotChanged', :slot_payload_jsonb); -- Step 7: Freeze final HTTP response onto the idempotency key. UPDATE idempotency_keys SET status = 'COMPLETED', response_code = 201, response_body = :response_jsonb WHERE account_id = :patient_id AND idem_key = :idem_key; COMMIT;Notice why writing
slot_eventsexplicitly inside this repository transaction (while revokingUPDATEandDELETEprivileges onslot_eventsfrom the application database role) is so clean: every transition is 100% atomic with the state change, connection poolers like PgBouncer in transaction mode never leak session variables across requests, and taking over a lapsed hold cleanly records bothHELD -> AVAILABLE(HOLD_EXPIRED) andAVAILABLE -> BOOKED(BOOK).Deep dive 2: Transactional Outbox for notifications and auditability
Why can't
BookingServicesimply commit to Postgres and then callkafka.produce(...)ortwilio.send_sms(...)on the next line of code? That creates the classic dual-write problem: 1. Commit DB first, then publish to Kafka: If the server pod restarts in the 2 ms betweenCOMMITandkafka.produce, the slot is permanently booked in Postgres, yet the confirmation SMS is never sent and the Redis search cache never removes the slot. 2. Publish to Kafka first, then commit DB: If the database commit fails or hits a constraint violation, the patient receives a"Your appointment is confirmed!"text message for an appointment that rolled back. 3. Distributed two-phase commit (2PC): Coordinating locks across Postgres and Kafka/Twilio adds massive latency, hurts availability if either side hiccups, and isn't supported by external SMS APIs anyway.The Transactional Outbox pattern solves this cleanly using local database atomicity: - Atomic commit: Step 6 of our booking transaction inserts
AppointmentBookedandSlotChangedrows into the Postgresoutboxtable. Either both the booking and the outbox rows exist on disk, or neither exists. - Low-latency WAL relay: A Change Data Capture (CDC) connector (such as Debezium tailing PostgreSQL's Write-Ahead Log (WAL)—the internal append-only journal Postgres writes before modifying tables, configured withpublish_via_partition_root = truefor daily partitions) streams newoutboxrows into Kafka within~100–500 ms. - Ordered, idempotent consumers: Kafka partitionsavailabilityevents byprovider_idandappointmentsevents byappointment_id. Because a crashed CDC relay can republish an outbox row (at-least-once delivery), every downstream worker deduplicates:Notification Service Flow (consuming `appointments` topic) AppointmentBooked(event_id, appt_id, version=1, start_at) | +--> 1. INSERT INTO notification_log (event_id, channel='SMS', status='SENDING') | ON CONFLICT (event_id, channel) DO NOTHING | (0 rows -> duplicate Kafka delivery; skip immediately!) | +--> 2. Call SMS/Email vendor passing client_reference = event_id; mark status = 'SENT' | SMS text stays HIPAA-minimal: "Appt confirmed for Dec 9 at 10:15 AM. Open app for details." | +--> 3. Schedule 24h and 2h rows in `scheduled_reminders(appt_id, target_version=1, send_at)` At `send_at`, dispatcher verifies `appointments.status = 'BOOKED' AND version = target_version` so canceled or rescheduled appointments NEVER trigger stale reminders!Deep dive 3: Fast search, versioned cache invalidation, holds, and rescheduling
1. Meeting the
< 150 msp99 search budget Availability search executes in two fast stages without touching the PostgreSQL primary:Stage Datastore & Operation p99 Latency ------------------------------------- ------------------------------------------------- ----------- 1. Gateway auth & TLS Verify token, parse query ~5 ms 2. Provider discovery OpenSearch (50k docs): geo_distance + specialty ~35 ms + accepted_insurance + open_dates range filter 3. Fetch open slots (top 20 doctors) 1 pipelined Redis call: ~5 ms ZRANGE avail:{provider_id} <from_ts> <to_ts> BYSCORE 4. JSON serialization & network Group slots by provider, build pagination cursor ~20 ms ------------------------------------- ------------------------------------------------- ----------- Total end-to-end p99 ~65 ms (< 150 ms!)2. Preventing stale cache resurrection with monotonic slot versions What if a slot is booked (
version = 2), removed from Redis immediately, and 200 ms later a delayedAVAILABLEevent (version = 1) from an earlier cancelled hold arrives from Kafka—or a cache miss reads a slightly lagging read replica still atversion = 1? Without version tracking, the old event would put the already-booked slot back into Redis!We prevent this by storing a companion version hash
availv:{provider_id}on the same Redis shard (using Redis Cluster hash tags{provider_id}) and applying every write-through, Kafka event, and replica rebuild through one atomic Lua check:Redis Lua Gate for Cache Updates: KEYS[1] = avail:{14} -- Sorted Set: member = slot_id, score = start_epoch (ONLY 'AVAILABLE' slots) KEYS[2] = availv:{14} -- Hash: field = slot_id, value = highest slot.version applied so far if new_version <= (HGET availv:{14} slot_id or -1) then return 0 -- Ignore stale out-of-order Kafka message or lagging replica row! end HSET availv:{14} slot_id new_version if new_status == 'AVAILABLE' then ZADD avail:{14} start_epoch slot_id else ZREM avail:{14} slot_id -- Hides HELD, BOOKED, CANCELLED!Right after
COMMIT,BookingServicefires a best-effort synchronous call to this script (closing the stale window to< 5 msin the healthy case), while theSlotChangedoutbox consumer runs the exact same script asynchronously to guarantee eventual convergence even if the booking pod crashed right afterCOMMIT.3. 10-minute holds without a polling cron job Correctness comes from lazy expiration (
status = 'HELD' AND hold_expires_at <= now()is treated as bookable in SQL), so an expired hold never blocks a real buyer even if background queues are delayed. To restore the slot to Redis search and write theHOLD_EXPIREDaudit row promptly when a user abandons checkout,POST /v1/holdsemitsHoldCreated(slot_id, hold_id, expires_at)via the outbox, which enqueues a message onto a delay queue (for example AWS SQS withDelaySeconds = 600, well inside SQS's 900-second native limit). Ten minutes later, a worker runs an idempotent conditional release (WHERE slot_id = :id AND claim_id = :hold_id AND status = 'HELD' AND hold_expires_at <= now()): if the patient already confirmed,0rows match and the message is harmlessly ignored; otherwise the slot flips back toAVAILABLEand reappears in Redis.4. Atomic rescheduling without deadlocks Because all
64Mslots live on one Postgres primary, moving an appointment fromslot_atoslot_bexecutes in one ACID transaction: 1. Lock both rows in deterministic ascending ID order (SELECT ... FROM slots WHERE slot_id IN (:slot_a, :slot_b) ORDER BY slot_id FOR UPDATE) so two patients swapping slots (4101 -> 4180and4180 -> 4101) can never deadlock. 2. Verifyslot_bis claimable (AVAILABLE, caller's own hold, or expired hold) andslot_astill belongs to:appointment_idat:if_matchversion. Ifslot_bwas just taken,ROLLBACKimmediately—slot_awas never modified! 3. Claimslot_b(BOOKED), releaseslot_a(AVAILABLEifstart_at > now() + interval '2 hours', elseCANCELLEDso last-minute releases aren't wasted), updateappointments.slot_id = :slot_b, appendslot_events, and emitAppointmentMoved+ twoSlotChangedoutbox rows. (If 100x future growth ever shards slots byprovider_id, cross-shard reschedules use a make-before-break saga: hold B -> book B -> release A, with idempotent retries on every step so the patient never ends up with zero appointments.)Scaling, failure modes, and trade-off summary
Production footprint & failure handling - Postgres HA (
RPO = 0): 1 primary + 2 synchronous standbys in a quorum (synchronous_standby_names = 'ANY 1 (s1, s2)') so losing a single standby never stalls writes, plus 2 async read replicas behind PgBouncer.Failure Scenario Impact & Automatic Recovery ------------------------------------ ---------------------------------------------------------------------- Client drops connection before 201 App retries with same Idempotency-Key -> replays exact saved 201 JSON Booking pod crashes mid-transaction Postgres rolls back uncommitted work -> client retry runs cleanly Postgres Primary crashes Writes return 503 for ~15-30 s during promotion of sync standby; zero committed bookings lost (RPO = 0); client retries succeed CDC relay or Kafka cluster down Bookings still succeed! Outbox rows buffer safely on Postgres disk; alert if oldest unpublished outbox row > 30 seconds Redis shard down / cache cold Single-flight fallback queries async Postgres read replica using `slots_open_idx` with tighter rate limits until Redis recovers Delay-queue message lost Slot remains bookable in SQL via `hold_expires_at <= now()`; nightly cache reconciler treats expired holds as open and restores Redis ZSETCore trade-offs recap - Pre-materialized slot rows (
~19.2 GB) vs. dynamic intervals: Trades modest predictable storage and nightly horizon generation for single-row atomic locking, simpleslot_idaudit trails, and~5 msRedis sorted-set reads. - Database conditional updates vs. distributed locks: Keeps concurrency control inside the single system that already owns durable state, eliminating split-brain lease bugs and extra network round trips. - Strictly consistent primary writes vs. ~1s eventually consistent cached search: Protects100%against double-bookings while absorbing1,500+ QPSsearch spikes cheaply, turning rare cache lag into a fast409carrying ready-to-tap alternative times. - Transactional Outbox + CDC vs. dual writes or 2PC: Guarantees notifications and cache invalidations never diverge from committed bookings without putting third-party latency inside database locks.
Intuition & how it works
Think of scheduling doctors at scale like running a busy clinic reception desk paired with a fast lobby display board. Behind the desk sits one locked filing cabinet holding pre-materialized slots (individual database rows created ahead of time, one row per bookable 20-minute appointment window). Out in the waiting room, thousands of patients browse an electronic display board (OpenSearch for finding nearby specialists plus Redis Sorted Sets—in-memory lists sorted by start timestamp—for open times) that refreshes within a second so searches finish in under 150 ms without bothering the receptionist. Whenever two patients rush the desk for the 10:15 AM card at the exact same millisecond, the database settles the tie using one ACID transaction (a group of database writes that either all succeed together or all roll back together) with a conditional atomic update—flipping the card from AVAILABLE to BOOKED only if it is still AVAILABLE right now. Every write request also brings an idempotency key (a unique client-generated ticket ID saved alongside the frozen response so network retries replay the first receipt instead of booking twice) and drops outgoing notices into a Transactional Outbox (a database table committed in the exact same transaction and streamed out later so emails and cache updates are never lost).
Why do obvious designs fail under real contention and network hiccups? Reading a slot's status in application code (SELECT status) before updating it lets two concurrent requests both see AVAILABLE and double-book the doctor, while relying on an external Redis lock fails whenever a server pauses longer than its lock lease and lets a second writer enter. Sending confirmation texts or publishing to Kafka directly inside or right after the HTTP handler either blocks database locks on slow third-party APIs or silently drops notifications when a server crashes a millisecond after committing. Finally, implementing reschedules as "cancel old slot, then book new slot" leaves the patient with no appointment at all whenever someone else grabs the new slot first.
Let's trace Dr. Lin's 10:15 AM (slot 4101) and 10:35 AM (slot 4102) windows across four real-world events:
Step Event What happens inside the system
---- ----------------------------------------- --------------------------------------------------------------
1 Nora & Devon tap slot 4101 at 11:00:00.001 Nora's Postgres tx locks row 4101 first, flips AVAILABLE ->
(Nora key="kN", Devon key="kD") BOOKED (version 0 -> 1), writes appointment #8204 + audit row
+ outbox events, and saves 201 on "kN". Devon's tx unblocks,
sees status='BOOKED', updates 0 rows, returns 409 + [4102].
2 Nora's train Wi-Fi drops the 201 reply; INSERT into idempotency_keys hits conflict on (Nora, "kN");
her app retries with key="kN" server replays the exact saved 201 for #8204—no second booking!
3 150 ms later, async CDC relay reads WAL Debezium streams outbox rows to Kafka: Redis Lua script checks
(Postgres's internal change journal) version 1 > 0 and removes 4101 from avail:{14}; Notification
Service deduplicates event_id and sends Nora's confirmation.
4 Nora reschedules #8204 from 4101 -> 4102 Single tx locks (4101, 4102) in ID order: claims 4102 (BOOKED),
(or rolls back untouched if 4102 is gone) releases 4101 (AVAILABLE, version 2), and moves #8204 atomically.
Key trade-offs
- Pre-materialized slot rows (
~19.2 GB) vs. dynamic interval subtraction. Creating one row per bookable slot over a 90-day horizon (64Mrows) makes row-level locking,slot_idaudit trails, and Redis caching straightforward, at the cost of regenerating futureAVAILABLErows when a doctor edits their weekly template. Dynamic interval subtraction fits variable-length visits better, but requires heavier range-overlap queries on every search and booking; we still add a GiST exclusion constraint (a PostgreSQL spatial/range index rule preventing overlapping live time ranges per provider) so template edits can never overlap existing bookings. - Database conditional updates vs. distributed locks. Guarding reservations inside PostgreSQL (
FOR UPDATE/ conditionalUPDATE ... WHERE status = 'AVAILABLE') keeps concurrency control inside the single datastore that already owns durable truth, avoiding an extra network hop and lease-expiration race conditions in Redis or ZooKeeper. - Strictly consistent primary writes vs. eventually consistent cached reads. Deciding every hold, booking, and reschedule on one PostgreSQL primary backed by synchronous replication (waiting for at least one standby server in a 2-standby quorum to flush every commit before acknowledging
201) guarantees zero double-bookings and zero lost appointments, while serving1,500+ QPSsearches from OpenSearch and Redis (< 1 slag) keepsp99read latency well below150 ms. - In-transaction audit log vs. asynchronous outbox events. Writing
slot_eventsinside the booking transaction guarantees compliance history is never delayed or missing, whereas routing SMS/email and cache invalidations through the Transactional Outbox and Change Data Capture (CDC) (streaming committed database log entries to Kafka) keeps slow external vendors off the database lock path at the cost of at-least-once delivery (requiring consumers to deduplicate byevent_id). - Lazy hold expiration + delay queue vs. periodic cron sweeps. Treating
status = 'HELD' AND hold_expires_at <= now()as immediately claimable in SQL ensures correctness never depends on a background job running on time, while a 10-minute delayed message restores search cache visibility promptly without hammering the database with table scans.
Common mistakes
- Application-level check-then-act (
SELECT statusfollowed by unconditionalUPDATE). Under concurrency, two threads both readAVAILABLEbefore either writes, causing classic double-bookings. - Relying on a Redis distributed lock without a database-level guard. Process garbage-collection pauses or clock drift can let a Redis lock expire mid-request so two workers write to the database concurrently.
- Storing idempotency keys in Redis separately from the Postgres transaction, or skipping
409responses. Separate stores create crash windows where a booking commits without its key (or vice versa), and failing to cache deterministic409responses breaks strict idempotency on retries. - Calling Twilio/SendGrid or
kafka.producedirectly inside or after the transaction. Calling inside holds row locks during slow network I/O and sends texts for transactions that later roll back; calling after without an outbox silently drops messages if the server crashes right afterCOMMIT. - Unversioned cache invalidation. A bare
ZREM/ZADDwithout checkingslot.versioninside a Redis Lua script (an atomic server-side check in Redis) allows a delayed Kafka message or a lagging read-replica cache rebuild to put an already-booked slot back into search results. - Locking two slots in arbitrary order during rescheduling. Locking
old_slotthennew_slotdeadlocks whenever two concurrent requests swap the opposite direction; always lock in ascendingslot_idorder (ORDER BY slot_id FOR UPDATE). - Generating future slots in UTC instead of provider-local time. Materializing templates without converting each calendar date through the clinic's IANA time zone (
America/New_York) shifts appointments by an hour across Daylight Saving Time transitions.
Follow-up questions
- How would you support a 10-minute checkout hold—for instance, while a patient enters insurance details—that releases automatically on timeout without relying on a periodic database-polling job? Separate correctness from cache cleanup: store
status = 'HELD'andhold_expires_at = now() + interval '10 minutes'on theslotsrow, and write every booking query sostatus = 'HELD' AND hold_expires_at <= now()is immediately claimable (lazy expiration)—meaning an expired hold never blocks another patient even with zero background jobs. To restore the abandoned slot in Redis search and write theHOLD_EXPIREDaudit event without polling, the hold transaction writes aHoldCreatedoutbox event that pushes a message to a native delay queue (such as AWS SQS withDelaySeconds = 600, inside its 900-second limit). When the message delivers 10 minutes later, a worker runs an idempotent conditional update (WHERE slot_id = :id AND claim_id = :hold_id AND status = 'HELD' AND hold_expires_at <= now()); if the patient already confirmed, zero rows change, and otherwise the slot cleanly flips back toAVAILABLE(avoid Redis keyspace TTL pub/sub events, which drop messages whenever a subscriber disconnects). - Suppose availability queries surge to 50,000 QPS. How would you serve cached slot data from Redis while keeping patients from frequently clicking slots that were just taken? At 20 providers per search page,
50,000 QPSgenerates~1,000,000sorted-set range reads per second, so shard Redis Cluster by{provider_id}with read replicas, add a 1-second in-memory cache insideSearchServicepods for the hottest 1% of doctors, and protect cold-key rebuilds with single-flight (coalescing concurrent misses for the same provider into one database replica query). Minimize stale views by hiding slots as soon as they enterHELD, running a best-effort synchronous write-through afterCOMMITbacked by the versioned Lua script (availv:{provider_id}) so out-of-order Kafka events or lagging replicas can never resurrect booked slots, and performing a lightweight live check against the Redis primary when a user taps a slot to open the booking screen. Track the409 Conflictrate on search-originated clicks and shorten the in-process TTL if it rises above1%. - When a patient moves an existing visit from slot A to slot B, how do you make the switch atomic so their original slot A stays intact whenever claiming slot B fails? Because
50 QPSwrites and~19.2 GBof slots fit comfortably on one PostgreSQL primary, execute the reschedule inside a single ACID transaction: lockslot_aandslot_bin ascendingslot_idorder (FOR UPDATE) to prevent deadlocks, attempt to claimslot_bfirst, and immediatelyROLLBACKreturning409ifslot_bis unavailable—leavingslot_aand the patient's existing appointment completely untouched. Only afterslot_bis secured does the transaction releaseslot_a, updateappointments.slot_id = :slot_b, append audit rows, and write outbox events before committing. If 100x future scale ever shards slots across multiple databases byprovider_id, replace the single transaction with a make-before-break saga (a sequence of local transactions with compensating retries: holdslot_b-> confirmslot_b-> releaseslot_a), so a failure onslot_bstill leavesslot_asafe and a temporary mid-saga crash briefly holds two slots rather than zero.
Follow-up questions
- How would you support a 10-minute checkout hold—for instance, while a patient enters insurance details—that releases automatically on timeout without relying on a periodic database-polling job?
- Suppose availability queries surge to 50,000 QPS. How would you serve cached slot data from Redis while keeping patients from frequently clicking slots that were just taken?
- When a patient moves an existing visit from slot A to slot B, how do you make the switch atomic so their original slot A stays intact whenever claiming slot B fails?
Similar questions
- Healthcare Appointment Scheduling Architecture Under Flash-Crowd Traffic
- 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