Healthcare appointment booking without double-booking

Design a booking platform for 3,000 clinics: patients book slots in a mobile app, practitioners manage availability in a partner app, and a…

Ready45:00
ClarifyEstimateHigh-level designDeep diveTrade-offs and wrap-up
Start the clockReset Practice mode
Part 1 of 5

Basics

Start with the product and the ideas it depends on. If these are clear, the design that follows will feel obvious rather than memorised.

1.1Product in plain words

Who uses it, what a normal day looks like, and why it is harder than it seems.

A platform where patients book appointments at clinics, practitioners manage their availability, and clinic admins configure services and hours. Popular slots open at 9 a.m. and are gone within seconds.

Who uses it

  • Patients: book from the app, often for a specific practitioner.
  • Practitioners: check their day on a partner app, sometimes without signal in treatment rooms.
  • Clinic admins: set hours, services and prices on a web dashboard.

A day in the life

  1. At 8:59 she opens Dr Rao’s calendar; Thursday’s slots show as opening at 9:00.
  2. At 9:00:01 she taps 10:30; the app holds it for five minutes and shows a countdown.
  3. Another patient who tapped the same slot a moment later sees ‘Just taken, 11:00 is free’.
  4. She confirms and pays a deposit; the booking appears in both apps.
  5. Dr Rao’s partner app, which synced the day’s schedule earlier, shows the new patient.

Why it is hard

Thousands want one slot

Exactly one person may get it, instantly and fairly.

Holds must expire

Abandoned checkouts must release slots automatically.

Time zones

A 10 a.m. appointment is 10 a.m. at the clinic, wherever the patient is.

Health privacy

Who visits which clinic is sensitive; clinical notes even more so.

Think of it like this

Like a theatre box office that puts a ticket aside for five minutes while you get your wallet out. If you walk away, it goes back on sale.

1.2Key concepts

The building blocks this design uses. Each one appears again in the answer.

01Contention

Thousands of patients try to take the same slot at 9 a.m. Exactly one may win, even when requests arrive in the same millisecond.

02Conditional writes

Book with an update that only succeeds if the slot is still free, or a unique constraint on the slot id. The database picks the winner atomically.

03Short holds

While the patient enters details, the slot is held for a few minutes, then released automatically if they give up.

04Time zones

Store times in UTC together with the clinic's IANA time zone, and display them in the clinic's local time. Otherwise daylight-saving changes move appointments.

05Read model for search

Availability search reads a copy built for fast queries. It may be seconds behind; the final booking check always runs on the source of truth.

06Health data

Appointment details are sensitive: encrypt them, limit who can see them, log every access and keep them out of notification text.

Learn them properly in the deep dives:

Part 2 of 5

Question

Now read the question closely. Agree on what you are building, ask what is unclear, and work out the numbers before you draw anything.

2.1Brief and scope

The question exactly as the interviewer asks it, and what they want to learn from your answer.

Interviewer

Design a booking platform for 3,000 clinics: patients book slots in a mobile app, practitioners manage availability in a partner app, and admins configure clinics in a web dashboard. Popular slots open at 9 a.m. and sell out in seconds. Health data must be protected.

What it tests: Concurrency under contention, holds and expiry, time zones, notifications and health-data privacy.

The answer in one sentence. Slot rows with capacity, an atomic conditional update to place a short hold, confirmation as a second idempotent step, and audit on every change.

How to spend the 45 minutes

  1. Clarify~5 minAsk questions, agree on scope and write down assumptions.
  2. Estimate~5 minRough numbers for users, data and traffic, and what they imply.
  3. High-level design~11 minComponents, data flow and the key API on the board.
  4. Deep dive~16 minThe two or three hardest parts, with real mechanisms.
  5. Trade-offs and wrap-up~9 minDecisions, failure modes, and what you would do next.

2.2Clarify the problem

The first five minutes. Each answer removes a guess from your design.

Your turn: Before drawing anything, list the questions you would ask the interviewer.Reveal model answer
You askInterviewer answers
Can a slot hold more than one patient?Most hold one; group sessions hold up to 20.
Payment at booking?Optional deposit for some clinics.
Offline needs?Practitioners must see today’s schedule without signal.
Regions and time zones?Several cities across time zones; the clinic’s zone is authoritative.

2.3Estimate the scale

Say the arithmetic out loud. What matters is the order of magnitude and what it forces you to do.

