Design a Multi-Calendar Availability and Scheduling Service
Medium · System Design · Software Engineer · Other
Prompt
Design an availability and meeting-scheduling backend. Given a group of people, a date-time range, and a target meeting length, the service identifies open time slots so an application can suggest meeting times across teammates or let external guests reserve a slot on a personal booking link. Participants keep their day-to-day schedules inside third-party calendar platforms connected to your product.
Establish scope and confirm any open product rules with the interviewer up front:
- Connected accounts: Each person links multiple third-party calendar accounts (for instance, Google Workspace or Microsoft 365 / Outlook). Clarify whether the platform also hosts standalone native calendars or only tracks external busy blocks plus bookings created through your service.
- Availability queries: Callers pass attendees, a search window, and a meeting duration, receiving candidate slots in which every required attendee is free and within their configured working hours in their local time zone.
- Product surfaces & event semantics: Clarify whether the design serves internal colleague scheduling, public 1-on-1 booking links, or both; how quickly edits made in external calendars must appear; how tentative replies, declined invitations, transparent entries, and all-day events should be treated; and whether the service reserves selected slots and writes confirmed events back to external calendars.
Scope & Expectations
- Time modeling & slot-finding algorithm: Represent instants, local working hours, time zones, and daylight-saving transitions unambiguously; combine busy periods, buffers, recurring series, and optional invitees to produce candidate slots; and state time/space complexity alongside a concrete example.
- External calendar synchronization: Justify querying providers on demand versus maintaining a synchronized local store, and detail initial imports, change notifications, incremental sync cursors, staleness bounds, provider rate quotas, revoked credentials, and data minimization.
- Concurrency-safe booking & horizontal scale: Guarantee that two people clicking the same slot simultaneously cannot double-book a host, reliably write events back to external calendars while handling conflicts or provider downtime, and partition and cache data for high-traffic booking pages.
Step-by-step walkthrough
Clarify requirements and scope
Finding free time for a group sounds simple at first: put everyone's meetings on a timeline and look for empty spaces. What turns this into a real distributed systems problem are three realities outside that loop:
- People live in different time zones that switch to and from daylight saving time (DST) on different dates.
- Their calendars live inside third-party providers (such as Google Calendar and Microsoft Outlook) behind strict rate limits and occasional outages.
- Showing an open 1:00 p.m. slot on a web page does not stop two visitors from clicking "Book" at the exact same millisecond.
Functional requirements
- External calendar connections: people link multiple third-party calendar accounts (Google Calendar, Microsoft Outlook). Our service also tracks its own bookings, without trying to build a full standalone calendar app.
- Group availability query: given a list of participants (marked required or optional), a target date range, and a requested call length, return candidate start times where every required participant is free and within their working hours.
- Public booking pages: a host publishes a link (for example,
/book/maya-30m); an external visitor views open slots and books one, locking that window and pushing a confirmed invite onto the host's external calendar. - Scheduling rules: per-user working hours in their local time zone, breathing-room buffers (padding minutes before or after meetings), minimum advance notice, maximum booking horizon (such as 60 or 90 days ahead), and which connected calendars count as busy.
Non-functional requirements
- Low latency: availability queries finish in under 300 ms at p99 (the 99th percentile, meaning 99 out of 100 requests are faster than 300 ms), and public booking pages load in under 200 ms p99 from cache.
- Bounded freshness: an edit made in Google or Outlook normally reflects in our service within ~1 minute, and every query response reports how fresh each participant's calendar copy is.
- Zero internal double-bookings: two bookings made through our service for the same host can never overlap. Conflicts with events created directly inside the external provider are minimized via a live check at booking time and detected automatically if they occur.
- Fault isolation: if one provider is down or one user revokes OAuth access, only that user's freshness degrades — the rest of the service stays healthy.
Baseline product rules confirmed up front
- Supported workflows: Both internal multi-colleague scheduling and external 1-on-1 booking links.
- Busy-status rules: Declined invites and entries marked
"free"(transparent) do not block availability. Tentative replies block time by default (per-user setting). All-day entries block time only when marked busy or out-of-office by the provider, avoiding false blocks from birthday or holiday reminders. - Event write-back: Public booking links atomically lock the chosen slot and push the confirmed event to the host's calendar; internal group scheduling proposes candidate times and dispatches the calendar invitation once the organizer confirms.
Back-of-the-envelope numbers
Before picking an architecture, let's estimate traffic and storage — and compare querying external calendar APIs live on every read against maintaining a synchronized local mirror.
Scale assumptions users & calendars 5M users x 1.5 calendars/user = 7.5M connected calendars calendar edits ~10 changes/user/day -> 50M changes/day (~580/s avg, ~2,000/s peak) stored horizon rolling 90 days ahead (~400 busy intervals per calendar) busy-interval storage 7.5M x 400 = 3B rows x ~60 bytes = ~180 GB raw (+ indexes & 3x replicas) Read & booking traffic availability reads 100M/day (group queries + booking page loads) -> ~1,160 reads/s avg, ~4,000 reads/s peak completed bookings 2M/day -> ~23 bookings/s avg, ~100/s peak (spiky on popular pages) Option A: ask external providers live on every read provider API calls 100M reads/day x ~3 participants = 300M calls/day (~12,000/s peak) query latency slowest of ~3 external HTTPS calls (100-500 ms each, worse at p99) hot booking page link shared in a newsletter -> 200 views/s = 200 API calls/s on ONE host's OAuth token -> immediately trips per-user provider rate limits availability 1 provider slow or down out of 5 colleagues -> whole query fails Option B: keep a synchronized local copy of busy intervals webhook-triggered syncs <= 50M/day (coalesced when multiple edits arrive together) safety polling 1M booking-page hosts every 30 min = 48M/day 6.5M other calendars every 6 hours = 26M/day horizon roll + live book ~5M/day (weekly horizon extension + 1 live check per booking) total provider calls ~130M/day steady, completely decoupled from read spikes! In-memory interval math 5 participants x 1 week ~5 x (25 meetings + 8 off-hours blocks) = ~165 intervals sorting + merging 165 intervals takes < 50 microseconds of CPUThree design decisions fall straight out of these numbers:
- Synchronize locally instead of querying providers live on reads: live lookups fail on viral booking pages (where 200 visitors/s hammer a single host's per-user provider quota) and make multi-person queries only as fast and reliable as the slowest external API.
- Busy-interval storage is modest: storing only start/end timestamps (~180 GB) fits comfortably in a sharded relational database with hot weeks cached in memory.
- Interval math is practically free: CPU time for merging 165 intervals is microseconds, so network I/O and database layout — not algorithm micro-optimizations — govern latency.
API design
Every timestamp sent over the network uses UTC (Coordinated Universal Time, the single global reference clock without daylight saving shifts), while local working-hour rules carry an IANA time zone name such as
America/New_YorkorEurope/London(a standard identifier from the global time zone database that knows all historical and future daylight saving rules for that region). Booking mutations require an idempotency key — a unique UUID generated by the client before sending a request so that retrying after a network timeout returns the original booking instead of creating a duplicate.POST /v1/availability/query request: { participants: [{user_id: "u_maya", required: true}, {user_id: "u_lukas", required: false}], window: {start: "2026-03-17T00:00:00Z", end: "2026-03-22T00:00:00Z"}, organizer_tz: "America/New_York", duration_min: 30, step_min: 15, max_results: 20 } 200 OK: { slots: [{start: "2026-03-17T13:00:00Z", end: "2026-03-17T13:30:00Z", optional_free: ["u_lukas"]}], data_as_of: {u_maya: "2026-03-17T10:02:11Z", u_lukas: "2026-03-17T09:58:04Z"}, warnings: [{user_id: "u_lukas", code: "calendar_stale", as_of: "..."}] } GET /v1/pages/{slug}/slots?from=2026-03-17T00:00:00Z&to=2026-03-24T00:00:00Z 200 OK: {slots: ["2026-03-17T13:00:00Z", ...], duration_min: 30, generated_at: "...", ttl_s: 60} POST /v1/bookings header: Idempotency-Key: 7d4e9a12-3b8c-4f10-9c55-20a8e614d9f1 request: {page_id: "pg_18", start: "2026-03-17T13:00:00Z", invitee: {name: "Noah", email: "noah@example.org", time_zone: "Europe/Berlin"}} 201 Created: {booking_id: "bk_74", status: "confirmed", start: "...", end: "..."} 409 Conflict: {error: "slot_unavailable", alternatives: ["2026-03-17T13:15:00Z", "2026-03-17T15:30:00Z"]} PUT /v1/users/{id}/working-hours request: {time_zone: "America/New_York", rules: [{days: ["MON","TUE","WED","THU","FRI"], start: "09:00", end: "17:00"}]} GET /v1/connections/{provider}/authorize -> OAuth redirect + initial sync + webhook setup POST /v1/providers/{provider}/notifications -> inbound webhook endpoint for calendar changesNotice two intentional details in these contracts:
data_as_ofandwarningsmake staleness transparent: because our database is a synchronized mirror of external systems, callers can show "Updated just now" or warn "u_lukas's calendar was last synced 2 hours ago."- Slot listings are hints, while
POST /v1/bookingsis the promise: if someone grabs a slot a split second before you click,POST /v1/bookingsreturns409 Conflictalong with fresh alternative slots so the UI can recover in one screen without reloading.
Data model and unambiguous time representation
Represent every concrete time range as a half-open interval
[start_utc, end_utc)— an interval that includesstart_utcand excludesend_utc. With half-open intervals, a10:00–10:30meeting[10:00, 10:30)and a10:30–11:00meeting[10:30, 11:00)share the boundary point10:30without overlapping (10:30 < 10:30is false), so back-to-back meetings work with zero±1 secondhacks.Never store a user's time zone as a fixed numeric offset like
-05:00. New York isUTC-5in January (09:00local =14:00 UTC) andUTC-4in July (09:00local =13:00 UTC). Instead, store local rules ("09:00"to"17:00"plus"America/New_York") and convert each specific date to UTC using the IANA zone database.users (user_id PK, home_tz, tentative_is_busy, buffer_before_min, buffer_after_min) working_hours (user_id, weekday 0..6, local_start "09:00", local_end "17:00", time_zone) connections (connection_id PK, user_id, provider, encrypted_token_ref, status ACTIVE|DISCONNECTED, last_error) calendars (calendar_id PK, connection_id, provider_cal_id, counts_as_busy, time_zone, sync_cursor, webhook_id, webhook_expires_at, last_synced_at, version) busy_intervals (calendar_id, provider_event_id, instance_start_utc, start_utc, end_utc, kind BUSY|TENTATIVE|OOO) PRIMARY KEY (calendar_id, provider_event_id, instance_start_utc) INDEX (calendar_id, start_utc, end_utc) booking_pages (page_id PK, host_id, slug UNIQUE, duration_min, step_min, buffer_before_min, buffer_after_min, min_notice_min, horizon_days) reservations (reservation_id PK, host_id, starts_at, ends_at, blocked tstzrange, status HELD|CONFIRMED|CANCELLED|EXPIRED, hold_expires_at, idempotency_key UNIQUE, provider_event_id, page_id, invitee_json) outbox (outbox_id PK, reservation_id, action CREATE|CANCEL, attempts, next_attempt_at)Key data-modeling choices:
- Privacy-by-minimization:
busy_intervalsstores only timestamps, busy status, and event IDs — never meeting titles, descriptions, locations, or attendee emails. That shrinks storage several-fold and eliminates the privacy risk of mirroring sensitive company calendars. - Expanded recurring instances over a 90-day window: recurrence rules (
RRULE, exception dates, shifted single instances, and DST interactions) are notoriously bug-prone to evaluate from scratch. Both Google (singleEvents=true) and Microsoft (calendarView) expand recurring series on their side, so we store concrete instances over[now - 1 day, now + 90 days]. - All-day events: providers return all-day events as local calendar dates (
2026-03-16), not UTC instants. At sync time, if the event is marked busy/out-of-office, we convert[2026-03-16 00:00, 2026-03-17 00:00)in that calendar's IANA time zone to UTC. - Monotonic
calendars.version: incremented on every sync transaction so caches keyed by(user_id, week, version)automatically become obsolete on change.
- Privacy-by-minimization:
High-level architecture
Separate the system into three independent paths so slow or flaky external providers never block availability reads.
Internal Web App Public Booking Pages External Providers (group scheduling) (visitor browsers) (Google, Microsoft) | | webhook | ^ incremental sync, v v push | | live free/busy, +------------------------------------------+ v | event write-back | API Gateway | +-----------------------+ +------------------------------------------+ | Notification Receiver | | | | +-----------------------+ v v v | +--------------+ +-------------+ +-----------------+ v | Availability | | Page Slots | | Booking Service | +-----------------------+ | Service | | Service | | (atomic reserve)| | Coalesced Sync Queue | +--------------+ +-------------+ +-----------------+ | (max 1 pending/cal) | | ^ | ^ | | +-----------------------+ | +-- Redis Cache -+ | | | | (busy lists & page slots) | | v +-----------------+----------------+ | +-----------------------+ | | | Sync Workers | v | | (per-user/app quotas) | +-------------------------+ | +-----------------------+ | Busy Store (Sharded |<--------------+ | | Postgres by user_id) |<--------------------------------------+ +-------------------------+ applies deltas & bumps calendars.version | v +-----------------------------+ | Reservations DB (Sharded | | Postgres by host_id) | | GiST exclusion + outbox | +-----------------------------+ | v +-----------------------------+ | Outbox Write-Back Workers |---> External Providers +-----------------------------+ [ Background Scheduler: safety polling, webhook renewal, weekly +7d horizon roll ] ---> Sync Queue- Read path: Availability Service and Page Slots Service read only from Redis cache and the sharded Busy Store (plus active
reservations). They make zero calls to Google or Microsoft. - Sync path: inbound webhooks (HTTP callbacks sent by a provider when a calendar changes) and scheduled safety polls push
calendar_idonto a coalesced queue — a queue that deduplicates pending IDs so 50 rapid edits to one calendar trigger only one sync fetch. - Booking path: Booking Service performs a fresh check, inserts a reservation protected by a database constraint, and writes an outbox record (a row saved in the same database transaction as the reservation so a background worker can reliably push the calendar invite to Google/Microsoft even if our server crashes mid-request).
- Read path: Availability Service and Page Slots Service read only from Redis cache and the sharded Busy Store (plus active
Deep dive 1: computing common free time across time zones
The cleanest algorithmic approach is to union everyone's blocked intervals and extract the remaining unblocked gaps, rather than computing each person's free windows and intersecting them pairwise. Why? Because four different things can block a required participant from taking a meeting:
- Busy intervals from their counted external calendars;
- Confirmed or temporarily held reservations in our own database;
- Buffer padding around their existing meetings (
[start - buffer_before, end + buffer_after)); - Every minute outside their local working hours (for example, nights and weekends).
Notice a subtle rule: buffers pad existing meetings, not working-hour boundaries. If Maya works 09:00–17:00 and wants a 15-minute breather between meetings, she can still start her first meeting right at 09:00! Treating non-working hours and padded meetings uniformly as "blocked intervals" handles this naturally: we dump all blocked intervals from all required participants into one list, sort and merge overlapping intervals, and slice the remaining gaps onto the slot grid.
from datetime import datetime, timedelta from zoneinfo import ZoneInfo def merge_busy(intervals): """Merge overlapping or touching half-open [start, end) intervals.""" # Sort by start time so one left-to-right pass combines overlaps merged = [] for start, end in sorted(intervals): if start >= end: continue # Touching intervals like [10:00, 10:30) and [10:30, 11:00) have # start == merged[-1][1], so '<=' fuses them into one solid busy block if merged and start <= merged[-1][1]: if end > merged[-1][1]: merged[-1][1] = end else: merged.append([start, end]) return merged def gaps_within(blocked_intervals, window_start, window_end): """Return free [gap_start, gap_end) intervals inside [window_start, window_end).""" gaps = [] cursor = window_start for start, end in merge_busy(blocked_intervals): if start >= window_end: break if start > cursor: gaps.append((cursor, start)) if end > cursor: cursor = end if cursor < window_end: gaps.append((cursor, window_end)) return gaps def align_up_in_zone(timestamp_utc, step_sec, organizer_tz): """Snap timestamp_utc forward to the next step grid boundary in organizer_tz.""" # Aligning in the organizer's local zone handles half-hour / 45-min zones # like India (UTC+5:30), where 09:00 local is 03:30 UTC (not a UTC whole hour) tz = ZoneInfo(organizer_tz) local_dt = datetime.fromtimestamp(timestamp_utc, tz) midnight = datetime.combine(local_dt.date(), datetime.min.time(), tzinfo=tz) elapsed = timestamp_utc - int(midnight.timestamp()) remainder = elapsed % step_sec if remainder == 0: return timestamp_utc return timestamp_utc + (step_sec - remainder) def working_intervals_utc(rules_by_weekday, tz_name, window_start, window_end): """Convert a user's local working-hour rules per calendar date into UTC intervals.""" tz = ZoneInfo(tz_name) # Start 1 local day early so an overnight shift from yesterday into window_start is included day = datetime.fromtimestamp(window_start, tz).date() - timedelta(days=1) last_day = datetime.fromtimestamp(window_end, tz).date() work_utc = [] while day <= last_day: for start_local, end_local in rules_by_weekday.get(day.weekday(), []): # Converting each specific date through ZoneInfo applies that date's exact DST offset start_dt = datetime.combine(day, start_local, tzinfo=tz) end_dt = datetime.combine(day, end_local, tzinfo=tz) work_utc.append((int(start_dt.timestamp()), int(end_dt.timestamp()))) day += timedelta(days=1) return work_utc def common_free_slots(required_people, window_start, window_end, duration_sec, step_sec, organizer_tz): """Find [slot_start, slot_end) intervals where all required participants are free.""" blocked = [] for person in required_people: # 1. Invert working hours inside the query window to get off-hours blocks work = working_intervals_utc(person.rules, person.time_zone, window_start, window_end) outside_work = gaps_within(work, window_start, window_end) blocked.extend(outside_work) # 2. Pad each existing meeting / reservation by this person's buffers for start, end in person.busy_and_reserved: blocked.append((start - person.buffer_before_sec, end + person.buffer_after_sec)) # 3. Walk every common free gap and emit start times that fit the full duration slots = [] for gap_start, gap_end in gaps_within(blocked, window_start, window_end): t = align_up_in_zone(gap_start, step_sec, organizer_tz) while t + duration_sec <= gap_end: slots.append((t, t + duration_sec)) t += step_sec return slotsComplexity and optional attendees:
- Time and space: let
Nbe the total blocked intervals across all required participants (busy events plus ~1 off-hours block per person per day) andSbe the returned slots. Sorting takesO(N log N)time, merging and scanning gaps takesO(N)time, and stepping through valid slots takesO(S)time —O(N log N + S)total time andO(N + S)space. - Optional attendees: optional people never block a slot. Instead, merge each optional person's blocked list once (
O(n log n)), and for each candidate slot found above, run a binary search (O(log n)) to count how many optional attendees can make it.
Worked trace during a real US/Europe daylight-saving mismatch (Tuesday, March 17, 2026):
On March 8, 2026, the US springs forward to EDT (
UTC-4), while Central Europe stays on CET (UTC+1) until March 29. For those three weeks, New York and Berlin are 5 hours apart instead of the winter 6:Query: 2026-03-17 00:00..24:00 UTC, duration = 30 min, step = 15 min, buffers = 0 Maya (New York, 09:00-17:00 EDT = UTC-4) -> works 13:00-21:00 UTC; customer call 13:45-14:30 UTC Lukas (Berlin, 09:00-17:00 CET = UTC+1) -> works 08:00-16:00 UTC; review 14:45-15:30 UTC Step 1 - Collect all blocked intervals in UTC: Maya off-hours: [00:00, 13:00), [21:00, 24:00) Lukas off-hours: [00:00, 08:00), [16:00, 24:00) Meetings: [13:45, 14:30), [14:45, 15:30) Step 2 - Sort and merge_busy: Blocked union: [00:00, 13:00), [13:45, 14:30), [14:45, 15:30), [16:00, 24:00) Step 3 - Read gaps_within [00:00, 24:00): Gaps: [13:00, 13:45) (45m) | [14:30, 14:45) (15m - too short!) | [15:30, 16:00) (30m) Step 4 - Emit 30-min slots on 15-min grid: Candidate starts: 13:00 UTC, 13:15 UTC, 15:30 UTC (= 09:00, 09:15, 11:30 EDT for Maya; 14:00, 14:15, 16:30 CET for Lukas)Notice what would break if we stored
-05:00instead ofAmerica/New_York: Maya's workday would start at14:00 UTC, silently throwing away both13:00 UTCand13:15 UTC!Deep dive 2: calendar sync, staleness bounds, and quota budgets
Our read path stays fast because sync workers maintain
busy_intervalsin the background. Keeping that mirror accurate requires four mechanisms:- Initial sync + sync cursor + webhook registration: when a user connects a calendar, a worker fetches expanded instances over
[now - 1 day, now + 90 days], writes their busy intervals, saves the provider's sync cursor (Google'snextSyncTokenor Microsoft'sdeltaLink, a bookmark token that lets future calls download only events changed since that bookmark), and registers a webhook channel. Because provider webhooks expire after days or weeks, the scheduler renews them well beforewebhook_expires_at. - Coalesced incremental sync: a provider webhook says only "calendar
cal_9changed." The notification receiver verifies the webhook signature and insertscal_9into the sync queue if it is not already queued. If a user imports 50 events at once, 50 webhooks collapse into 1 incremental fetch. The worker applies inserts/updates/deletes in a single database transaction, updatessync_cursorandlast_synced_at, and incrementscalendars.version. If the provider invalidates an old cursor (410 Gone), the worker cleanly falls back to a full 90-day resync. - Weekly horizon extension (a classic gotcha): a sync cursor only reports events that were edited — it never fires when next Tuesday's instance of an unchanged weekly standup crosses the 90-day boundary! Once a week, a background job fetches
[horizon_end, horizon_end + 7 days)for each calendar (~1.1M calls/day) so the pre-expanded window never runs dry. - Tiered safety polling, rate limits, and auth errors:
Update path Typical lag Worst-case lag if webhooks drop silently -------------------------------- ----------------- ---------------------------------------- Webhook push + incremental sync 2 - 30 seconds - Safety poll (booking-page hosts) - 30 minutes Safety poll (regular users) - 6 hours Live free/busy check at booking - 0 seconds for the host at checkoutEach sync worker draws from two token buckets (rate-limit counters that refill at a steady rate): one for our overall app quota with the provider and one per connected user. On
429 Too Many Requests, workers honorRetry-Afterand back off with random jitter, prioritizing active booking-page hosts first. If a user revokes their OAuth grant (401/invalid_grant), we markconnections.status = DISCONNECTEDand email the user once instead of hammering the provider in an infinite retry loop.- Initial sync + sync cursor + webhook registration: when a user connects a calendar, a worker fetches expanded instances over
Deep dive 3: preventing double bookings and reconciling conflicts
A core rule of scheduling systems is that slots rendered on a web page are advisory snapshots, never reservations. Look at what goes wrong if two requests check availability in Python and then
INSERTa row without an atomic database guard:Time Visitor A (wants 13:00-13:30) Visitor B (wants 13:00-13:30) ----- -------------------------------------- -------------------------------------- t=0ms SELECT overlaps for 13:00 -> 0 rows! SELECT overlaps for 13:00 -> 0 rows! t=5ms INSERT booking at 13:00 -> succeeds INSERT booking at 13:00 -> ALSO succeeds! (Double-booked!)We close that race inside PostgreSQL using an exclusion constraint — a declarative database rule backed by a GiST index that forbids any two active rows for the same
host_idfrom having overlapping time ranges:CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE reservations ( reservation_id uuid PRIMARY KEY, host_id bigint NOT NULL, starts_at timestamptz NOT NULL, ends_at timestamptz NOT NULL, -- When buffer is uniform per host, [starts_at, ends_at + buffer) guarantees -- earlier_end + buffer <= later_start; for per-page asymmetric buffers, -- store [starts_at - buffer_before, ends_at + buffer_after) blocked tstzrange NOT NULL, status text NOT NULL, -- HELD | CONFIRMED | CANCELLED | EXPIRED hold_expires_at timestamptz, idempotency_key text UNIQUE NOT NULL, EXCLUDE USING gist (host_id WITH =, blocked WITH &&) WHERE (status IN ('HELD', 'CONFIRMED')) );When Visitor A and Visitor B execute
INSERTconcurrently, PostgreSQL locks the conflicting index entry so the second transaction waits milliseconds for the first; once Visitor A commits, Visitor B immediately gets an exclusion-constraint error, which our API turns into409 Conflictwith fresh alternative slots. (If your database is MySQL or DynamoDB instead of PostgreSQL, two portable alternatives are locking the host's parent row withSELECT ... FOR UPDATEbefore checking overlaps, or bucketizing time into 5- or 15-minute slot rows under aUNIQUE (host_id, cell_start)key.)Here is the complete
bookflow in order:def book_slot(request, db, busy_store, provider_client, outbox): """Atomically reserve a slot on a host's booking page without double-booking.""" # 1. Fast path for network retries or accidental double-clicks existing = db.find_reservation_by_key(request.idempotency_key) if existing is not None: return existing page = db.get_booking_page(request.page_id) validate_booking_rules(page, request.start) # min notice, horizon, working hours end = request.start + page.duration_sec # 2. Cheap pre-checks against fresh local store + a 1.5s live provider free/busy call if busy_store.has_conflict(page.host_id, request.start, end, page.buffer_before, page.buffer_after): return conflict_with_alternatives(page, request) if not live_provider_check_allows(provider_client, page.host_id, request.start, end): return conflict_with_alternatives(page, request) # 3. Single atomic transaction: clean expired holds, enforce exclusion constraint, queue write-back blocked_start = request.start - page.buffer_before blocked_end = end + page.buffer_after try: with db.transaction(): db.expire_past_holds(page.host_id, blocked_start, blocked_end) reservation = db.insert_confirmed( host_id=page.host_id, starts_at=request.start, ends_at=end, blocked=(blocked_start, blocked_end), idempotency_key=request.idempotency_key, ) # Same transaction ensures we never confirm a booking without queueing its calendar invite outbox.enqueue(reservation.reservation_id, action="CREATE") return reservation except UniqueIdempotencyViolation: # Concurrent twin from a double-click won the race milliseconds ago -> return that booking return db.find_reservation_by_key(request.idempotency_key) except ExclusionConstraintViolation: # Another invitee won an overlapping slot -> return 409 with fresh open times return conflict_with_alternatives(page, request)Reliable write-back and external conflict reconciliation:
- Idempotent provider event creation: the outbox worker creates the event in Google/Microsoft supplying a deterministic client event ID (Google's
idor Microsoft'stransactionId) derived fromreservation_id, so retrying after a timeout never creates duplicate calendar invites. When the webhook later echoes our own event back into sync, matchingprovider_event_idlinks it to our reservation instead of flagging a false conflict. - What if the provider is unreachable at booking time? If the 1.5 s live check times out, we confirm from our local mirror only if the host's sync is healthy and under 15 minutes old; otherwise we accept the submission as a pending booking request for the host to approve once connectivity recovers.
- Unpreventable external race: because no third-party app can lock Google Calendar itself, a host could accept an invite directly in Gmail in the exact second a visitor books on our page. When sync ingests that overlapping external event, we detect the overlap against our
CONFIRMEDreservation and alert the host immediately with a one-click reschedule link — never silently cancelling either meeting.
- Idempotent provider event creation: the outbox worker creates the event in Google/Microsoft supplying a deterministic client event ID (Google's
Scaling, failure handling, and trade-offs
Partitioning and caching
- Sharding: shard
busy_intervalsbyuser_id(so all calendars of one user live on one shard) and shardreservationsbyhost_id(so the GiST exclusion constraint is always a single-shard local check). A 5-person group query performs a parallel scatter-gather (querying at most 5 shards simultaneously and merging the ~165 intervals in the stateless Availability Service). - Self-invalidating caches: cache each user's merged weekly busy list in Redis under key
busy:{user_id}:{iso_week}:{versions_hash}(~1 KB per entry), and cache public booking-page slots in UTC underpage:{page_id}:{iso_week}:{cal_ver}:{res_ver}with a 60 s TTL (time-to-live automatic expiration). Whenever a sync or booking bumps a version number, readers immediately look up the new key — no race-prone cache-delete logic needed, and one UTC page-slot cache entry serves visitors across every time zone on Earth! If a viral link draws 1,000 views/s, 99.9% hit Redis whilePOST /v1/bookingsserializes actual bookings cleanly on the host's shard.
Failure handling summary
Failure Impact How the system handles it Webhook notifications silently stop Push updates stop arriving Tiered safety polling (30 min for hosts, 6 h for others) + webhook renewal health checks catch up automatically Sync token rejected ( 410 Gone)Delta fetch fails Worker clears cursor and runs a full 90-day window resync for that calendar Provider rate-limits requests ( 429)Sync queue backs up Per-app and per-user token buckets, webhook coalescing, Retry-Afterbackoff, priority queue for active hostsUser revokes OAuth token Cannot read user's calendar Mark connection DISCONNECTED, email user once, surfacecalendar_stalewarning on queriesProvider outage Mirror ages; write-backs pause Queries serve local mirror with data_as_of; bookings degrade to request-mode past 15 min staleness; outbox retries write-backsTwo visitors book the same slot Race condition PostgreSQL GiST exclusion constraint allows one commit and returns 409+ alternatives to the otherSummary of key trade-offs
- Synchronized local mirror + 1 live check at booking vs. live lookups on every read: trades ~180 GB of storage and background sync workers for predictable
< 200 msreads, immunity to viral traffic spikes, and resilience during provider hiccups. - Merging all blocked intervals vs. intersecting free intervals: treats external meetings, reservations, meeting buffers, and off-working hours identically in one
O(N log N)sweep. - UTC instants + IANA zones vs. local timestamps or fixed offsets: requires per-date conversion for local working rules, in exchange for exact correctness across every daylight-saving transition worldwide.
- Database exclusion constraint + transactional outbox vs. distributed locks or synchronous write-back: keeps booking fast, atomic, and immune to application crashes, while handling external calendar races via detection and host notification.
- Sharding: shard
Intuition & how it works
Think of finding common free time like stacking dark blackout strips onto a sunlit window: each participant lays opaque strips over the hours they are asleep/off-work and over their existing meetings (widened slightly if they want breathing room between calls). Wherever sunlight still shines through all the stacked layers for at least 30 continuous minutes, everyone can meet! Then, because viewing a seat map at a movie theater does not reserve a chair, clicking "Book" works like a theater checkout lock: the database puts an atomic lock on that exact time range for the host before confirming the ticket.
Why do the obvious approaches fail? First, calling Google Calendar or Microsoft Outlook live on every availability read breaks at scale: a popular booking link getting 200 views per second fires 200 API calls per second on one host's OAuth token (instantly tripping per-user rate limits), and a 5-person query fails or stalls whenever any single provider is slow. Second, storing time zones as fixed offsets like -05:00 breaks by an hour whenever daylight saving time (DST) shifts — especially during the three weeks in March when the US and Europe switch clocks on different Sundays. Third, checking "is 1:00 p.m. free?" in application code and then inserting a booking allows two simultaneous visitors to pass the check and double-book the host.
Let's trace a tiny concrete scenario across Tuesday, March 17, 2026 (when New York is on EDT UTC-4 and Berlin is on CET UTC+1) for a 30-minute meeting on a 15-minute step grid:
- Background sync updates our mirror: Maya (New York, working 09:00–17:00 local =
13:00–21:00 UTC) adds a13:45–14:30 UTCcall in Google Calendar. Google sends a webhook (an HTTP change notification), and a sync worker fetches the delta using a sync cursor (a bookmark token returning only changed events) and stores[13:45, 14:30)as a half-open interval (including start, excluding end). - Union of blocked time: Lukas (Berlin, working 09:00–17:00 local =
08:00–16:00 UTC) is busy14:45–15:30 UTC. Combining Maya's off-hours ([00:00, 13:00),[21:00, 24:00)), Lukas's off-hours ([00:00, 08:00),[16:00, 24:00)), and both meetings produces merged blocked blocks[00:00, 13:00),[13:45, 14:30),[14:45, 15:30), and[16:00, 24:00). - Reading the sunlit gaps: the remaining gaps
[13:00, 13:45)(45m),[14:30, 14:45)(15m, skipped as too short), and[15:30, 16:00)(30m) emit candidate 30-minute starts13:00 UTC,13:15 UTC, and15:30 UTCstraight from local storage in milliseconds. - Two visitors click
13:00 UTCat once: both pass pre-checks, but PostgreSQL's exclusion constraint (a database index rule forbidding overlapping active time ranges for the same host) lets Visitor 1 commit[13:00, 13:30)+ an outbox write-back job, while immediately rejecting Visitor 2 with409 Conflictand offering13:15and15:30instead.
Key trade-offs
- Synchronized local mirror vs. live provider calls on reads. Querying providers live requires zero storage and is always up to the second, but provider API volume scales with reads x participants (~300M calls/day), hot booking pages exhaust a single host's per-user quota, and tail latency equals the slowest external API. Mirroring busy intervals locally costs ~180 GB and a background sync pipeline with bounded staleness, but decouples read latency and availability from third-party APIs; we spend a single live free/busy check only at booking checkout where freshness matters most.
- Webhook push + tiered safety polling vs. pure polling. Webhooks deliver updates within seconds at zero idle cost, but subscriptions expire and occasional deliveries drop silently. Pairing webhooks with tiered safety polling (every 30 minutes for booking-page hosts, every 6 hours for others) guarantees a strict worst-case staleness ceiling without blowing through API quotas across 7.5M calendars.
- Merging blocked intervals vs. intersecting free intervals. Both run in
O(N log N)time, whereNis the number of intervals. Merging one combined list of everything that blocks a meeting treats external events, internal reservations, meeting buffers, and off-working hours identically, whereas intersecting free lists forces you to construct and clip each person's free windows separately first. - Pre-expanded instances vs. storing recurrence rules (
RRULE). Letting Google and Microsoft expand recurring series over a rolling 90-day window makes availability queries simple range scans and avoids re-implementing complex recurrence exceptions and DST rules. The trade-off is storing ~400 rows per calendar and running a weekly horizon-extension job (because incremental sync cursors only report edited events, not unchanged weekly meetings rolling into the 90-day window). - PostgreSQL GiST exclusion constraint vs. row locks vs. discrete slot cells. A GiST exclusion constraint prevents any overlapping active ranges in the database engine regardless of duration or step grid, at the cost of tying the reservations database to PostgreSQL. Locking the host's parent row (
SELECT ... FOR UPDATE) works in any SQL database by serializing bookings per host, while inserting discrete 5- or 15-minute cell rows under aUNIQUE (host_id, cell_time)key works in any key-value store at the cost of fixed grid granularity. - Minimal metadata storage vs. rich event storage. Storing only
[start_utc, end_utc)and busy status slashes database size and protects user privacy if a shard is ever inspected, trading away the ability to build meeting-title features without requesting broader permissions and fetching details separately.
Common mistakes
- Storing local wall-clock times or fixed numeric offsets (
-05:00) instead of UTC instants + IANA zone names. Fixed offsets silently shift meetings by an hour for half the year and break cross-continent scheduling when regions enter or leave daylight saving time on different dates. - Using closed intervals
[start, end]instead of half-open intervals[start, end). With closed bounds, a10:00–10:30meeting touches10:30–11:00at10:30, falsely flagging back-to-back slots as conflicting. - Calling external calendar APIs synchronously on the read path. It works in a prototype with two users and collapses in production under per-user provider rate limits and p99 latency spikes.
- Aligning 30- or 60-minute slot steps in UTC instead of the organizer's time zone. Time zones like India (
Asia/Kolkata,UTC+5:30) sit 30 minutes off UTC whole hours, so snapping 60-minute slots to:00in UTC produces:30start times (09:30, 10:30) for an organizer whose workday starts at09:00local time. - Applying buffers to non-working-hour boundaries or only in the frontend UI. Padding off-work intervals prevents someone from taking a
09:00meeting when their workday starts at09:00, while hiding buffered slots only in the browser leaks invalid slots to API callers. - Checking availability and inserting a booking in two unguarded steps. Without a database exclusion constraint, unique cell key, or per-host lock, concurrent clicks pass both
SELECTchecks and double-book the host. - Treating every calendar entry as busy. Declined invites, "free/transparent" blocks, and all-day birthday reminders block entire days if you ignore the provider's transparency and attendance status fields.
- Forgetting
Idempotency-Keyrace handling or outbox write-backs. Retrying after a mobile timeout without idempotency creates two bookings (or returns a false409on a double-click), and writing directly to Google Calendar outside an outbox loses the calendar invite if the server restarts right after committing the reservation.
Follow-up questions
- Instead of returning every valid slot chronologically, how would you score and rank the best meeting times? Compute a weighted convenience score for each valid slot and return the top
Kwith a per-day cap (such as at most 3 per day) so Monday morning does not monopolize the whole list. Useful scoring features include earliness (slight preference for sooner dates), time-of-day comfort across time zones (penalizing the worst-off participant's distance from core10:00–16:00local hours so one colleague is not always stuck at 7:00 a.m.), count of free optional attendees, calendar fragmentation (rewarding slots adjacent to existing meetings and penalizing awkward 15-minute orphan gaps), and explicit user preferences like "no Friday afternoons." Start with simple interpretable weights, log which suggested slot organizers actually pick, and tune weights via A/B tests measuring top-3 selection rate. - How would you extend the slot search to propose a recurring weekly time across a 12-week horizon? Anchor candidate series in the organizer's IANA time zone (for example,
"Tuesdays at 10:00 America/New_York"), because calendar providers define recurring series in one local zone and shift its UTC instant across DST transitions. Run our blocked-interval merge once across the full 12-week window (O(N log N)), map every valid candidate slot back to(organizer_weekday, organizer_local_time), and count how many of the 12 weeks each recurring slot is conflict-free for all required participants (including checking whether DST shifts push a week outside a remote teammate's working hours). Return slots free in all 12 weeks first, followed by "11 out of 12 weeks free (conflict on March 24)" because in real teams a 100% conflict-free multi-month slot rarely exists and rescheduling one single instance is expected. - What should the service do when one attendee's external calendar provider has been timing out for the past hour? Separate a transient provider outage (
5xxor network timeouts — back off with jitter and alert on-call if many users fail together) from a permanent credential failure (401/invalid_grant— markDISCONNECTEDand email the user once to reconnect). For internal group queries, still compute slots using that person's cached busy intervals from an hour ago, attachdata_as_ofplus acalendar_stalewarning in the UI, and let the organizer decide whether to proceed. If that user hosts a public booking page, our localreservationsconstraint still prevents internal double-bookings, while the failed live check triggers our staleness safeguard: once local sync age exceeds a strict threshold (say 15 minutes), new bookings switch from instant confirmation to pending host approval while write-backs wait safely in the outbox. - How would you design team scheduling links that assign incoming bookings across a pool of hosts in round-robin fashion? A team booking page offers a time slot whenever at least one eligible host on the team is free: compute each host's free slots individually and take their union, recording the list of available hosts per slot (caching under a key that hashes all team members' calendar and reservation versions). When a visitor clicks
POST /v1/bookingsfor13:00 UTC, sort the hosts free at13:00by fairness policy (for example, fewest bookings in the past 7 days, breaking ties by longest time since last booking) and attempt the single-shard atomic reservation on Host 1; if Host 1 just got booked a millisecond earlier and throws an exclusion violation, immediately fall through to Host 2 in the same request. Updating per-host booking counters asynchronously after commit keeps checkout fast without needing any cross-shard distributed transactions.
Follow-up questions
- Instead of returning every valid slot chronologically, how would you score and rank the best meeting times?
- How would you extend the slot search to propose a recurring weekly time across a 12-week horizon?
- What should the service do when one attendee's external calendar provider has been timing out for the past hour?
- How would you design team scheduling links that assign incoming bookings across a pool of hosts in round-robin fashion?
Similar questions
- Design an Enterprise Zoom Recording Ingestion and Analysis Pipeline
- Communicating Difficult News While Preserving Stakeholder Trust
- Creating Momentum When Scope and Ownership Are Unclear
- Working Through a High-Stakes Disagreement With a Colleague
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor