Concurrent Interview Scheduling and Availability API
Medium · System Design · Software Engineer · Onsite
Prompt
Architect the backend scheduling service for a technical recruiting platform. Interviewers configure the windows when they can conduct interviews, candidates browse deduplicated open start times across the upcoming 14 calendar days, and a candidate reserves a specific interview window. Whenever a reservation succeeds, the backend must atomically match the candidate with one eligible, free interviewer while ensuring zero overlapping assignments per interviewer.
Support three core HTTP endpoints:
POST /interviewers/{id}/availability— Allows an interviewer to register repeating weekly schedules or one-time open windows divided into30-minute or60-minute intervals.GET /interviews/available-slots— Returns distinct bookable start timestamps across all qualified interviewers for any requested date range inside the next 14 days, rendered with time-zone offset support.POST /interviews/bookings— Accepts a candidate's desired start timestamp, duration (30or60minutes), and interview track, then atomically selects one free qualified interviewer, records the confirmed reservation, and marks that interviewer's time window unavailable.
Target the following operational profile and service-level goals:
- Scale: 5,000 active interviewers and 50,000 weekly active candidates, averaging roughly 10,000 confirmed reservations per day with traffic bursts up to 500 booking requests per second when large recruiting cohorts open.
- Correctness: Strict transactional isolation so concurrent requests never double-book an interviewer.
- Performance: Available-slot lookups must complete under 100 ms at p95.
- Load balance: Distribute reservations proportionally across equally qualified interviewers.
Scope & Expectations
- Relational schema & constraints: Define the SQL tables, relational keys, secondary indexes, and database-enforced invariants that represent time blocks, interviewer qualifications, and confirmed reservations.
- API design: Specify request bodies, response payloads, idempotency semantics, and HTTP status codes for all three endpoints.
- High-concurrency booking: Explain how transactions and locking (such as row-level locks, optimistic concurrency, or distributed coordination) prevent race conditions at 500 requests/second while keeping interviewer utilization balanced.
- Fast reads & operational resilience: Detail how 14-day slot queries stay below 100 ms at p95 without full-table scans, and cover interviewer cancellations, timeouts, audit trails, and key metrics.
Step-by-step walkthrough
Clarify requirements and scope
At first glance, an interview scheduler looks like a small CRUD app—5,000 interviewers and 10,000 bookings a day are modest database numbers. What makes this problem genuinely tricky is concurrency and correctness: when a large recruiting cohort opens, 500 candidates per second may click the exact same Tuesday 10:00 AM window at the same instant. Every successful request must receive a different qualified interviewer with zero double-bookings, while candidates browsing the two-week calendar still get answers in under 100 ms.
Functional requirements
- Publish availability (
POST /interviewers/{id}/availability): Interviewers register repeating weekly schedules (such as "Tuesdays 09:00–12:00 in my local time zone") or one-time open windows, aligned to 30-minute blocks. They can also withdraw unbooked blocks. - List open slots (
GET /interviews/available-slots): Candidates fetch deduplicated bookable start timestamps for a chosen interview track (such asbackendorml) and duration (30or60minutes) across any requested date span inside the upcoming 14 calendar days, formatted for their time zone. - Book a slot (
POST /interviews/bookings): A candidate submits a start timestamp, duration, and track. In one atomic operation (an all-or-nothing unit of work), the backend selects one free qualified interviewer, records the confirmed reservation, and marks that interviewer's blocks occupied. - Supporting lifecycle actions: Candidates can inspect or cancel a reservation; interviewers can step back from an already-confirmed interview, triggering automated reassignment without voiding the candidate's time slot.
Non-functional requirements
- Strict consistency on writes: An interviewer can never be assigned to overlapping interviews, regardless of concurrent write bursts.
- Low read latency: Available-slot lookups complete in under 100 ms at p95 (meaning at least 95 out of 100 requests finish faster than 100 ms); booking mutations finish in under 300 ms at p95.
- Proportional load sharing: Equally qualified interviewers receive work in proportion to their offered capacity rather than overloading a single volunteer.
- Auditability: Every reservation, cancellation, reassignment, and schedule change is appended to an immutable audit trail.
Clarifying assumptions to confirm with the interviewer
- Qualification matching: An interviewer is eligible for a track if a row exists in
interviewer_trackandinterviewer.active = true. - Clock alignment: All blocks align to
:00and:30in UTC. That matches:00and:30local time in every standard whole-hour and 30-minute offset time zone (including India atUTC+05:30); rare 45-minute offset zones (such as Nepal atUTC+05:45) see:15and:45, which we document. - Minimum notice: Candidates cannot book a slot starting less than 12 hours from now so interviewers are never ambushed.
- Candidate booking limit: At most one active booking per candidate per track at a time.
- Daily interviewer cap: Each interviewer has a
max_per_daylimit (default 4 interviews per local day) to prevent burnout.
- Publish availability (
Back-of-the-envelope numbers
Before choosing databases or caches, let's turn the prompt's numbers into row counts, queries per second, and disk growth.
Scale inputs Active interviewers 5,000 Active candidates 50,000 / week Daily bookings 10,000 / day (~0.12 bookings/s average) Booking spike 500 booking attempts/s (given; assume a 10-min cohort drop) Availability rows in the 14-day rolling window Typical offered time 15 hours/week = 30 half-hour blocks/week -> ~60 blocks / 14 days Open block rows 5,000 x 60 = ~300,000 open rows Worst-case dense bound 5,000 x 14 days x 48 half-hours/day = 3,360,000 rows (< 500 MB) Interviewer supply sanity check Weekly demand 10,000/day x 7 days x 0.75 h avg = 52,500 interviewer-hours/week Weekly supply 5,000 interviewers x 15 h/week = 75,000 interviewer-hours/week Average utilization 52,500 / 75,000 = 70% (tight enough that fairness matters!) Read traffic (slot listing) Average 50,000 candidates/week x 10 views = 500,000/week (~0.8 req/s) Release spike 20,000 candidates x 5 refreshes / 600 s = ~167 req/s -> design for 2,000 req/s headroom Write traffic at the 500 attempts/s spike Rows touched per booking 1 booking + 2 slot rows + 1 day counter + 1 load counter + 1 outbox event + 1 audit row = ~7 row writes Peak row writes 500/s x 7 = ~3,500 row writes/s Storage growth Bookings + slots + audit ~3 KB total per booking x 10,000/day = ~30 MB/day (~11 GB/year)What these numbers tell us:
- One relational primary is plenty for storage and throughput. Three hundred thousand active slot rows and ~11 GB/year of history fit effortlessly in RAM on a single PostgreSQL primary with a synchronous standby. Sharding the database on day one would add massive complexity for zero gain.
- Contention—not raw write volume—is the booking bottleneck. Five hundred requests per second is easy when spread out, but catastrophic if all 500 fight over the exact same row lock for
Monday 10:00 AM. - Repeated aggregation is the read bottleneck. Joining and grouping hundreds of thousands of slot rows 2,000 times per second during a spike would burn CPU on the primary, so we should serve slot listings from precomputed counts in Redis.
Core idea: normalize time into 30-minute blocks
If interviewers stored arbitrary intervals like
09:10–11:47, every listing query and every booking would require messy interval-overlap math, and there would be no discrete unit to lock when two candidates want different slices of that window.Instead, we normalize time into discrete 30-minute blocks aligned to
:00and:30UTC:Interviewer 42 sets rule: "Mondays 09:00 - 11:00 America/Los_Angeles (UTC-8)" Materialized rows in `slot` table (UTC): +----------------+------------------------+--------+ | interviewer_id | start_at (UTC) | status | +----------------+------------------------+--------+ | 42 | 2026-12-07 17:00:00+00 | open | <- 09:00 - 09:30 local | 42 | 2026-12-07 17:30:00+00 | open | <- 09:30 - 10:00 local | 42 | 2026-12-07 18:00:00+00 | open | <- 10:00 - 10:30 local | 42 | 2026-12-07 18:30:00+00 | open | <- 10:30 - 11:00 local +----------------+------------------------+--------+ - A 30-minute interview claims 1 row (for example, 17:00). - A 60-minute interview claims 2 consecutive rows of the SAME interviewer (17:00 and 17:30).How rules and time zones work cleanly:
- Store recurring rules in local wall-clock time plus an IANA time zone name (an IANA time zone is a geographic region identifier like
America/Los_AngelesorAsia/Kolkatathat knows historical and future Daylight Saving Time rules, unlike a fixed offset like-08:00). That way, "Mondays at 09:00" stays 09:00 local time even after Daylight Saving Time shifts its UTC offset from-08:00to-07:00. - Materialize a rolling 15-day horizon. A background expansion job runs hourly (and immediately whenever an interviewer edits a rule) to generate concrete
slotrows up tonow + 15 days(14 days visible to candidates plus 1 day of buffer). On a spring-forward DST gap, nonexistent local times are skipped; on a fall-back repeated hour, the UTC instant is generated once. - Compare and store instants in UTC (
timestamptz). Inside the database, every timestamp is a UTC instant. Time-zone conversion happens only at the edges: expanding rules and formatting API responses.
- Store recurring rules in local wall-clock time plus an IANA time zone name (an IANA time zone is a geographic region identifier like
Relational data model and safety constraints
We design the PostgreSQL schema with defense in depth: fast row-level locks guide normal concurrent bookings, while database constraints make invalid states (like overlapping confirmed interviews) physically impossible even if future application code has a bug.
Key terms used in the schema below:
- A partial index indexes only the subset of rows matching a
WHEREfilter (herestatus = 'open'), keeping the index tiny and fast. - A half-open interval
[start, end)includesstartand excludesend, so10:00–11:00and11:00–12:00touch at11:00without overlapping. - An exclusion constraint (
EXCLUDE USING gist) is a PostgreSQL rule backed by a GiST index (Generalized Search Tree, an index structure that understands ranges and geometry) that rejects any two rows whose intervals overlap (&&) for the sameinterviewer_id(=). - An idempotency key is a client-generated unique token per user click so that retrying a timed-out network request returns the original booking instead of creating a duplicate.
- A transactional outbox is a database table where background events are inserted inside the exact same transaction as business data, guaranteeing we never commit a booking while losing its cache-update or email event.
CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE interviewer ( id bigint PRIMARY KEY, name text NOT NULL, email text NOT NULL UNIQUE, timezone text NOT NULL, -- IANA zone, e.g. 'Asia/Kolkata' max_per_day smallint NOT NULL DEFAULT 4, active boolean NOT NULL DEFAULT true ); CREATE TABLE track ( id smallint PRIMARY KEY, name text NOT NULL UNIQUE -- 'backend', 'ml', 'hiring-manager' ); CREATE TABLE interviewer_track ( interviewer_id bigint NOT NULL REFERENCES interviewer(id), track_id smallint NOT NULL REFERENCES track(id), PRIMARY KEY (interviewer_id, track_id) ); CREATE INDEX interviewer_track_by_track ON interviewer_track (track_id, interviewer_id); CREATE TABLE availability_rule ( id bigserial PRIMARY KEY, interviewer_id bigint NOT NULL REFERENCES interviewer(id), kind text NOT NULL CHECK (kind IN ('weekly', 'once')), weekday smallint, -- 1 (Mon) .. 7 (Sun), weekly rules local_start time, -- weekly rules, e.g. '09:00' local_end time, start_at timestamptz, -- one-off rules: exact UTC instants end_at timestamptz, timezone text NOT NULL, valid_from date NOT NULL, valid_until date ); CREATE TABLE slot ( -- one row per interviewer per 30-min block interviewer_id bigint NOT NULL REFERENCES interviewer(id), start_at timestamptz NOT NULL, status text NOT NULL CHECK (status IN ('open', 'booked', 'blocked')), booking_id bigint, rule_id bigint REFERENCES availability_rule(id), version int NOT NULL DEFAULT 0, PRIMARY KEY (interviewer_id, start_at), -- 1800 seconds = 30 minutes; enforces :00 and :30 UTC grid alignment CHECK (extract(epoch FROM start_at)::bigint % 1800 = 0), CHECK ((status = 'booked') = (booking_id IS NOT NULL)) ); CREATE INDEX slot_open_by_time ON slot (start_at, interviewer_id) WHERE status = 'open'; CREATE TABLE booking ( id bigserial PRIMARY KEY, candidate_id bigint NOT NULL, track_id smallint NOT NULL REFERENCES track(id), interviewer_id bigint REFERENCES interviewer(id), -- NULL while 'needs_interviewer' start_at timestamptz NOT NULL, end_at timestamptz NOT NULL, duration_min smallint NOT NULL CHECK (duration_min IN (30, 60)), status text NOT NULL CHECK (status IN ('confirmed', 'needs_interviewer', 'cancelled', 'completed')), idempotency_key text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), CHECK (end_at > start_at), UNIQUE (candidate_id, idempotency_key), -- Last-line safety net: two confirmed bookings for one interviewer can NEVER overlap CONSTRAINT no_interviewer_overlap EXCLUDE USING gist ( interviewer_id WITH =, tstzrange(start_at, end_at, '[)') WITH && ) WHERE (status = 'confirmed') ); CREATE UNIQUE INDEX one_active_booking_per_track ON booking (candidate_id, track_id) WHERE status IN ('confirmed', 'needs_interviewer'); CREATE INDEX booking_by_interviewer ON booking (interviewer_id, start_at); CREATE TABLE interviewer_load ( -- weekly utilization for fair matching interviewer_id bigint NOT NULL REFERENCES interviewer(id), week_start date NOT NULL, offered_minutes int NOT NULL DEFAULT 0, booked_minutes int NOT NULL DEFAULT 0, PRIMARY KEY (interviewer_id, week_start) ); CREATE TABLE interviewer_day ( -- enforces max_per_day strictly interviewer_id bigint NOT NULL REFERENCES interviewer(id), local_date date NOT NULL, -- calendar date in interviewer's timezone booked smallint NOT NULL DEFAULT 0, PRIMARY KEY (interviewer_id, local_date) ); CREATE TABLE outbox ( -- published asynchronously after commit id bigserial PRIMARY KEY, topic text NOT NULL, payload jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE audit_event ( -- immutable compliance & support log id bigserial PRIMARY KEY, at timestamptz NOT NULL DEFAULT now(), actor_type text NOT NULL, -- candidate | interviewer | system | admin actor_id text NOT NULL, action text NOT NULL, -- booked | cancelled | reassigned | rule_updated entity text NOT NULL, entity_id bigint NOT NULL, request_id text, before jsonb, after jsonb );Notice why
end_atis stored explicitly onbookinginstead of writingtstzrange(start_at, start_at + interval ...)inside the exclusion constraint: in PostgreSQL, index expressions must be immutable (guaranteed to produce the exact same result forever), andtimestamptz + intervalis not immutable because adding calendar intervals can depend on session time-zone settings.- A partial index indexes only the subset of rows matching a
API contracts
Here are the three core endpoints, their payloads, and the status codes clients rely on:
1) Configure Interviewer Availability POST /interviewers/{id}/availability { "timezone": "America/Chicago", "weekly": [ {"weekday": "TUE", "start": "09:00", "end": "12:00", "valid_from": "2026-12-01", "valid_until": null} ], "once": [ {"start": "2026-12-04T14:00:00-06:00", "end": "2026-12-04T16:00:00-06:00"} ], "remove": [ {"start": "2026-12-08T09:00:00-06:00", "end": "2026-12-08T10:00:00-06:00"} ] } -> 201 Created {"rule_ids": [614, 615], "blocks_opened": 16, "blocks_removed": 2} -> 400 Bad Req MISALIGNED_GRID (times not on :00 or :30 boundaries) -> 403 Forbidden Authenticated user does not match {id} -> 409 Conflict BOOKED_BLOCKS {"conflicts": [{"start": "...", "booking_id": 1408}]} (cannot silently delete an already-booked slot; must call /decline) -> 422 Unproc. INVALID_TIMEZONE | END_BEFORE_START 2) Query Open Start Times (14-day horizon) GET /interviews/available-slots?track=backend&duration=60 &from=2026-12-08T00:00:00+05:30&to=2026-12-15T00:00:00+05:30&tz=Asia/Kolkata -> 200 OK { "track": "backend", "duration_minutes": 60, "timezone": "Asia/Kolkata", "slots": [ {"start": "2026-12-08T21:30:00+05:30", "start_utc": "2026-12-08T16:00:00Z"}, {"start": "2026-12-08T22:00:00+05:30", "start_utc": "2026-12-08T16:30:00Z"} ], "as_of": "2026-12-06T08:15:02Z" } -> 400 Bad Req RANGE_INVALID (to <= from, in the past, or > now + 14 days) -> 422 Unproc. UNKNOWN_TRACK | INVALID_DURATION | INVALID_TIMEZONE 3) Reserve a Slot Atomically POST /interviews/bookings Idempotency-Key: 4f8c2a19-7e11-4d02-9a6b-83c105e2d904 { "candidate_id": 7810, "track": "backend", "start_utc": "2026-12-08T16:00:00Z", "duration_minutes": 60 } -> 201 Created { "booking_id": 1408, "status": "confirmed", "start_utc": "2026-12-08T16:00:00Z", "end_utc": "2026-12-08T17:00:00Z", "interviewer": {"id": 104, "name": "M. Patel"}, "meeting_link": null } -> 200 OK Exact same payload when replaying an earlier succeeded Idempotency-Key -> 409 Conflict SLOT_UNAVAILABLE {"alternatives": ["2026-12-08T16:30:00Z", "2026-12-08T18:00:00Z"]} -> 409 Conflict ALREADY_BOOKED (candidate already holds an active booking for this track) -> 422 Unproc. TOO_SOON (< 12h notice) | MISALIGNED_GRID | IDEMPOTENCY_KEY_REUSED -> 429 Too Many RATE_LIMITED (Retry-After: 5) -> 503 Unavail. DB_BUSY (nothing committed; safe to retry with the same Idempotency-Key)Supporting endpoints complete the lifecycle:
DELETE /interviews/bookings/{id}(candidate cancels) andPOST /interviewers/{id}/bookings/{booking_id}/decline(interviewer cannot attend, triggering automated reassignment). Notice thatGET /interviews/available-slotsreturns distinct start times without exposing interviewer names or remaining headcount, preventing candidates from cherry-picking interviewers or scraping team capacity.High-level architecture
Separating the read-heavy listing path from the strongly consistent booking path keeps both fast and simple:
Candidates (Web/Mobile) Interviewers Admins | | | v v v +---------------------------------------------------------------------------------+ | API Gateway: TLS, Auth, Per-User Rate Limiting, Request IDs | +---------------------------------------------------------------------------------+ | | | v v v +-----------------+ +---------------------+ +--------------------+ | Slots Service | | Booking Service | | Availability Svc | | (GET /slots) | | (POST /bookings) | | (POST /avail) | +-----------------+ +---------------------+ +--------------------+ | \ | | | fast path \ fallback |PgBouncer (tx pool) | v \ v v +----------+ `-----> +-------------------------------------------------------+ | Redis | | PostgreSQL Primary --> Sync Standby --> Read Replica | | Cached | | (slot, booking, load, day, outbox, audit_event) | | Counts | +-------------------------------------------------------+ +----------+ | ^ | Outbox Relay (polls & publishes) | v | +-------------------+ +--- Cache Updater <---------| Queue / Event Bus |---> Email & Calendar Invites (200ms coalesce, +-------------------+---> Video Meeting Link Worker recomputes day) \--> Reassignment Worker Hourly Expansion Worker ---> Materializes rolling 15-day `slot` & `interviewer_day` rows- Slot listings hit Redis first (~1–3 ms) and fall back to a read replica only if Redis is unreachable.
- Bookings always execute directly on the PostgreSQL primary.
- Slow external calls (creating a Zoom/Meet link, sending Google Calendar invites) run asynchronously off the outbox queue after the database transaction commits, so a slow third-party API never holds database row locks.
Deep dive 1: atomic booking without double-booking
Why does naive code fail? Suppose two candidates check
SELECT interviewer_id FROM slot WHERE start_at = '04:00' AND status = 'open' LIMIT 1at the same millisecond. Both read Interviewer 42, and without locking or constraints, both insert a booking for Interviewer 42—a classic check-then-act race condition.Even adding a plain pessimistic lock (
SELECT ... FOR UPDATE, which locks the selected row before modifying it) has a bottleneck: if 200 candidates want04:00and 50 interviewers are free, all 200 requests line up behind the single least-loaded interviewer's row lock one by one instead of spreading across the 50 free interviewers!PostgreSQL's
FOR UPDATE SKIP LOCKEDsolves both problems at once.SKIP LOCKEDtells the database: "Lock the first matching row that isn't currently locked by another in-flight transaction; if a row is already locked, skip right past it to the next eligible interviewer."Walk through three candidates (
C1,C2,C3) clicking Book 04:00–05:00 (60 min) at the exact same millisecond when only Interviewers42and77are free:Initial `slot` rows for 04:00 and 04:30: (interviewer 42, 04:00, open), (interviewer 42, 04:30, open) [utilization 20%] (interviewer 77, 04:00, open), (interviewer 77, 04:30, open) [utilization 35%] Millisecond 0: - C1 runs SELECT ... FOR UPDATE SKIP LOCKED -> locks (42, 04:00) and (42, 04:30). - C2 runs at the same instant -> sees 42's rows locked, SKIPS 42 without waiting, and immediately locks (77, 04:00) and (77, 04:30) in parallel! - C3 runs at the same instant -> sees both 42 and 77 locked, gets 0 rows back, rolls back in 1 ms, and returns 409 SLOT_UNAVAILABLE with nearby open times. Millisecond 2: - C1 and C2 both insert their `booking` rows, mark their locked slots `booked`, increment daily/weekly counters, write outbox + audit rows, and COMMIT in parallel.Here is the complete booking flow for a 60-minute interview (a 30-minute interview simply omits
s2):-- Pre-check before locking: if (candidate_id, idempotency_key) already exists, -- return the stored booking immediately as 200 OK. BEGIN; -- Isolation level: READ COMMITTED -- 1. Pick and lock ONE active, qualified interviewer under their daily cap -- who has BOTH consecutive 30-minute blocks open, least utilized first. SELECT s1.interviewer_id FROM slot s1 JOIN slot s2 ON s2.interviewer_id = s1.interviewer_id AND s2.start_at = s1.start_at + interval '30 minutes' AND s2.status = 'open' JOIN interviewer_track it ON it.interviewer_id = s1.interviewer_id AND it.track_id = :track_id JOIN interviewer i ON i.id = s1.interviewer_id AND i.active = true JOIN interviewer_day d ON d.interviewer_id = i.id AND d.local_date = (:start_utc AT TIME ZONE i.timezone)::date AND d.booked < i.max_per_day LEFT JOIN interviewer_load l ON l.interviewer_id = i.id AND l.week_start = :week_start WHERE s1.start_at = :start_utc AND s1.status = 'open' ORDER BY coalesce(l.booked_minutes, 0)::float / greatest(coalesce(l.offered_minutes, 0), 60), random() LIMIT 1 FOR UPDATE OF s1, s2 SKIP LOCKED; -- If 0 rows returned -> ROLLBACK and return 409 SLOT_UNAVAILABLE with alternatives. -- 2. Insert the booking (unique indexes & GiST exclusion constraint re-verify safety). INSERT INTO booking (candidate_id, track_id, interviewer_id, start_at, end_at, duration_min, status, idempotency_key) VALUES (:candidate_id, :track_id, :iid, :start_utc, :start_utc + interval '60 minutes', 60, 'confirmed', :idempotency_key) RETURNING id; -- 3. Mark both locked slot rows as booked. UPDATE slot SET status = 'booked', booking_id = :booking_id, version = version + 1 WHERE interviewer_id = :iid AND start_at IN (:start_utc, :start_utc + interval '30 minutes') AND status = 'open'; -- verify rowcount = 2; otherwise ROLLBACK -- 4. Atomically enforce max_per_day on the interviewer's local date row. UPDATE interviewer_day SET booked = booked + 1 WHERE interviewer_id = :iid AND local_date = (:start_utc AT TIME ZONE :interviewer_tz)::date AND booked < (SELECT max_per_day FROM interviewer WHERE id = :iid); -- If 0 rows updated (rare tie on last daily slot) -> ROLLBACK and retry excluding :iid. -- 5. Update weekly fairness counter, outbox event, and audit log atomically. INSERT INTO interviewer_load (interviewer_id, week_start, booked_minutes) VALUES (:iid, :week_start, 60) ON CONFLICT (interviewer_id, week_start) DO UPDATE SET booked_minutes = interviewer_load.booked_minutes + 60; INSERT INTO outbox (topic, payload) VALUES ('slot_changed', :event_json); INSERT INTO audit_event (actor_type, actor_id, action, entity, entity_id, request_id, after) VALUES ('candidate', :candidate_id, 'booked', 'booking', :booking_id, :req_id, :after_json); COMMIT;Critical concurrency details to highlight:
- Why stay on
READ COMMITTEDinstead ofREPEATABLE READ: In PostgreSQL, if another transaction committed an update to aslotrow micro-moments after our query started,READ COMMITTEDautomatically re-evaluatesWHERE status = 'open'on the newest committed row version and skips it cleanly. UnderREPEATABLE READ, locking a row modified since our snapshot raisesERROR: could not serialize access due to concurrent update, forcing unnecessary transaction retries. - Canonical lock ordering prevents deadlocks: Every write transaction (booking, cancellation, decline) acquires row locks in the exact same order:
slot(ordered bystart_at ASC) →interviewer_day→interviewer_load. Because no two transactions ever lock those tables in opposite orders, deadlocks between a booking and a simultaneous cancellation cannot form. - Why
SKIP LOCKEDbeats the alternatives here:- Optimistic locking (
UPDATE slot ... WHERE version = :old_vwithoutFOR UPDATE) avoids holding locks during reads and works on NoSQL stores, but during a 500/s spike, hundreds of requests all read the same #1 least-loaded interviewer, 499 fail the version check, and they retry in a thundering herd. - Redis distributed locks add an external point of failure: if a service process pauses (for example during garbage collection) past the Redis lock TTL, two processes can enter the critical section at once unless the database checks a monotonically increasing fencing token anyway—and since all our state lives in one PostgreSQL primary, native row locks + constraints are strictly simpler and safer.
- Optimistic locking (
- Why stay on
Deep dive 2: sub-100 ms 14-day slot listing with Redis
Listing answers the question: "For track
Tand durationD, which 30-minute start times in[from, to)have at least one eligible interviewer?"In PostgreSQL, the exact count per start time for a 60-minute interview is:
SELECT s1.start_at, count(*) AS free_interviewers FROM slot s1 JOIN slot s2 ON s2.interviewer_id = s1.interviewer_id AND s2.start_at = s1.start_at + interval '30 minutes' AND s2.status = 'open' JOIN interviewer_track it ON it.interviewer_id = s1.interviewer_id AND it.track_id = :track_id JOIN interviewer i ON i.id = s1.interviewer_id AND i.active = true JOIN interviewer_day d ON d.interviewer_id = i.id AND d.local_date = (s1.start_at AT TIME ZONE i.timezone)::date AND d.booked < i.max_per_day WHERE s1.status = 'open' AND s1.start_at >= :from_utc AND s1.start_at < :to_utc GROUP BY s1.start_at ORDER BY s1.start_at;Thanks to our partial index
slot_open_by_time, this query never scans closed or historical slots. Still, joining ~300,000 open rows takes ~10–20 ms of CPU—fine for background refreshes, too heavy to run 2,000 times per second on every candidate page refresh.Precomputed Redis Hash layout:
Key: slots:{track}:{duration}:{utc_date} (e.g. slots:backend:60:2026-12-01) Type: Redis Hash (up to 48 fields per UTC day) Field: "04:00" -> Value: "14" (14 qualified interviewers have 04:00 + 04:30 open) Field: "04:30" -> Value: "9" Field: "05:00" -> Value: "0"- Fast reads (~2–5 ms): Any query inside the 14-day window spans at most 15 UTC dates.
Slots Servicefetches all 15 Redis hashes in a single network round trip (a Redis pipeline), filters out counts<= 0and slots within the 12-hour notice cutoff, converts timestamps to the candidate's requestedtz, and returns in well under 100 ms at p95. - Self-healing updates via recomputation (not
HINCRBY): Whenever any transaction modifies availability (booking, cancellation, rule edit, daily cap reached), it writes{interviewer_id, affected_utc_date}tooutbox(plusaffected_utc_date - 1whenever a00:00 UTCblock changes, because a23:30 UTC60-minute interview spans midnight!). The Cache Updater batches (coalesces) events for the same(track, utc_date)over a 200 ms window, runs the SQLGROUP BYquery above against the primary (reading a lagging replica could overwrite fresh data with stale counts), and replaces that day's Redis hash. Recomputing from truth rather than incrementing/decrementing counters means a duplicated or delayed event can never cause permanent counter drift. A full 14-day rebuild every 5 minutes acts as a belt-and-suspenders safety net. - Database remains the source of truth: Redis may lag by ~200–500 ms. If a candidate clicks a slot that just filled up, the PostgreSQL booking transaction safely catches it and returns
409 SLOT_UNAVAILABLEwith fresh nearby slots. During extreme spikes,Booking Servicecan optionally reject requests whose Redis count is already0before touching PostgreSQL.
- Fast reads (~2–5 ms): Any query inside the 14-day window spans at most 15 UTC dates.
Deep dive 3: fair load distribution and daily caps
"Fairness" has a trap if we only count raw interviews:
Suppose both Alice and Bob are qualified for Backend: - Alice volunteers 2 hours/week (4 blocks). 2 interviews = 100% of her offered time! - Bob volunteers 20 hours/week (40 blocks). 2 interviews = 10% of his offered time!If we ranked interviewers by lowest raw interview count, Alice would be booked solid every single week while Bob sat 90% idle—punishing the interviewers who volunteer less time and wasting most of our capacity.
Instead, we rank by weekly utilization ratio:
booked_minutes / offered_minutes:interviewer_load.offered_minutesis maintained by the expansion job;booked_minutesis incremented/decremented inside booking and cancellation transactions (greatest(offered_minutes, 60)guards against division by zero if a rule was just added).- Ties are broken with
random()so interviewer ID1doesn't get hammered ahead of ID5000at the start of every week. - Under heavy concurrency,
SKIP LOCKEDnaturally routes simultaneous requests down the utilization ranking—1st least-utilized, 2nd least-utilized, 3rd least-utilized—preserving fairness without coordination bottlenecks. - Asynchronous daily-cap cleanup: When
UPDATE interviewer_dayhitsbooked == max_per_day, we do not try to lock and flip that interviewer's remaining open slots for the day inside the booking transaction (doing so could wait on another block currently locked by a parallel booking, risking a deadlock). Instead, Step 1'sd.booked < i.max_per_dayjoin immediately stops new bookings from picking them, and the outbox consumer marks their remaining day slotsblockedand refreshes Redis right after commit.
Spikes, failure modes, observability, and trade-offs
Surviving a 500 attempts/s cohort release spike
- Connection pooling: Application pods connect through PgBouncer in transaction-pooling mode (a lightweight proxy that hands a PostgreSQL server connection to a query only for the few milliseconds its transaction runs), capping backend connections at ~50–80 so PostgreSQL never thrashes CPU on thousands of idle sockets. If the pool waits more than 1 second, return
503 DB_BUSYso clients retry cleanly with the sameIdempotency-Key. - Edge protection: Per-candidate rate limits (such as 5 booking attempts/minute) and the
one_active_booking_per_trackunique index stop scripts from hoarding slots.
Failure modes and recovery
- Network timeout after commit: Client retries with the same
Idempotency-Key, hits the pre-check (orUNIQUE (candidate_id, idempotency_key)), and receives200 OKwith the original booking. - Primary database crash: Promote the synchronous standby (zero committed bookings lost; RPO = 0, meaning Recovery Point Objective—the maximum age of data that could be lost—is zero). In-flight transactions fail and clients safely retry.
- Interviewer declines a confirmed interview: The decline endpoint marks the interviewer's blocks
blocked, setsbooking.status = 'needs_interviewer'andinterviewer_id = NULL(keeping the candidate's confirmed time intact!), decrements counters, and emits an outbox event for the Reassignment Worker. - Redis down:
Slots Servicetrips a circuit breaker and queries the PostgreSQL read replica with stricter caching/rate limits while Redis recovers.
Observability and invariant checks
- Key metrics: Slot listing p50/p95/p99 latency, booking transaction duration,
409 SLOT_UNAVAILABLErate (spikes indicate stale cache or low interviewer supply), PgBouncer queue wait time, outbox lag, and weekly utilization spread (p90 - p10utilization per track). - Automated invariant queries (run every 5 minutes; alert immediately if row count > 0): any
confirmedbooking whoseslotrows are notbookedwith matchingbooking_id, or anybookedslot pointing to a non-confirmed booking.
Summary of design trade-offs
- Discrete 30-minute materialized blocks vs. free-form intervals: Requires an expansion job and fixes interview lengths to multiples of 30 minutes, in exchange for turning overlap math into fast primary-key lookups and row locks.
FOR UPDATE SKIP LOCKED+ GiST exclusion constraint: Couples us to a relational database like PostgreSQL (or MySQL 8+ forSKIP LOCKED), in exchange for parallel lock-free throughput across interviewers and an ironclad zero-double-booking guarantee.- Event-recomputed Redis counts vs. live SQL
GROUP BY: Accepts < 1 second of listing staleness (safely absorbed as409s on booking) to keep p95 reads well under 100 ms at 2,000 req/s.
- Connection pooling: Application pods connect through PgBouncer in transaction-pooling mode (a lightweight proxy that hands a PostgreSQL server connection to a query only for the few milliseconds its transaction runs), capping backend connections at ~50–80 so PostgreSQL never thrashes CPU on thousands of idle sockets. If the pool waits more than 1 second, return
Intuition & how it works
Think of an airport passport-control hall at 10:00 AM with 50 open booths, plus a digital lobby board outside that simply shows "10:00 AM — Open" as long as at least one officer is free. When a crowd of passengers rushes in at once, you do not want everyone standing in a single-file line behind Booth 1 while Booths 2 through 50 sit empty—you want each arriving passenger to walk straight past any occupied booth into the first unlocked booth, while the lobby board updates a moment later in the background.
A naive implementation breaks in three ways under load. First, checking "is an interviewer free at 10:00?" with a plain SELECT and inserting a booking in a separate step lets two simultaneous requests pick the exact same interviewer and double-book them. Second, locking only the top-ranked interviewer with a standard SELECT ... FOR UPDATE forces 500 concurrent candidates during a recruiting cohort drop to wait behind a single database row lock one at a time, spiking latency and timing out requests. Third, expanding weekly recurring calendar rules across 5,000 interviewers on every page view burns far too much database CPU to hit a 100 ms p95 latency target.
To make both paths fast and exact, we materialize availability into fixed 30-minute UTC rows in a slot table, serve read-heavy 14-day listings from precomputed Redis counts, and execute bookings directly on PostgreSQL using FOR UPDATE SKIP LOCKED (a row-locking clause that locks the first matching unlocked row and immediately skips rows locked by other in-flight transactions). Walk through three candidates—C1, C2, and C3—clicking Book Monday 10:00–11:00 Backend at the exact same millisecond when only Interviewers I1 (20% weekly utilization) and I2 (35% weekly utilization) have both their 10:00 and 10:30 blocks open:
- Before the rush: Redis holds
slots:backend:60:2026-12-07 -> {"10:00": 2}, so all three candidates load the calendar in ~3 ms and see10:00as open. C1arrives: PostgreSQL locks(I1, 10:00)and(I1, 10:30), insertsC1's confirmed booking, flips both blocks tobooked, incrementsI1's daily and weekly counters, and writes an event to the transactional outbox (a database table committed in the same transaction as business data so background events are never lost).C2arrives in the same millisecond: PostgreSQL seesI1's blocks are locked, skipsI1with zero waiting viaSKIP LOCKED, immediately locks(I2, 10:00)and(I2, 10:30), and confirmsC2in parallel.C3arrives in the same millisecond: BothI1andI2are locked, so the query returns zero rows in ~1 ms andC3gets a clean409 SLOT_UNAVAILABLEresponse listing nearby open times like10:30and11:00, while the outbox worker recomputes the Redis count for10:00to0.
Key trade-offs
- Pessimistic
SKIP LOCKEDvs. optimistic version checks. Pessimistic locking locks the chosenslotrows before updating them, andSKIP LOCKEDlets hundreds of concurrent requests grab different interviewers in parallel without retries; the trade-off is requiring PostgreSQL 9.5+ or MySQL 8.0+ and keeping transactions a few milliseconds short. Optimistic locking (storing aversioninteger on each row and updating withWHERE version = old_versionwithout holding locks) works on any key-value store, but during a 500/s spike, hundreds of requests read the same #1 least-utilized interviewer, all but one fail the version check, and they retry in a thundering herd. - Database row locks + exclusion constraint vs. external Redis distributed locks. Keeping all booking state in one PostgreSQL primary lets row locks guide concurrency while a GiST exclusion constraint (a database-enforced rule preventing two confirmed bookings for the same interviewer from having overlapping
[start_at, end_at)time ranges) guarantees safety. Adding an external Redis lock introduces split-brain failure modes—if an application process pauses past the Redis lock expiry, two processes can enter at once unless the database checks a monotonically increasing fencing token anyway. - Materialized 30-minute blocks vs. on-the-fly recurrence math. Expanding recurring rules into discrete
:00and:30rows requires an hourly background job and restricts durations to multiples of 30 minutes, but turns "find, lock, and count availability" into simple indexed row operations instead of complex interval-intersection queries. - Precomputed Redis hashes vs. live SQL aggregation. Serving
GET /available-slotsfrom Redis hashes (slots:{track}:{duration}:{utc_date}) keeps p95 latency in single-digit milliseconds and shields PostgreSQL during 2,000 req/s browsing spikes. The trade-off is ~200–500 ms of cache staleness, which is harmless becausePOST /bookingsalways checks PostgreSQL as the single source of truth. - Idempotent full-day recomputation vs.
HINCRBYcounter deltas. Having the outbox consumer recompute an affected(track, utc_date)hash from the primary database does slightly more SQL work per event than+1/-1increments, but is idempotent (safe to apply multiple times without changing the result) and self-healing—a retried or out-of-order message can never permanently corrupt slot counts. - Weekly utilization ratio (
booked_minutes / offered_minutes) vs. equal interview counts. Equal raw counts overload an interviewer who offered 2 hours a week while leaving someone who offered 20 hours mostly idle; utilization ratio shares load proportionally to offered capacity.
Common mistakes
- Check-then-insert without row locks or database constraints, allowing two concurrent transactions to see the same open interviewer and double-book them.
- Using plain
SELECT ... FOR UPDATEwithoutSKIP LOCKED, forcing every concurrent candidate requesting 10:00 AM to wait serially behind the exact same top-ranked interviewer's lock. - Running
FOR UPDATEunderREPEATABLE READorSERIALIZABLEisolation without retry logic, which causes PostgreSQL to abort concurrent transactions with serialization errors whenever a row changes after the transaction snapshot started. - Calling slow external calendar or video-conferencing APIs inside the database transaction, holding row locks and exhausting connection pools for hundreds of milliseconds per request instead of offloading side effects via the transactional outbox.
- Checking only the first 30-minute block when booking a 60-minute interview, allowing a 10:00–11:00 interview and a 10:30–11:30 interview to collide on the 10:30 block.
- Forgetting to filter
interviewer.active = trueandbooked < max_per_dayin both the booking query and the cache query, either assigning deactivated/capped interviewers or showing phantom slots in Redis that always fail with409on click. - Expanding recurring rules using fixed UTC offsets instead of IANA time zones (region names like
America/New_Yorkthat track Daylight Saving Time), causing "Mondays at 09:00" to shift to 08:00 or 10:00 twice a year. - Omitting an
Idempotency-Keyheader (a unique per-click token sent by the client), so retrying after a mobile network timeout books a second interview or throws a spurious error instead of replaying the original confirmation.
Follow-up questions
- How would you extend the booking transaction to schedule multi-interviewer panels that need distinct role specialties at the same time (such as a backend specialist paired with an engineering manager)? Execute all role picks inside a single PostgreSQL transaction, running the
SELECT ... FOR UPDATE SKIP LOCKEDquery once per required track starting with the scarcest track first and excluding already-selected interviewers (interviewer_id <> ALL(:picked_ids)), rolling back cleanly if any role cannot be filled. Because a dual-qualified interviewer picked for Role 1 might have been the only available person for Role 2, retry the small bipartite matching with that person excluded on Role 1 if Role 2 comes up empty—with only 2–3 roles, this takes milliseconds, and updatinginterviewer_dayandinterviewer_loadin ascendinginterviewer_idorder prevents deadlocks between concurrent panel bookings. ForGET /available-slots, the cache updater computes a panel-specific Redis hash by checking whether distinct interviewers exist across the panel's tracks at each 30-minute start time rather than trusting independent per-track counts. - Suppose an assigned interviewer drops out two hours prior to start time—how can the platform automatically swap in a replacement without voiding the candidate's confirmed time slot? When the interviewer calls
/decline, a single transaction marks their blocksblocked, setsbooking.status = 'needs_interviewer'andinterviewer_id = NULL(preserving the candidate's booking ID, confirmed time, and calendar invite), decrements the old interviewer's counters, and writes an outbox event. A Reassignment Worker immediately runs the standardSKIP LOCKEDquery for that track and window; if an open interviewer is found, it assigns them atomically, updates the video link and interviewer invite, and leaves the candidate undisturbed. If zero open slots exist, the worker pings qualified active interviewers who have no conflicting booking, using an atomic conditional update (UPDATE booking SET interviewer_id = :me, status = 'confirmed' WHERE id = :id AND status = 'needs_interviewer') so the first volunteer wins, and pages a recruiting coordinator to offer priority rescheduling if still unfilled 30 minutes before start time. - How must your concurrency control evolve once the system outgrows one primary relational node and moves to horizontal sharding or active-active regions? Shard horizontally by
interviewer_id(and in multi-region setups, assign each interviewer a home write region), so every interviewer'sslot,interviewer_day,interviewer_load, and assignedbookingrows still co-locate on one shard whereSELECT ... FOR UPDATE SKIP LOCKEDworks unchanged inside a local transaction. The Booking Service consults per-shard Redis counts to pick a shard with free capacity and falls back to the next shard on409, while cross-shard invariants like "at most one active booking per candidate per track" use a saga (a sequence of local transactions with compensating undo steps): first insert a short-lived reservation row on the candidate's shard, then book on the interviewer's shard, and release the candidate reservation if all shards are full. Alternatively, a distributed SQL database (such as Google Cloud Spanner or CockroachDB) preserves single-transaction cross-shard guarantees at the cost of higher consensus commit latency (~10–50 ms).
Follow-up questions
- How would you extend the booking transaction to schedule multi-interviewer panels that need distinct role specialties at the same time (such as a backend specialist paired with an engineering manager)?
- Suppose an assigned interviewer drops out two hours prior to start time—how can the platform automatically swap in a replacement without voiding the candidate's confirmed time slot?
- How must your concurrency control evolve once the system outgrows one primary relational node and moves to horizontal sharding or active-active regions?
Similar questions
- Snapshot Queries on a Versioned Array
- Check Lexicographical Order With Custom Alphabet
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests