📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Design a booking system that must never double-book: appointments with practitioners at a chain of clinics, or reserved seats for a concert. Walk me through availability search, holding a slot or seat while the customer pays, preventing two people from booking the same thing, cancellations, and surviving a big on-sale rush.

A full booking system design: requirements and on-sale estimates, slot and seat data models, double-booking prevention with unique constraints or locked range checks, holds with expiry, idempotent confirm with payment, availability caching, waiting rooms for on-sales, time zones and cancellations, on Azure with .NET.

Senior SystemDesign Advanced booking caching concurrency system-design unique-constraints waiting-room

🎯 Key points

  • Clarify: fixed slots vs variable durations, seats vs general admission, hold time, payment timing, cancellations
  • Estimate: clinics are low volume; a concert on-sale is 200k users for 50k seats in minutes
  • Fixed units (seats, materialised slots): the database enforces it with a unique key on (EventId, SeatId) or (PractitionerId, SlotStart) and conditional status updates
  • Variable durations: a unique key on start alone can't catch overlaps, so book contiguous materialised slots, or run the overlap check (start < @end AND end > @start) under UPDLOCK, HOLDLOCK
  • Hold = row with ExpiresAt; confirm only an unexpired hold owned by the user, with an idempotency key; sweeper releases
  • Availability from a cache/projection; final check at the database; on 'just taken' the UI refreshes and offers the nearest alternatives
  • On-sale: virtual waiting room, seat map from cache, short holds, per-account limits
  • UTC + IANA time zone per location; cancellations release slots and offer them to the waitlist by email/push with a short hold

⏱ 30-second answer

I make the database enforce no double-booking, not application code. For fixed slots or seats, each bookable unit is a row and a unique constraint on (ResourceId, SlotStart) or (EventId, SeatId) makes the second insert fail. For variable-length appointments, I either materialise slot rows or check for overlaps inside a transaction with range locks (UPDLOCK, HOLDLOCK). The customer gets a hold with an expiry while paying; confirm only succeeds for an unexpired hold they own, and a sweeper releases the rest. Availability search reads a cache, because it's 100× the traffic of bookings, while the final check always hits the database. For a concert on-sale I add a waiting room and short holds. The trade-off: caches can show a seat that's just gone, so the UI must handle a polite 'just taken'.

🗣 Full answer (senior)

How I would answer this in an interview

"These are two flavours of the same problem, so I'd clarify which. Clinic appointments: [200] clinics, practitioners with variable appointment lengths, low volume, a few bookings a second, but customers hate being double-booked. Concert seats: fixed seats, tiny bursts of extreme demand, 200,000 people for 50,000 seats in the first ten minutes. The core rule is the same: the database is the arbiter.

For seats, each seat for an event is a row, and holding a seat is a conditional update: set status to Held with my session and an expiry where status is Available or the hold has expired. One row changes, I have it; zero rows, someone beat me. Confirming after payment only works if the hold is still mine and unexpired, and it's keyed by an idempotency key so a retried confirm doesn't fail or double-charge. For clinic appointments with variable durations I'd materialise bookable 5- or 15-minute slots per practitioner and book a contiguous set in one transaction, so a unique index still does the work. If I can't materialise, I check for overlap in a serializable or UPDLOCK, HOLDLOCK transaction, which takes key-range locks so two overlapping inserts can't both pass the check.

For example, at [company] we [had double bookings because the app checked availability, then inserted]; [adding a unique constraint on practitioner and slot] [stopped them overnight and surfaced a retry bug we then fixed].

Availability search is the heavy read path, so it comes from a cached projection updated by events. On-sale day gets a virtual waiting room that admits buyers at a controlled rate, holds of five minutes, and a limit of tickets per account.

The mistake I see is 'check then insert' in application code, maybe with a C# lock that works on one server. If two requests on two servers can both book, the design is wrong; let the database say no."


Requirements

Type Requirement Assumption
Functional Search availability by location, practitioner, date Clinics in several Australian time zones
Functional Hold, pay, confirm; cancel and reschedule Hold 10 min (clinic), 5 min (seats)
Functional Waitlist on cancellation Notify in order
Non-functional Zero double-bookings Enforced by DB constraints
Non-functional Search p95 < 200 ms Cached projection
Non-functional On-sale: 200k users, no collapse Waiting room

Capacity estimate

