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.
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'.
"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, HOLDLOCKtransaction, 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."
| 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 |
| 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 |
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
| 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 |
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].
Checks that the candidate prevents double-booking with database guarantees and separates the heavy read path from the strongly consistent write path.
Green flags
Red flags
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.
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.
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.
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.
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.
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.
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.
UPDLOCK, HOLDLOCK and test concurrently with overlapping intervals.FakeTimeProvider.Australia/Adelaide across the daylight saving change and check the count.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.
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.WHERE HeldBy = @me AND HoldExpiresAt > now.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.
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.
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.
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.
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.
Last updated 23 Nov 2026.