Your turn: Write down the numbers that will drive the design.Reveal model answer
MetricEstimateHow
Clinics3,000
Bookable slots≈ 1.5M/week3,000 × 10 practitioners × 50 slots
Peak booking attempts≈ 2,000/s9 a.m. release spikes
Successful bookings≈ 200k/day
Part 3 of 5

Detailed answer

The design itself, from the big picture down to the code: components first, then one request end to end, then the parts interviewers push hardest on.

3.1Architecture

Three apps share one booking core. The core turns contention into a short hold, then a confirmation, with every transition recorded for audit.

Your turn: Sketch the components and arrows, then compare.Reveal model answer
APPSBOOKING COREPLATFORMPatient appsearch · bookPartner appschedule offlineAdmin webclinic configBooking APIholds · confirmAvailabilityslot generatorNotificationsSMS · pushPostgresslots · bookingsRedisslot countsAudit logappend-onlyPaymentsdepositsCalendar syncGoogle · OutlookQueueremindersbookhoursupdatecountsdepositauditbooked
ClientServiceData storeQueue / streamExternal
Reference design. Boxes show components; arrows show who calls whom.
Slot model
Availability rules (weekly hours, breaks, leave) generate concrete slot rows ahead of time. Each slot row has capacity, booked count and a version.
Holds
Booking starts by placing a hold that expires in five minutes, decrementing remaining capacity atomically. Confirming converts the hold; expiry releases it.
Read path
Search hits a Redis cache of slot counts, and every change updates it. It may be a second stale; the database write is the real arbiter.
Partner app offline
Practitioners sync today’s and tomorrow’s schedule into SQLite. Changes they make offline are proposals that the server validates.
Audit and privacy
The system logs every view and change of a patient record. Health details live in a separate, encrypted service with stricter access than the booking data.

3.2Key flow, step by step

Two patients tap the same last slot at 9:00:00.

Your turn: Narrate one request end to end.Reveal model answer
Patient APatient BBooking APIPostgresNotificationshold slot 77hold slot 77UPDATE … WHERE remaining > 01 row (A wins)UPDATE … WHERE remaining > 00 rowsheld until 9:05taken · next free 9:30confirm holdhold → bookingsend confirmation
Solid arrows are requests; dashed arrows are responses.
  1. The database decides with a single conditional update, so no read-then-write race can occur.
  2. The loser gets an immediate, helpful answer: the next available slot, not just an error.
  3. Confirmation is a second, idempotent step; abandoning the screen lets the hold expire.

3.3Front end

Three front ends serve this product: the patient app, the partner app and the admin web dashboard. Each has a different job, but all must show availability honestly and react gracefully when someone else got there first.

Your turn: Sketch the screens, the client layers and every UI state the user can see.Reveal model answer

Screen map

Find careservice · areaPractitionerprofile · reviewsSlot pickerdate strip · timesHold + confirmcountdown · depositPartner: my dayoffline schedulePartner: visitcheck-in · notesAdmin: hoursweekly editorMy bookingsreschedule · canceltap slotconfirmedpublishes
Client
Screens and how users move between them.
Slot picker
A horizontal date strip and a grid of time chips. Availability comes from a cached count that can be a second stale; the hold request is the real check.
Hold + confirm
A visible five-minute countdown based on the server’s expiry time, not the device clock. Leaving the screen keeps the hold until it expires.
Partner app: my day
The app syncs today and tomorrow into SQLite, so the schedule opens without signal. Edits are proposals the server validates.
Admin: weekly hours
A React drag-to-select weekly grid that edits availability rules, with a preview of generated slots and warnings for existing bookings.

Client layers

LayerTechnologyResponsibility
Patient appReact Native or nativeSearch, slot picker, hold flow, my bookings
Partner appNative with local DBOffline day view, check-in, notes
Admin webReact + TanStack QueryAvailability rules, services, reports
Real-timeWebSocket or polling for open slot screensMark slots taken while the user is looking
TimeClinic IANA zone on every slotFormat in clinic time with the zone shown

Every state the user can see

StateWhat the user seesHow it works
Opening soonSlots greyed with ‘Opens at 9:00’Server release time
AvailableTime chip enabledRemaining capacity above zero
Just takenChip shakes, next free slot highlightedHold returned zero rows
HeldCountdown ‘Held for 4:32’Hold expiry from server
Hold expired‘This slot was released’ with Try againCountdown reached zero
BookedConfirmation with add-to-calendarHold converted

Code

Hold with a server-based countdown (React Native)

hold-serverbased-countdown.tsxTypeScript JSXCopy
1function HoldTimer({ expiresAt, serverOffsetMs, onExpire }: Props) {2  const [left, setLeft] = useState(() => expiresAt - (Date.now() + serverOffsetMs));3  useEffect(() => {4    const t = setInterval(() => {5      const ms = expiresAt - (Date.now() + serverOffsetMs);   // server time, not the phone's clock6      setLeft(ms);7      if (ms <= 0) { clearInterval(t); onExpire(); }8    }, 1000);9    return () => clearInterval(t);10  }, [expiresAt, serverOffsetMs]);11  const s = Math.max(0, Math.round(left / 1000));12  return <Text accessibilityLiveRegion="polite">Held for {Math.floor(s / 60)}:{String(s % 60).padStart(2, '0')}</Text>;13}14 15async function onTapSlot(slot: Slot) {16  const res = await api.hold(slot.id, { idempotencyKey: holdKey(slot.id) });17  if (res.status === 'taken') { haptics.warning(); showNext(res.nextFree); return; }18  navigation.navigate('Hold', { holdId: res.holdId, expiresAt: res.expiresAt });19}
19 linesUTF-8TypeScript JSX

Admin availability editor data flow (React + TanStack Query)

admin-availability-editor.tsxTypeScript JSXCopy
1const rules = useQuery({ queryKey: ['rules', clinicId], queryFn: () => api.rules(clinicId) });2const save = useMutation({3  mutationFn: (next: Rules) => api.saveRules(clinicId, next, rules.data!.version),   // optimistic concurrency4  onError: (e: ApiError) => { if (e.status === 409) toast('Someone else changed these hours. Reloading.'); },5  onSettled: () => queryClient.invalidateQueries({ queryKey: ['rules', clinicId] }),6});
6 linesUTF-8TypeScript JSX

3.4Data model and APIs

The tables and contracts that make the design concrete.

Your turn: Write the schema or contract you would put on the board.Reveal model answer

Atomic hold

atomic-hold.sqlSQLCopy
1UPDATE slot2   SET remaining = remaining - 1, version = version + 13 WHERE id = $1 AND remaining > 04RETURNING version;5 6INSERT INTO hold (id, slot_id, patient_id, expires_at)7VALUES ($2, $1, $3, now() + interval '5 minutes');
7 linesUTF-8SQL

Expiry sweeper

expiry-sweeper.sqlSQLCopy
1WITH expired AS (2  DELETE FROM hold WHERE expires_at < now() AND confirmed = false3  RETURNING slot_id)4UPDATE slot s SET remaining = remaining + c.n5FROM (SELECT slot_id, count(*) n FROM expired GROUP BY slot_id) c6WHERE s.id = c.slot_id;
6 linesUTF-8SQL

3.5Tested code, explained

The core of this design as working code, with what each part does and why.

Holding a popular slot

At 9 am thousands of people want the same slot. One conditional update solves this without a lock service.

SlotBooking.ktKotlinCopy
1data class Slot(val capacity: Int, var held: Int = 0, var booked: Int = 0)2data class Hold(val id: String, val slotId: String, val expiresAtMs: Long, var confirmed: Boolean = false)3 4/**5 * Each method stands for one conditional UPDATE, such as:6 * UPDATE slot SET held = held + 1 WHERE id = ? AND held + booked < capacity7 * The row is the lock, so there is nothing separate to forget to release.8 */9class SlotBooking(private val slots: Map<String, Slot>, private val holdMs: Long = 120_000) {10  private val holds = HashMap<String, Hold>()11 12  @Synchronized13  fun hold(requestId: String, slotId: String, nowMs: Long): Hold? {14    holds[requestId]?.let { return it }                 // a retry returns the same hold15    expire(nowMs)16    val slot = slots.getValue(slotId)17    if (slot.held + slot.booked >= slot.capacity) return null18    slot.held += 119    return Hold(requestId, slotId, nowMs + holdMs).also { holds[requestId] = it }20  }21 22  @Synchronized23  fun confirm(holdId: String, nowMs: Long): Boolean {24    expire(nowMs)25    val h = holds[holdId] ?: return false26    if (h.confirmed) return true                        // confirming twice is fine27    val slot = slots.getValue(h.slotId)28    slot.held -= 129    slot.booked += 130    h.confirmed = true31    return true32  }33 34  private fun expire(nowMs: Long) {35    val dead = holds.values.filter { !it.confirmed && it.expiresAtMs <= nowMs }36    for (h in dead) {37      slots.getValue(h.slotId).held -= 138      holds.remove(h.id)39    }40  }41}
41 linesUTF-8Kotlin
slot.held + slot.booked >= slot.capacity
The condition in the UPDATE. The database applies it atomically, so two people can't both take the last place.
holds[requestId]?.let { return it }
A retried hold returns the same hold, so a flaky network can't take two places.
expire(nowMs)
An abandoned hold frees its place automatically.
if (h.confirmed) return true
Confirming twice is fine, and books once.

Compiled and tested by npm run test:mobile.

3.6Hard parts, in depth

Where interviewers spend the second half of the round.

Your turn: Pick two areas the interviewer will push on and explain them.Reveal model answer

Why not a distributed lock

A lock service adds a network hop and a failure mode. A conditional update in the same database that stores the slot is atomic, fast and impossible to forget to release.

For extreme spikes, put a short queue in front of the hottest clinics so requests are applied in order, and return position-in-line feedback.

Time zones

Store slot times in UTC plus the clinic’s IANA zone. Render in the clinic’s zone, because a 10 a.m. appointment is 10 a.m. where the clinic is, even if the patient is travelling. Handle daylight-saving transitions when generating slots, not when displaying them.

Protecting health data

Keep booking data (who, when, which clinic) separate from clinical notes. Clinical notes require stricter roles and separate encryption keys, and audits cover every access. The patient app caches only what it needs and clears it on sign-out.

Part 4 of 5

Q&A

The questions that come after the design, with model answers. Answer each one out loud before opening it.

4.1Follow-up questions

What the interviewer asks once the main design is on the board.

How do group sessions change the design?
Capacity is just higher; the same conditional update works. Waitlists become a queue per slot that promotes on cancellation.
How do you handle no-shows?
Deposits, reminders 24 hours and 2 hours before, and a configurable penalty policy per clinic.
What would you log for compliance?
Who accessed which patient record, when, from which app and why, in an append-only store with retention rules.

4.2Front-end follow-ups

Questions aimed at the client: rendering, state and devices.

Why base the countdown on server time?
Phone clocks can be minutes off. The app computes an offset from server response headers and counts down to the server’s expiry.
How do you stop users seeing slots that are already gone?
Short-lived cached counts, live updates while the picker is open, and graceful handling of ‘just taken’ with the next free slot.

4.3Incidents, probes and traps

Realistic production incidents and pointed probes, grouped by topic.

The product 1

ProbeWhy not let whoever pays first get the slot?
Several people would pay and then be told the slot is gone, causing refunds and anger. A short hold gives one person a fair window and everyone else an instant ‘taken’ with an alternative.
I can answer this

Requirements 1

TrapWhich clarifying question changes the data model?
Whether slots can hold more than one person (group sessions and waitlists). Capacity counts, waitlist queues and partial cancellations follow from that answer.
I can answer this

Scale 1

Probe2,000 attempts a second on a few hot slots. What is the bottleneck?
Row-level contention on the same slot rows, not overall throughput. Keep the hold a single short statement, keep transactions tiny, queue requests per hot clinic, and answer losers immediately.
I can answer this

Architecture 2

IncidentAt 9 a.m. database CPU hits 100% and bookings time out.
Search traffic is hitting the primary, connection pools are exhausted and hot rows are contended. Serve search from Redis and replicas, put PgBouncer in front, rate-limit per user and pre-warm caches before release time.
I can answer this
ProbeWhy keep clinical notes in a separate service?
Least privilege, separate encryption keys, stricter audit and a smaller compliance scope. Most of the platform only needs who, when and where, not clinical details.
I can answer this

The key flow 1

IncidentTwo patients ended up booked into the same single slot.
The code read the remaining count and wrote later, or confirmation did not check that the hold was still valid. Use one conditional update for the hold, check hold validity and expiry inside the confirm transaction, and add a unique constraint on slot and seat.
I can answer this

Front end 2

IncidentPatients travelling abroad arrive an hour late.
The app showed times in the device’s time zone. Always display in the clinic’s zone with the zone named, store UTC plus the IANA zone, and generate slots with daylight-saving rules on the server.
I can answer this
ProbeHow should the UI handle ‘just taken’?
A light haptic, the chip marked taken in place, and the next free slot highlighted, keeping the user’s scroll position. No blocking error dialog.
I can answer this

Data and APIs 1

TrapWhy must the capacity decrement and hold insert share a transaction?
If the app crashes between them, capacity is reduced with no hold to expire, and the slot disappears until someone fixes it by hand.
I can answer this

The hard parts 2

IncidentThe hold sweeper stopped after a deploy and slots vanished all afternoon.
Leader election failed, so no instance ran the sweeper. Alert on the age of the oldest unconfirmed hold, and also treat expired holds as free at read and write time, so correctness never depends on the sweeper alone.
I can answer this
ProbeHow do you build a fair waitlist?
A queue per slot. On cancellation, offer the slot to the first person with a short time-limited hold and a notification; if it expires, move to the next. Record every step for support.
I can answer this

Trade-offs 1

ProbeWhy not use a distributed lock such as Redlock?
It adds a network hop and failure modes such as locks expiring during long pauses. A conditional update in the database that owns the slot is atomic and cannot leak a lock.
I can answer this

Failures 2

IncidentEvery patient received each SMS reminder twice.
The notification worker retried after a timeout without idempotency. Use a dedupe key per booking and reminder type, and record provider message IDs.
I can answer this
IncidentAn admin deleted availability that already had bookings.
The server must reject changes that affect existing bookings, show the impacted patients, and offer a guided reschedule flow with notifications.
I can answer this
Part 5 of 5

Extra depth

What turns a good answer into a strong one: the decisions you rejected, how the system fails, and the signals of seniority.

5.1Trade-offs and decisions

Every choice has a cost. Naming it is what interviewers listen for.

Your turn: State each decision, the alternative you rejected and why.Reveal model answer
Show detailsHide details
DecisionChosenRejectedWhy
Contention controlConditional update + hold TTLDistributed lockAtomic in one store; no lock to leak.
Search freshnessRedis counts, eventually consistentQuery DB per searchSearch volume far exceeds bookings; the write path is still exact.
Offline practitionersRead schedule offline, propose changesFull offline editingAvoids conflicts with patient bookings made meanwhile.
NotificationsQueue with retries and channelsInline SMS callProviders fail; reminders must not block booking.

5.2Failure modes

What breaks in production, and how the design keeps working when it does.

Your turn: List what breaks and how the system degrades.Reveal model answer
Show detailsHide details
What breaksHow the design copes
Hold sweeper stopsExpired holds keep slots unavailable; alert on hold age and run sweeper with leader election.
Practitioner deletes a slot with a bookingServer rejects; partner app shows the conflict and offers to reschedule the patient.
SMS provider downFail over to a second provider and push; mark reminder delivery state.
Thundering 9 a.m. spikePre-warm caches, rate-limit per user, queue per hot clinic.

5.3Performance and accessibility

The client-side details that separate a demo from a product.

Performance

  • Prefetch the next seven days of slot counts when a practitioner page opens.
  • Keep the hold request tiny so it wins races on slow networks.
  • The partner app’s day view reads only local data and opens in under a second.

Accessibility and localisation

  • Time chips announce date, time and availability.
  • The countdown is a polite live region, not a constantly interrupting announcement.
  • All times show the clinic’s time zone when it differs from the device.

5.4Senior versus principal

The same design, answered at two levels. Use the rubric to score yourself.

Senior answer

A senior answer prevents double-booking with a transaction.

Principal answer

A principal answer explains holds and expiry, avoids distributed locks, handles 9 a.m. spikes, gets time zones right, separates health data and designs notifications as a reliable pipeline.

Score yourself

Requirements Asked clarifying questions and stated assumptions. Numbers Estimated scale and used it to make a decision. Architecture Clear components with responsibilities and data flow. Depth Went deep on the hardest part with real mechanisms. Trade-offs Named alternatives and why they lost. Operations Covered failures, monitoring and rollout. Leadership Explained how the team would build and evolve it.

5.5Whiteboard

Draw the design here, in this order. It stays in this browser.

  1. Three apps feeding one booking core
  2. Slot row with capacity and version
  3. Hold → confirm state with TTL
  4. Race diagram: two patients, one conditional update
  5. Audit log and separate health-data store
PenBoxArrowTextEraserUndoClear
Tip: draw boxes first, then arrows, then label them with Text.