Quantity Arithmetic Result
Clinic bookings/day 200 clinics × 10 practitioners × 25 50,000 (≈ 0.6/s, peak 10/s)
Clinic slot rows/year 2,000 practitioners × 32 slots/day × 260 days ≈ 17M
On-sale demand 200k users in 10 min ≈ 330 arrivals/s, with initial spikes far higher
Seat map reads 200k users × refresh every 5 s ≈ 40,000/s → cache only
Seat holds 50k seats sold in ~15 min ≈ 55 holds/s average, bursts of 2,000/s

High-level design

Users ──► Front Door ──► Waiting room (on-sale only, signed admission token)
                              │
                              ▼
               Booking API (ASP.NET Core) ── search ──► Availability projection (Redis / Cosmos DB)
                  │  hold / confirm / cancel                   ▲ events (outbox)
                  ▼                                            │
               Azure SQL: Slots/Seats (unique keys), Holds, Bookings ──┘
                  │
                  ├──► Payment service (idempotent charge)
                  └──► Notifications (confirmations, reminders, waitlist)
               Sweeper: releases expired holds every 30 s

Preventing double-booking

Technique Fits How it works
Unique index on unit Seats, fixed slots Second insert fails (error 2601/2627)
Conditional status update Pre-created seat rows WHERE Status='Available' OR HoldExpiresAt < now
Materialised slots Variable durations Book N contiguous slot rows in one transaction
Range-locked overlap check Free-form intervals UPDLOCK, HOLDLOCK / SERIALIZABLE on the overlap query

Production example

A clinic booking platform with [180] clinics moved from check-then-insert to materialised 5-minute slots with a unique index: double-bookings went from [about 15 a month] to zero, and the availability projection served [95%] of searches from Redis with p95 [60 ms].

🔍 What the interviewer is checking

Checks that the candidate prevents double-booking with database guarantees and separates the heavy read path from the strongly consistent write path.

Green flags

  • Unique constraints or conditional updates, and range locks for intervals
  • Holds with expiry, owned confirms and idempotency
  • Cached availability with final check at the database
  • Waiting room and per-user limits for on-sales; time zones handled

Red flags

  • Check-then-insert or in-process locks
  • No hold expiry
  • Seat map served from the transactional database at peak
  • Local times without zones

📚 Learn in depth

1. Why check-then-insert fails

Req A: SELECT overlaps for Dr Lee 10:00–10:30 → none
Req B: SELECT overlaps for Dr Lee 10:15–10:45 → none
Req A: INSERT booking                Req B: INSERT booking   ← overlap

Under READ COMMITTED (or RCSI) neither SELECT blocks the other's insert. A C# lock only serialises one process. Fix it in the database.

2. Fixed units: let a unique key decide

Seats: EventSeats(EventId, SeatId, Status, HeldBy, HoldExpiresAt, BookingId) with PK (EventId, SeatId). Holding is a conditional update; booking flips Held → Booked only WHERE HeldBy = @me AND HoldExpiresAt > now. Multiple seats: update all in one statement and check @@ROWCOUNT = @requested, rolling back otherwise, so a group never gets a partial set.

3. Variable durations

Materialise slots: generate rows for each practitioner's working hours at a granularity (5 or 15 minutes). A 30-minute appointment books six 5-minute rows in one transaction; all six must be free. Unique key (PractitionerId, SlotStart) and a status make it impossible to overlap. Rosters change, so slot generation is a job that runs when schedules change.

Range-locked overlap check: if intervals are free-form, run the overlap query with WITH (UPDLOCK, HOLDLOCK) inside the transaction, with an index on (PractitionerId, StartsAt). HOLDLOCK takes key-range locks, so a concurrent transaction trying to insert an overlapping interval blocks until the first commits, then sees it. It is correct but can deadlock and reduces concurrency; keep transactions tiny.

4. Holds and expiry

A hold is a short lease. Expiry is lazy (the conditional update treats expired holds as available) plus a sweeper that resets them so search projections update. Holds must be short enough to stop hoarding and long enough for 3-D Secure; 5–10 minutes is typical. Payment outcome unknown → extend the hold and resolve.

5. Availability search

Search is read-heavy and tolerant of a few seconds' staleness. Build a projection per practitioner-day or per event section (counts and free seat ids) in Redis or Cosmos DB, updated from outbox events. The UI shows 'available' from the projection; the hold call is the truth. On a 'just taken' response, refresh the section.

6. On-sale rush

  • Virtual waiting room in front of the booking API (third-party or custom with signed tokens and an admission rate).
  • Seat map served from cache/CDN with section-level availability; seat-level only after admission.
  • Per-account ticket limits and bot protection (Front Door WAF, CAPTCHA at entry).
  • Pre-scale: Azure SQL scaled up before the sale; connection pools sized; load-tested.

7. Time zones and cancellations

Store UTC plus the clinic's IANA zone (Australia/Brisbane has no daylight saving; Australia/Sydney does). Display and reminders convert per clinic. A cancellation releases the slot rows and emits an event; the waitlist offers it to the next person with a short hold.

8. AWS mapping

Aurora/RDS with the same constraints, or DynamoDB conditional writes (attribute_not_exists on seat key), ElastiCache for availability, SQS for events; waiting room via third party or CloudFront + Lambda@Edge.

Try it yourself

  1. Fire 100 parallel bookings for the same slot with check-then-insert, count doubles, then add the unique index.
  2. Implement the overlap check with and without UPDLOCK, HOLDLOCK and test concurrently with overlapping intervals.
  3. Hold 4 seats where one is taken and confirm the whole request rolls back.
  4. Write a test that a hold expires and another user can take the seat, using FakeTimeProvider.
  5. Generate slots for a practitioner in Australia/Adelaide across the daylight saving change and check the count.

💻 Code

Holding seats atomically (all or nothing), confirming only an owned unexpired hold, and a range-locked overlap check for free-form appointments.

using System.Data;
using Microsoft.Data.SqlClient;

namespace Booking;

public sealed record HoldRequest(Guid EventId, IReadOnlyList<string> SeatIds, Guid SessionId);

public sealed class SeatHoldService(string connectionString, TimeProvider clock)
{
    private static readonly TimeSpan HoldFor = TimeSpan.FromMinutes(5);

    public async Task<bool> TryHoldAsync(HoldRequest r, CancellationToken ct)
    {
        var now = clock.GetUtcNow().UtcDateTime;
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);

        // Conditional update of all requested seats; expired holds count as available.
        await using var cmd = new SqlCommand("""
            UPDATE dbo.EventSeats
            SET Status = 'Held', HeldBy = @session, HoldExpiresAt = @expires
            WHERE EventId = @event AND SeatId IN (SELECT value FROM STRING_SPLIT(@seats, ','))
              AND (Status = 'Available' OR (Status = 'Held' AND HoldExpiresAt < @now));
            """, conn, tx);
        cmd.Parameters.AddWithValue("@session", r.SessionId);
        cmd.Parameters.AddWithValue("@expires", now.Add(HoldFor));
        cmd.Parameters.AddWithValue("@event", r.EventId);
        cmd.Parameters.AddWithValue("@seats", string.Join(',', r.SeatIds));
        cmd.Parameters.AddWithValue("@now", now);

        var held = await cmd.ExecuteNonQueryAsync(ct);
        if (held != r.SeatIds.Count) { await tx.RollbackAsync(ct); return false; } // all or nothing for a group
        await tx.CommitAsync(ct);
        return true;
    }
}
-- Confirm: only my unexpired hold becomes a booking (run with the idempotency key recorded in the same transaction).
UPDATE dbo.EventSeats SET Status = 'Booked', BookingId = @booking
WHERE EventId = @event AND SeatId IN (SELECT value FROM STRING_SPLIT(@seats, ','))
  AND Status = 'Held' AND HeldBy = @session AND HoldExpiresAt > SYSUTCDATETIME();

-- Free-form appointments: range locks stop a concurrent overlapping insert between check and insert.
BEGIN TRAN;
IF NOT EXISTS (
    SELECT 1 FROM dbo.Appointments WITH (UPDLOCK, HOLDLOCK)
    WHERE PractitionerId = @p AND StartsAt < @end AND EndsAt > @start AND Status <> 'Cancelled')
    INSERT dbo.Appointments(Id, PractitionerId, StartsAt, EndsAt, PatientRef, Status)
    VALUES (NEWID(), @p, @start, @end, @patient, 'Booked');
COMMIT;
-- Needs an index on (PractitionerId, StartsAt) INCLUDE (EndsAt, Status) so the range lock is narrow.

⚠ Common mistakes

  • Mistake: Check availability, then insert, in application code. Why it is wrong: concurrent requests both pass the check and both insert. Instead: unique constraints, conditional updates, or range-locked checks in one transaction.
  • Mistake: Using a C# lock or SemaphoreSlim to serialise bookings. Why it is wrong: it only works inside one process; a second instance double-books. Instead: database constraints, or a distributed lease only if there's no database way.
  • Mistake: Holds with no expiry. Why it is wrong: abandoned sessions and bots hoard seats until the event sells out on paper. Instead: short holds, lazy expiry in the predicate and a sweeper.
  • Mistake: Confirming without checking the hold owner and expiry. Why it is wrong: a slow payer can confirm a seat already re-held and paid for by someone else. Instead: confirm only WHERE HeldBy = @me AND HoldExpiresAt > now.
  • Mistake: Serving the seat map from the database during an on-sale. Why it is wrong: tens of thousands of map refreshes a second swamp the database that must process holds. Instead: a cached projection, section-level counts and a waiting room.
  • Mistake: Storing local times without a time zone. Why it is wrong: daylight saving differs between states, so appointments shift by an hour twice a year. Instead: UTC plus the location's IANA zone.
  • Mistake: Partial group holds. Why it is wrong: a family gets two of four seats and abandons them, wasting inventory. Instead: all-or-nothing holds checked by row count.

🏛 Senior insight: trade-offs

Senior designs separate the read path (search, maps: cached, stale, huge) from the write path (holds, bookings: tiny, strongly consistent, database-enforced), and they treat on-sale as a capacity event planned like a launch. I'd also point out that materialising slots often beats clever interval logic: it trades some storage for constraints the database can enforce cheaply.

Option When it fits Cost When not to
Unique key / conditional update Seats, fixed slots Pre-created rows Free-form intervals
Materialised time slots Variable lengths on a grid Slot generation job, storage Truly arbitrary times
Range-locked overlap check Free-form intervals, low volume Lower concurrency, deadlock retries High-contention resources
Waiting room Predictable rushes Third-party or build effort Clinics' everyday traffic

I measure double-bookings (zero, verified by a nightly overlap query), hold-to-booking conversion, hold expiry rate, 'just taken' responses, and search cache hit rate and staleness.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions serializable or range locks Why: Checks isolation levels, phantoms and how serializable prevents them
    How to answer

    Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.

    The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.

  2. When: Candidate mentions holding inventory while the customer pays Why: Checks reservation with expiry, sagas and compensation in checkout
    How to answer

    Never overselling comes down to one atomic, conditional reservation: UPDATE Stock SET Available = Available - @qty WHERE Sku = @sku AND Available >= @qty. Zero rows means sold out. I reserve at checkout, not at add-to-cart, with a reservation row and an expiry (say 10 minutes) and a sweeper that releases expired holds. The flow is a saga: reserve stock → take payment → confirm the order; if payment fails, compensate by releasing the reservation. Each step is idempotent and events go through an outbox. For a flash sale, one SKU row becomes a lock hotspot, so I split its stock into buckets or use a Redis counter with the database as the record, and add a waiting room. The trade-off: strong consistency only on the reservation, eventual consistency everywhere else.

  3. When: Candidate says confirm is safe to retry Why: Checks idempotency keys and concurrent duplicates
    How to answer

    An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.

🛠 Real-world problems: how you handle them

Double-booked appointments after scaling out the booking API
Situation
Online booking for [a physiotherapy chain], [180] clinics across [NSW, QLD and WA], [ASP.NET Core on App Service] with Azure SQL. Scaled from one to [four] instances for a winter promotion.
Signals
Front-desk staff reported two patients arriving for the same slot, [about 15] times in the first month; complaints to support; no errors in logs.
Investigation
Found a `SemaphoreSlim` guarding check-then-insert, which only serialised requests within one instance. Reproduced with a parallel load test against two instances. A nightly overlap query found [41] historical overlaps.
Resolution
Immediate: contacted affected patients and ran the overlap query hourly to catch new cases. Long term: materialised 5-minute slots with a unique index on (PractitionerId, SlotStart), bookings take contiguous slots in one transaction, holds with expiry for online payment, and clinic time zones stored as IANA ids.
Prevention
Concurrency test in CI against two app instances; nightly overlap check that alerts on any result; code review rule: 'no in-process locks for business invariants'.

How to tell it (STAR)

**S:** At [company] patients started arriving for the same physio slot after we scaled the booking API to [four] instances, about [15] times a month. **T:** I needed to stop double-bookings and prove they couldn't come back. **A:** I found a `SemaphoreSlim` around check-then-insert, which only protected a single instance. I moved the rule into the database: materialised 5-minute slots with a unique index, contiguous slots booked in one transaction, and holds with expiry for online payment. I added a two-instance concurrency test in CI and a nightly overlap query that alerts. **R:** Double-bookings went to [zero] and stayed there through [two] peak seasons, and we could scale instances freely.

More in Systems to Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me