Case study: design a ticket booking system
A senior-level walkthrough of ticket and seat booking: atomic seat holds, all-or-nothing party holds without deadlocks, choosing the hold time, the on-sale surge and the waiting room, and live availability, with tested C#.
Case studyApplied38 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 2 data models
- 1 API design
- 9 code samples
- 10 interviewer follow-ups
- 5 self-checks
On this page15 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Rate limiting, Case study: design a payment system
- Inventory that can be sold once needs an atomic claim, a conditional update on the seat and never a read followed by a write, with a unique constraint on the sale as the last line of defence.
- Hold a party's seats all or nothing, locking in one global order so that overlapping buyers cannot deadlock, and let a hold expire by comparing times so that nobody has to sweep it first.
- Pick the hold time from the payment-time distribution and extend it while a payment is in progress. A 2-minute hold with extension sold out in 1,225 s with 11.5% of payers losing the seat, against 2,909 s and 7.3% for a plain 5-minute hold.
- The on-sale surge is handled in front of the system. A waiting room admits shoppers at a rate set by Little's law and the inventory, not by server capacity, and the availability of a whole venue is a 15 KB blob that a CDN serves.
- Let the server choose seats where it can, defend against bots, and prepare the senior answers on fairness, late payments, hotels and testing.
6 code samples (254 lines), collapsed so the explanation stays in focus.
A ticket booking system has one rule that matters more than any other: a seat is sold once. Everything else, the seat map, the checkout, the confirmation email, is built around that rule and around the uncomfortable fact that when tickets for a famous show go on sale, millions of people want the same few thousand seats within the same minute. The first problem is a concurrency problem, because two buyers can pick the same seat at the same instant. The second is a traffic problem, because the surge is hundreds of times what the system sees on an ordinary day. And the third is a human problem, because most people lose, and the system has to treat them honestly.
This lesson builds the design around those three and tests the core pieces in C#: a seat map whose holds are atomic and all-or-nothing, a simulation of how long a hold should last, and a simulation of what happens when everyone picks the best seats. It uses the payment system for the money, rate limiting for the front door, and the CDN ideas from DNS, CDNs and the edge for the seat map.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| Reserved seats, general admission, or both? | Reserved seats are individual rows with an owner. General admission is a counter, which is much easier |
| Is it events, or hotels and flights? | Hotels and flights sell counts of rooms or seats per date range, so a booking touches several counters at once |
| How large is the biggest on-sale? | Fifty thousand seats and five million fans decide whether a waiting room is needed |
| Do buyers pick seats, or does the system assign them? | Picking creates contention on the best seats. Assigning lets the server spread it |
| How long may a seat be held while someone pays? | It is the main trade-off between lost buyers and locked inventory |
| Party size and limits per account? | Parties need all-or-nothing holds, and limits are the first defence against resellers' bots |
| Refunds, transfers, resale? | Each adds states. Scope them out and say how you would extend |
| What must never happen? | The same seat sold twice, a buyer charged with no ticket, or a ticket with no payment |
A good scope for 45 minutes: browse an event, choose or be assigned seats, hold them for a few minutes, pay, and receive tickets, with an on-sale surge in mind. Mention resale, transfers, dynamic pricing and fraud as extensions.
State assumptions out loud. They are illustrative and the interviewer may change them.
event: 60,000 seats (assumed), one on-sale, 5M fans waiting
orders: 60,000 seats / 2.5 seats per order = ~24,000 orders
conversion: ~70% of admitted shoppers pay = ~34,000 admitted
shop time: ~5 minutes from first click to paid (select, hold, pay)
admit rate: 34,000 shoppers over ~7 minutes (420 s) = ~80 a second
in the shop: 80 a second x 300 s = ~24,000 at once, as many as the orders
not admitted: 5M - 34,000 = ~99.3% of the fans, told "sold out"
availability: 60,000 seats x 2 bits = 15 KB for the whole venue
polling: 1M viewers every 2 s x 15 KB = ~7.5 GB/s, from the CDNFive conclusions:
- Reads dwarf writes. Millions look at the seat map and tens of thousands buy. The map is cached at the edge, and the writes that matter are few, concentrated on the same hot rows.
- The admission rate is set by inventory, not by server capacity. By Little's law, the shoppers inside at once equal the admission rate times the time they spend, and that number should not exceed the orders the seats can absorb. That is about 80 a second here, far below what the servers could take, so a bigger server fleet does not help. A waiting room's job is fairness and protection.
- Nearly everyone loses. About 99% of the fans never get in. The system should say so early and honestly, show a real position, and release seats from abandoned holds as they expire.
- Availability is tiny. Two bits per seat make the state of an entire stadium 15 KB, which a CDN can serve to a million viewers a few seconds at a time.
- Money arrives asynchronously. A payment can succeed after the hold expired, or end unknown, which is exactly the case the payment lesson treats.
| Call | Who calls it | Meaning |
|---|---|---|
GET /v1/events/{id}/availability | Fan app, through the CDN | The status of every seat, as a compact snapshot |
POST /v1/holds | Fan app, with an admission token | Hold specific seats, or ask for the best available |
DELETE /v1/holds/{id} | Fan app | Give the seats back |
POST /v1/orders | Fan app | Pay for a hold. Returns the tickets, or pending while the payment settles |
- auth
- user token plus the admission token issued by the waiting room
- idempotency
- Idempotency-Key header, so a double tap holds once
- body
- { "event": "ev_88", "seats": ["12A", "12B"] }
- note
- a hold is all or nothing, and the response always carries the time at which it ends
- 201held, returns { "hold_id": "h_5d1", "seats": ["12A", "12B"], "expires_at": "2026-11-12T14:07:00Z" }
- 201also for { "event": "ev_88", "quantity": 2, "mode": "best_available" }, where the server picks the seats
- 409at least one of the seats is no longer available, and none was held
- 429this account is over its purchase limit, or the admission token is missing or expired
event_idbigint
PKSHARD KEYseat_idtext
section, row and number
PKstatustext
free, held or sold
hold_idtext
NULLINDEXhold_expires_attimestamptz
a hold counts as over once this time has passed, whether or not anyone has cleaned it up
NULLorder_idtext
NULLprice_centsbigint
versionint
A seat is available when it is free, or held with an expired hold. Nobody has to sweep it before it can be sold again.
idtext
PKevent_idbigint
INDEXbuyer_idbigint
INDEXseatstext
the seat ids of the party
statetext
active, confirmed, released or expired
expires_attimestamptz
One hold covers a whole party, so releasing or confirming it touches all of its seats together.
The seat is claimed with one statement whose condition is the check. Everything depends on it being a single atomic step:
UPDATE seats
SET status = 'held', hold_id = :hold, hold_expires_at = :expires
WHERE event_id = :event AND seat_id = :seat
AND (status = 'free' OR (status = 'held' AND hold_expires_at <= now()));
-- One row updated: the seat is yours. Zero rows: somebody else has it.
-- For a party, run it for every seat in ascending seat order inside one transaction, and roll back if any returns zero rows.
CREATE UNIQUE INDEX one_sale_per_seat ON sale_items (event_id, seat_id);
-- The last line of defence: even a bug in the hold logic cannot sell one seat twice.Read it as three layers of defence. The edge serves everything static and absorbs the looking: the venue layout, and an availability blob that is rebuilt every second or two. The waiting room decides who may talk to the booking system, and when. The hold service is the only writer of seat state and makes each claim atomically, so even if the first two layers fail, a seat still cannot be held by two people. Payment is asynchronous, and the order service confirms the hold only after the payment answers, with the unknown outcome handled as in the payment lesson.
The check-then-write hold is the bug everyone knows: read the seat, see that it is free, write "held". Two buyers can both read "free" before either writes, and both are told the seat is theirs. The conditional update above closes the gap because the check is part of the write, and the number of rows changed says who won. A lock in a cache such as SET seat:42 hold NX PX 300000 is faster, and it is tempting, but a cache is not the source of truth: with asynchronous replication a failover can lose the key, and two holders can briefly exist. Use a cache lock as an accelerator in front of the database if you must, never in place of it, and keep the unique constraint on the sale as the final guard (see Martin Kleppmann's essay on distributed locking for why a lock alone is not enough).
A party of four needs four seats or none. Taking them one at a time, in the order the buyer thought of them, invites a deadlock: buyer 1 holds seat 1 and waits for seat 2 while buyer 2 holds seat 2 and waits for seat 1. The cure is old and simple: every buyer acquires seats in one global order (ascending seat id), so a cycle of waiting is impossible. The class below does that with a lock per seat, checks every seat before writing any, and treats an expired hold as free by comparing times, so no sweeper has to run before a seat can be sold again.
C# · SeatStatus, Seat, SeatMap
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
public enum SeatStatus { Free, Held, Sold }
public sealed class Seat
{
public readonly object Gate = new();
public SeatStatus Status;
public int Owner;
public long ExpiresAt;
}
// The seats of one event. A hold takes all the seats of a party or none of them, expires after a time to live, and is confirmed
// only by the buyer who holds it and only before it expires.
public sealed class SeatMap
{
private readonly Seat[] _seats;
public SeatMap(int count) { _seats = Enumerable.Range(0, count).Select(_ => new Seat()).ToArray(); }
public Seat this[int i] => _seats[i];
public int Count => _seats.Length;
// A seat is available if it is free, or its hold has run out (nobody has to sweep it before it can be sold again).
private static bool Available(Seat s, long now) => s.Status == SeatStatus.Free || (s.Status == SeatStatus.Held && s.ExpiresAt <= now);
// Locks every seat of the party in ascending order, checks them all, and writes them all. One global order means two buyers
// who want overlapping seats can never each hold a lock the other needs, so there is no deadlock, and nobody is left with half a party.
public bool TryHold(int buyer, int[] seatIds, long now, long ttl) => WithLocks(seatIds.Distinct().OrderBy(i => i).ToArray(), 0, ordered =>
{
if (!ordered.All(i => Available(_seats[i], now))) return false;
foreach (int i in ordered) { _seats[i].Status = SeatStatus.Held; _seats[i].Owner = buyer; _seats[i].ExpiresAt = now + ttl; }
return true;
});
// Payment succeeded: the seats become sold, but only for the buyer who still holds them, and only if the hold has not run out.
public bool Confirm(int buyer, int[] seatIds, long now) => WithLocks(seatIds.Distinct().OrderBy(i => i).ToArray(), 0, ordered =>
{
if (!ordered.All(i => _seats[i].Status == SeatStatus.Held && _seats[i].Owner == buyer && _seats[i].ExpiresAt > now)) return false;
foreach (int i in ordered) _seats[i].Status = SeatStatus.Sold;
return true;
});
public void Release(int buyer, int[] seatIds) => WithLocks(seatIds.Distinct().OrderBy(i => i).ToArray(), 0, ordered =>
{
foreach (int i in ordered) if (_seats[i].Status == SeatStatus.Held && _seats[i].Owner == buyer) _seats[i].Status = SeatStatus.Free;
return true;
});
private bool WithLocks(int[] ordered, int depth, Func<int[], bool> action)
{
if (depth == ordered.Length) return action(ordered);
lock (_seats[ordered[depth]].Gate) return WithLocks(ordered, depth + 1, action);
}
}The first part of the sample below shows the deadlock with a tiny lock table, so that it is deterministic: requests in the order each buyer thought of them make a cycle, and the same requests in one global order cannot. The second part releases 8 threads at once on 1,000 seats with 2,000 buyers, each wanting a random party of one to four seats. The third part checks expiry and confirmation, and the fourth shows how little a venue's availability weighs, which the next sections use.
C# · Two buyers want overlapping seats and take them one at a time in the order each thought…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
// Two buyers want overlapping seats and take them one at a time in the order each thought of them. A lock table shows the trap:
// buyer 1 holds seat 1 and waits for seat 2, buyer 2 holds seat 2 and waits for seat 1, so each waits for something the other holds.
var lockHolder = new Dictionary<int, int>(); // seat -> the buyer holding it
var waitsFor = new Dictionary<int, int>(); // buyer -> the seat it is waiting for
bool Take(int buyer, int seat) { if (lockHolder.TryAdd(seat, buyer)) return true; waitsFor[buyer] = seat; return false; }
bool Deadlocked(int buyer)
{
var seen = new HashSet<int>();
while (waitsFor.TryGetValue(buyer, out int seat) && lockHolder.TryGetValue(seat, out int holder)) { if (!seen.Add(buyer)) return true; buyer = holder; }
return false;
}
Take(1, 1); Take(2, 2); // each takes the seat it thought of first
Take(1, 2); Take(2, 1); // and then needs the other one
Debug.Assert(Deadlocked(1) && Deadlocked(2));
lockHolder.Clear(); waitsFor.Clear();
Take(1, 1); Take(1, 2); // in one global order both want seat 1 first, and buyer 1 gets both
Take(2, 1); // buyer 2 waits for seat 1 only, behind a buyer that is waiting for nothing
Debug.Assert(!Deadlocked(1) && !Deadlocked(2));
Console.WriteLine("unordered requests deadlock, requests in one global order cannot");
// 1,000 seats, 8 threads and 2,000 buyers released together, each wanting a random party of 1 to 4 seats.
var map = new SeatMap(1_000);
var parties = new int[2_000][];
var partyRandom = new Random(5);
for (int b = 0; b < parties.Length; b++) parties[b] = Enumerable.Range(0, 1 + partyRandom.Next(4)).Select(_ => partyRandom.Next(1_000)).Distinct().ToArray();
var gotSeats = new bool[parties.Length];
var go = new ManualResetEventSlim(false);
var workers = Enumerable.Range(0, 8).Select(w => new Thread(() =>
{
go.Wait();
for (int b = w; b < parties.Length; b += 8) gotSeats[b] = map.TryHold(b + 1, parties[b], now: 0, ttl: 600);
})).ToList();
workers.ForEach(t => t.Start());
go.Set();
workers.ForEach(t => t.Join());
int heldSeats = Enumerable.Range(0, 1_000).Count(i => map[i].Status == SeatStatus.Held);
int expectedSeats = Enumerable.Range(0, parties.Length).Where(b => gotSeats[b]).Sum(b => parties[b].Length);
Console.WriteLine($"{gotSeats.Count(g => g)} of {parties.Length} parties got their seats, {heldSeats} seats held");
Debug.Assert(heldSeats == expectedSeats); // no seat is held twice
for (int b = 0; b < parties.Length; b++) // all or nothing: a winner owns every seat of its party, a loser owns none
Debug.Assert(gotSeats[b] ? parties[b].All(i => map[i].Owner == b + 1 && map[i].Status == SeatStatus.Held) : parties[b].All(i => map[i].Owner != b + 1));
// A hold runs out by itself: at second 700 the seat is available again, the first buyer can no longer confirm, and the second can.
var show = new SeatMap(10);
Debug.Assert(show.TryHold(1, new[] { 5 }, now: 0, ttl: 600));
Debug.Assert(!show.TryHold(2, new[] { 5 }, now: 599, ttl: 600)); // still held
Debug.Assert(show.TryHold(2, new[] { 5 }, now: 700, ttl: 600)); // the first hold has run out
Debug.Assert(!show.Confirm(1, new[] { 5 }, now: 700) && show.Confirm(2, new[] { 5 }, now: 700));
Debug.Assert(show[5].Status == SeatStatus.Sold && !show.TryHold(3, new[] { 5 }, now: 10_000, ttl: 600)); // sold stays sold
Debug.Assert(show.TryHold(4, new[] { 6 }, now: 0, ttl: 100) && !show.Confirm(4, new[] { 6 }, now: 101)); // too late, even if nobody else took the seatOf the 2,000 buyers, about 410 got their parties (the exact count changes from run to run with thread timing) and held roughly 790 of the 1,000 seats between them, and every one of the rest was refused without taking anything. The asserts are the guarantees to name: no seat is held twice, a winner owns every seat of its party and a loser owns none, an expired hold can be taken by someone else, and the old holder can no longer confirm. The last assert is the one that connects to payment: a buyer whose payment finishes after the hold ran out cannot confirm, even if nobody else took the seat. The order service must then re-hold (if the seats are still free) or refund, and it must decide which before the customer sees a result.
A hold is a promise to keep seats away from everyone else while one person pays. Too short and people who are about to pay lose their seats, which feels like theft. Too long and abandoned holds lock seats for people who never pay, which shows "sold out" while seats are only parked. The simulation uses 5,000 seats and about 20 buyers a second. Each buyer who finds a free seat holds it: 70% pay after a log-normal time (median 90 seconds, with a long tail), and 30% abandon. It tries six policies, five fixed hold times and a short one that is extended while a payment that has been started is still in progress.
C# · 5,000 seats and about 20 buyers a second. Every buyer who finds a free seat holds it…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 5,000 seats and about 20 buyers a second. Every buyer who finds a free seat holds it while paying: 70% pay, after a log-normal
// time (median 90 s, with a long tail), and 30% abandon and never pay. A hold lasts `ttl` seconds. With the extension policy a
// hold also lasts while a payment that has been started is still in progress (up to 15 minutes).
var ttlRandom = new Random(17);
double Normal() => Math.Sqrt(-2 * Math.Log(1 - ttlRandom.NextDouble())) * Math.Cos(2 * Math.PI * ttlRandom.NextDouble());
int Poisson(double lambda) { double limit = Math.Exp(-lambda), product = 1; int k = 0; do { k++; product *= ttlRandom.NextDouble(); } while (product > limit); return k - 1; }
var outcomes = new Dictionary<string, (int SoldOutAt, double LostPayers, int TurnedAway, double LockedMinutes)>();
foreach (var (ttl, extend) in new[] { (60, false), (120, false), (300, false), (600, false), (900, false), (120, true) })
{
const int Pool = 5_000;
int free = Pool, sold = 0, payers = 0, lostPayers = 0, turnedAwayWhileHeld = 0;
var releases = new PriorityQueue<(int Freed, bool Sale), int>(); // when a hold ends: back to the pool, or into a sale
double abandonedSeatSeconds = 0;
int soldOutAt = -1;
for (int t = 0; t < 7_200 && soldOutAt < 0; t++)
{
while (releases.TryPeek(out var next, out int at) && at <= t) { releases.Dequeue(); if (next.Sale) sold++; else free++; }
if (sold == Pool) { soldOutAt = t; break; }
for (int b = Poisson(20); b > 0; b--)
{
if (free == 0) { if (sold < Pool) turnedAwayWhileHeld++; continue; }
free--;
bool pays = ttlRandom.NextDouble() < 0.7;
double payTime = 90 * Math.Exp(0.8 * Normal());
if (pays) payers++;
bool keeps = pays && (payTime <= ttl || (extend && payTime / 2 <= ttl && payTime <= 900)); // with extension, a payment that was started keeps the hold
if (keeps) releases.Enqueue((1, true), t + (int)Math.Ceiling(payTime));
else
{
if (pays) lostPayers++; // wanted to pay, but the hold had run out
else abandonedSeatSeconds += ttl;
releases.Enqueue((1, false), t + ttl);
}
}
}
string label = extend ? $"{ttl} s + extension" : $"{ttl} s";
outcomes[label] = (soldOutAt, lostPayers / (double)payers, turnedAwayWhileHeld, abandonedSeatSeconds / 60);
var o = outcomes[label];
Console.WriteLine($"hold {label,-16} sold out at {(soldOutAt < 0 ? "never" : soldOutAt + " s"),-7} paying buyers who lost the seat {o.LostPayers:P1}, turned away while seats were only held {o.TurnedAway}, seat-minutes locked by abandoners {o.LockedMinutes:F0}");
}
Debug.Assert(outcomes["60 s"].LostPayers > 0.6 && outcomes["900 s"].LostPayers < 0.01); // short holds lose buyers who were about to pay
Debug.Assert(outcomes["900 s"].LockedMinutes > 3 * outcomes["120 s"].LockedMinutes); // long holds lock seats for people who never pay
Debug.Assert(outcomes["120 s + extension"].SoldOutAt < outcomes["300 s"].SoldOutAt && outcomes["120 s + extension"].LockedMinutes < outcomes["300 s"].LockedMinutes);
Debug.Assert(outcomes["120 s + extension"].LostPayers < outcomes["120 s"].LostPayers / 2);| Hold | Sold out at | Paying buyers who lost the seat | Turned away while seats were only held | Seat-minutes locked by abandoners |
|---|---|---|---|---|
| 60 s | 2,643 s | 70.1% | 28,500 | 7,133 |
| 120 s | 1,898 s | 35.7% | 26,686 | 6,586 |
| 300 s | 2,909 s | 7.3% | 50,210 | 11,745 |
| 600 s | 4,678 s | 1.0% | 86,658 | 20,190 |
| 900 s | never (4,999 of 5,000 in two hours) | 0.2% | 137,277 | 32,820 |
| 120 s plus extension | 1,225 s | 11.5% | 16,455 | 5,010 |
The fixed policies show the trade-off. At 60 seconds, 70% of the buyers who meant to pay lost their seat, because the median payment takes 90. At 900 seconds almost nobody loses a seat, and the abandoned holds lock 32,820 seat-minutes, so the pool never sold out in two hours and 137,277 arrivals were turned away while the remaining seats were merely parked. The extension policy does better on every axis that matters except one. A base hold of 120 seconds, extended for as long as a payment that has been started is in progress, sold out first (1,225 seconds), locked the fewest seat-minutes (5,010) and turned the fewest buyers away (16,455), and 11.5% of payers lost their seat, against 35.7% for a plain two-minute hold and 7.3% for a plain five-minute one.
What to build from that:
- Short base hold, extended while paying. Abandoners release their seats at the short time, and people who are paying keep theirs. Cap the total (ten or fifteen minutes) so a stuck payment cannot park a seat for ever.
- Show the clock. The hold response carries
expires_at, the app shows a countdown, and an extension is visible. - Release on exit. A buyer who leaves the page or clicks back should free the seats at once. Do not wait for the timer.
- Pay after expiry is a real case. If the payment settles after the hold ended, re-hold the seats if they are still free, and refund otherwise (the payment is idempotent and may also be unknown, see the payment lesson).
Contention concentrates on a few seats. Buyers who choose their own seats all look at the same front rows, so a seat that is free in the snapshot a thousand phones are showing is wanted by dozens at once, and all but one of them lose a race and must try again. The simulation sends 3,000 buyers a second for three seconds at 10,000 seats ranked from best to worst. Each buyer picks from the availability seen at the start of the second, favouring the best seats, and when several buyers pick the same seat one wins and the others retry. The alternative is for the server to hand out the best free seats in turn.
C# · 10,000 seats ranked from the best (0) to the worst, and a sale that sends 3,000 buyers a…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 10,000 seats ranked from the best (0) to the worst, and a sale that sends 3,000 buyers a second for 3 seconds, each wanting one
// seat. Client-chosen: a buyer picks from the availability seen at the start of the second, favouring the best seats (weight
// 1 / (rank + 1)), and when several buyers pick the same seat one wins and the others try again the next second. Server-assigned:
// the server hands out the best free seats in turn, so there is nothing to collide on.
const int Stadium = 10_000, PerSecond = 3_000, Seconds = 3;
var pickRandom = new Random(23);
var attemptsPerBuyer = new List<int>();
var taken = new bool[Stadium];
var waiting = new List<(int Id, int Attempts)>();
int nextBuyer = 0, lostRaces = 0, secondsUsed = 0;
for (int second = 0; waiting.Count > 0 || second < Seconds; second++)
{
secondsUsed = second + 1;
if (second < Seconds) for (int i = 0; i < PerSecond; i++) waiting.Add((nextBuyer++, 0));
var free = Enumerable.Range(0, Stadium).Where(s => !taken[s]).ToArray();
if (free.Length == 0) break;
var cumulative = new double[free.Length];
double sum = 0;
for (int i = 0; i < free.Length; i++) cumulative[i] = sum += 1.0 / (free[i] + 1);
var pickedBy = new Dictionary<int, List<int>>();
for (int w = 0; w < waiting.Count; w++)
{
int index = Array.BinarySearch(cumulative, pickRandom.NextDouble() * sum);
if (index < 0) index = ~index;
int seat = free[Math.Min(index, free.Length - 1)];
if (!pickedBy.TryGetValue(seat, out var list)) pickedBy[seat] = list = new List<int>();
list.Add(w);
}
var winners = new HashSet<int>();
foreach (var (seat, buyers) in pickedBy)
{
winners.Add(buyers[pickRandom.Next(buyers.Count)]); // one buyer wins the seat
taken[seat] = true;
lostRaces += buyers.Count - 1; // and the rest lose the race for it
}
var stillWaiting = new List<(int Id, int Attempts)>();
for (int w = 0; w < waiting.Count; w++)
{
var (id, attempts) = waiting[w];
if (winners.Contains(w)) attemptsPerBuyer.Add(attempts + 1); else stillWaiting.Add((id, attempts + 1));
}
waiting = stillWaiting;
}
Console.WriteLine($"client-chosen: {attemptsPerBuyer.Count} buyers served in {secondsUsed} s, {attemptsPerBuyer.Average():F2} attempts each on average, {attemptsPerBuyer.Count(a => a > 3) / (double)attemptsPerBuyer.Count:P1} needed more than 3, worst {attemptsPerBuyer.Max()}, {lostRaces} lost races");
Console.WriteLine($"server-assigned: {Seconds * PerSecond} buyers served, 1.00 attempts each, 0 lost races");
Debug.Assert(attemptsPerBuyer.Count == Seconds * PerSecond && lostRaces > Seconds * PerSecond / 4 && attemptsPerBuyer.Average() > 1.3);| Client-chosen seats | Server-assigned best available | |
|---|---|---|
| Attempts per buyer, on average | 1.68 | 1.00 |
| Buyers needing more than 3 attempts | 4.9% (worst case 6) | none |
| Lost races | 6,103 for 9,000 buyers | 0 |
With client-chosen seats, 6,103 hold attempts lost a race, 68% extra writes aimed at the hottest rows, and one buyer in twenty needed more than three tries. Server assignment has nothing to collide on. In SQL it is one statement that locks the best free rows that no other request has locked:
SELECT seat_id FROM seats
WHERE event_id = :event AND (status = 'free' OR (status = 'held' AND hold_expires_at <= now()))
ORDER BY rank
LIMIT 2
FOR UPDATE SKIP LOCKED;
-- Each request locks the best rows that nobody else has locked, so concurrent buyers get different seats and nobody waits.
-- Asking for seats together needs contiguous runs, which a per-row index of free runs can provide.The design consequence is to offer "best available" as the fast path and keep seat-by-seat choice for buyers who want it, with a shorter list of seats shown as free (hiding the most contested ones for a moment) and a clear "someone else just took that seat" message.
Live availability is the other half of the read path. The state of a venue is tiny: two bits per seat. The code packs 60,000 seats into 15,000 bytes, and computes the delta between two snapshots, which is what a push channel sends.
C# · Availability
using System;
using System.Collections.Generic;
public static class Availability
{
// Two bits per seat (0 free, 1 held, 2 sold). A 60,000-seat stadium becomes a blob of 15,000 bytes that a CDN can cache for a
// second or two and a phone can compare with the last one it has.
public static byte[] Pack(SeatStatus[] seats)
{
var packed = new byte[(seats.Length + 3) / 4];
for (int i = 0; i < seats.Length; i++) packed[i / 4] |= (byte)((int)seats[i] << (i % 4 * 2));
return packed;
}
public static SeatStatus Read(byte[] packed, int seat) => (SeatStatus)((packed[seat / 4] >> (seat % 4 * 2)) & 3);
// The seats whose state changed between two snapshots: what a push channel needs to send.
public static List<(int Seat, SeatStatus Status)> Delta(byte[] before, byte[] after, int count)
{
var changes = new List<(int, SeatStatus)>();
for (int i = 0; i < count; i++) if (Read(before, i) != Read(after, i)) changes.Add((i, Read(after, i)));
return changes;
}
}C# · The availability of a 60,000-seat stadium fits in 15,000 bytes, and a few hundred sales…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// The availability of a 60,000-seat stadium fits in 15,000 bytes, and a few hundred sales change a few hundred entries of it.
var stadium = new SeatStatus[60_000];
var snapshotBefore = Availability.Pack(stadium);
var saleRandom = new Random(3);
var changed = new HashSet<int>();
while (changed.Count < 500) { int seat = saleRandom.Next(stadium.Length); stadium[seat] = SeatStatus.Sold; changed.Add(seat); }
var snapshotAfter = Availability.Pack(stadium);
var delta = Availability.Delta(snapshotBefore, snapshotAfter, stadium.Length);
Console.WriteLine($"snapshot {snapshotAfter.Length} bytes, {delta.Count} seats changed in this interval");
Debug.Assert(snapshotAfter.Length == 15_000 && delta.Count == 500 && delta.All(d => d.Status == SeatStatus.Sold && changed.Contains(d.Seat)));A publisher rebuilds the blob every second or two from the stream of seat changes and puts it behind the CDN, so a million viewers polling every two seconds cost the origin almost nothing (7.5 GB a second leaves the edge, and a handful of requests reach the origin). Clients that stay on the page can receive deltas over a push channel instead. The snapshot is advisory: it can be a second stale, and the hold decides.
Scaling the database is the wrong reflex. The seat table has 60,000 rows, and the load is contention on a few of them, so more servers just mean more buyers fighting over the same rows. What protects the system is limiting who gets to fight, and when. That is the waiting room, a queue in front of the booking system.
- Join phase. In the minutes before the on-sale, people who arrive are placed in a random order, not in order of arrival, because arrival order rewards the fastest connection and the bots. Those who arrive after the sale starts queue behind them in order.
- Admission by token. When a person's turn comes, the waiting room issues a signed, short-lived token bound to the account and device. The booking API rejects any request without a valid token, so the waiting room is also a security boundary (see authentication for signed tokens).
- The rate is Little's law. The number of shoppers inside equals the admission rate times the time each spends, so with about 24,000 orders' worth of inventory and a five-minute shop, 80 a second is the ceiling. A control loop adjusts it: admit faster while holds in flight and conversion are below target, slower when the booking API's latency rises.
- The room must itself scale. It holds millions of waiting connections, so it runs at the edge, answers polls from a counter or sorted set in a fast store, and keeps almost no per-user state. People who leave lose their place after a heartbeat timeout.
- Honesty is part of the design. Show a real position and an honest estimate, say early when the event is sold out, and release seats from expired holds to people still queued.
- Alternatives. A lottery with pre-registration removes the stampede altogether and is the fairest, at the cost of not feeling like "first come, first served". Dynamic pricing lowers the pressure on the cheapest seats.
Bots and resellers are the adversary. Purchase limits per account, verified-fan registration, device attestation and challenges for suspicious sessions, rate limits per address and per network (see rate limiting), and detection of accounts that behave in lockstep. Treat the admission token as single use, and tie it to the purchasing account, so that it cannot be resold or shared.
A hotel or a flight sells a count (rooms of a type for a night, seats in a fare class on a flight) and not individual seats. A booking for three nights decrements three counters at once, and it must do so atomically:
UPDATE room_inventory SET available = available - 1
WHERE hotel_id = :hotel AND room_type = :type AND night BETWEEN :from AND :to - 1 AND available > 0;
-- The booking is valid only if the number of rows updated equals the number of nights. Otherwise roll back the whole transaction.The same atomic conditional update guards each counter, and a hold is a temporary decrement with an expiry. Hotels and airlines also overbook on purpose, with a limit based on the expected number of no-shows, so available is allowed to go below zero by a policy-defined amount. Search is the heavy read here (many dates, many properties), and it runs on a separate, eventually consistent index, while the booking transaction reads the authoritative counters.
| Case | What goes wrong | Handle it |
|---|---|---|
| Two buyers pick one seat | Double selling | A conditional update on the seat, one transaction per party, and a unique constraint on the sale |
| Overlapping parties lock in different orders | A deadlock or partial holds | One global lock order, check all seats before writing any, release everything on failure |
| The payment settles after the hold expired | A buyer is charged with no seat | Re-hold if the seats are free, otherwise refund, and decide before the customer sees a result |
| The payment outcome is unknown | The seats are stuck, or sold without being paid | Keep the hold while the outcome is unknown (extended, capped), resolve it as in the payment lesson |
| Abandoned holds lock the inventory | "Sold out" while seats sit parked | A short base hold, release on exit, extension only while paying |
| A cache lock is lost in a failover | Two holders for one seat | Use the database as the source of truth, with the unique constraint as the last guard |
| The waiting room fails | The surge reaches the booking system | Admission tokens required by the booking API, rate limits and load shedding behind it |
| Bots take the best seats | Real fans are shut out, resale prices rise | Purchase limits, registration, tokens bound to accounts, challenges, anomaly detection |
| The CDN serves a stale availability blob | Fans choose seats that are gone | Treat it as advisory, show "just taken" gracefully, and refresh by push |
| A hot event overloads one shard | Slow holds | One event is one small partition: give it its own primary, replicas for reads and a hot standby |
| A sweeper lags or fails | Expired holds stay visible as held | Compare expiry times on every read and write so correctness does not depend on the sweeper |
Interviewer follow-upL5How do you stop two people buying the same seat?How to answer
Make the claim atomic: a conditional update whose WHERE clause says the seat is free (or its hold has expired), and the row count says who won. A read followed by a write is exposed to the race. Add a unique constraint on the sale as the last guard, so a bug in the hold logic still cannot sell one seat twice. A cache lock can speed it up but must not replace it, because a failover can lose the key.
Interviewer follow-upL5What happens to a seat while someone is paying?How to answer
It is held, with an owner and an expiry. Other buyers see it as unavailable until the hold ends, and the hold ends in one of three ways: the buyer pays and the hold is confirmed, the buyer leaves and releases it, or the time runs out and the seat becomes available again. Expiry is checked by comparing times, so a seat is sellable the moment its hold ends, with no cleanup job needed.
Interviewer follow-upL6How do you hold four seats together without deadlocks or partial holds?How to answer
Acquire the seats in one global order (ascending seat id), check all of them, and write all of them within one transaction or one set of locks, rolling back on any failure. With one order, a cycle of waiting is impossible. In the test, 2,000 buyers with random parties of one to four seats on 1,000 seats across 8 threads produced no seat held twice and no partial party.
Interviewer follow-upL6How long should a hold last?How to answer
It depends on how long payment really takes, which you measure. Too short loses buyers who are about to pay (70% at 60 seconds when the median payment takes 90), too long lets abandoners lock inventory (the pool never sold out at 15 minutes). Use a short base hold and extend it while a started payment is in progress, with a cap. In the simulation 120 seconds plus extension sold out first, locked the fewest seat-minutes and lost 11.5% of payers, against 35.7% for a plain two-minute hold.
Interviewer follow-upL6Five million fans want 60,000 seats. How does the system survive?How to answer
A waiting room in front, static content at the edge, and atomic holds behind. Admit shoppers at a rate set by Little's law and the inventory (about 80 a second for 24,000 orders and a five-minute shop), not by server capacity, with signed admission tokens that the booking API requires. The seat map and a 15 KB availability blob come from the CDN. Adding database servers would not help, because the load is contention on a few rows.
Interviewer follow-upL6The payment succeeded after the hold expired. What now?How to answer
Decide quickly and visibly. If the seats are still free, re-hold them under the same buyer and confirm. If someone else has them, refund, and tell the buyer why. The charge itself is idempotent and may have an unknown outcome, so the order service resolves that first (see the payment lesson). Extending the hold while a payment is in flight makes this rare.
Interviewer follow-upL6How do you show live availability to a million viewers?How to answer
A compact snapshot (two bits per seat, 15,000 bytes for 60,000 seats) rebuilt every second or two from the stream of seat changes and served by the CDN, with deltas pushed to clients that stay on the page. Treat it as advisory and let the hold decide. A million viewers every two seconds is about 7.5 GB a second from the edge and almost nothing from the origin.
Interviewer follow-upL6How do you deal with bots and scalpers?How to answer
Layers: purchase limits per account, verified-fan registration, signed single-use admission tokens bound to the account and device, rate limits per address and network, challenges for suspicious sessions, and detection of accounts acting in lockstep. A lottery with pre-registration removes the race that bots win. Accept that the defence is a moving target and measure it.
Interviewer follow-upL7How would you support hotels or flights?How to answer
Model inventory as counts per room type and night (or fare class and flight), and book with one transaction that decrements every night's counter under a condition, valid only if all of them updated. Holds are temporary decrements with an expiry. Allow a policy-controlled overbooking margin, put search on a separate eventually consistent index, and keep the booking path on the authoritative counters.
Interviewer follow-upL7How would you test this before a big on-sale?How to answer
Load-test with the real shape of the traffic, a skewed pick of the best seats and a sudden surge, and with the waiting room in place. Inject payment timeouts and late settlements, kill the hold service mid-hold, and run invariant checks continuously: seats sold never exceed capacity, no seat has two owners, every sold seat has a paid order, and every paid order has a seat. Rehearse the failure of the waiting room itself.
- Clarify: reserved or general admission, events or hotels, the largest on-sale, whether buyers pick seats, hold time, bot limits.
- Estimate: a venue of tens of thousands of seats, millions of fans, an admission rate from Little's law, and a 15 KB availability blob.
- Model it: seats with a status, an owner and an expiry, a hold per party, an order for the payment.
- Draw it: CDN for the map and availability, a waiting room, a booking API that checks tokens, a hold service on a seat store, an order service with payment, a publisher.
- Go deep on the claim: a conditional update, all-or-nothing in one global order, expiry by time comparison, a unique constraint on the sale.
- Size the hold: the trade-off between lost payers and locked inventory, a short hold with extension.
- Handle the surge: the waiting room with signed tokens at a Little's-law rate, a lottery as an alternative, honest messages.
- Reduce contention: best available assigned by the server with
SKIP LOCKED, advisory availability. - Close with failures and extensions: a payment after expiry, bots, a lost cache lock, hotels and overbooking.
A ticket booking system sells inventory that can be sold once, so a seat is a row with an owner and an expiry, claimed by one atomic conditional update with a unique constraint on the sale as the last guard. A party's seats are held all or nothing in one global lock order, so buyers cannot deadlock or leave partial holds (no seat held twice in the test of 2,000 buyers), and expired holds are treated as free by comparing times. The hold time comes from the payment-time distribution: a plain short hold loses payers and a long one locks inventory (the pool never sold out at 15 minutes), while a short hold extended during payment sold out first at 1,225 seconds with 11.5% of payers losing the seat. Contention on the best seats is cut by server-assigned best available with SKIP LOCKED (1.68 attempts per buyer against 1.00). The surge is handled in front of the database by a waiting room whose admission rate follows Little's law and the inventory (about 80 a second here), signed admission tokens and bot defences, with the venue's availability served from the CDN as a 15 KB blob. Late and unknown payments, hotels with counts per night, and testing are the senior answers.
Try answering out loud before you reveal each answer.
QuestionTwo buyers click the same seat at the same moment. Why can read-then-write sell it twice, and what prevents it?Reveal answer
Both read "free" before either writes, so both write "held" and both are told the seat is theirs. A conditional update (WHERE status = 'free' OR the hold has expired) makes the check part of the write, and the number of rows changed says who won. A unique constraint on the sale is the final guard. A cache lock is only an accelerator, since a failover can lose the key.
QuestionWhy must a party's seats be locked in a global order, and what does all-or-nothing mean?Reveal answer
If buyers take seats one by one in the order they thought of them, buyer 1 can hold seat 1 and wait for seat 2 while buyer 2 holds seat 2 and waits for seat 1, a deadlock. One global order makes a cycle impossible. All-or-nothing means checking every seat first and writing them all, or none, so nobody is left with half a party. In the test, 2,000 buyers on 8 threads left no seat held twice and no partial party.
QuestionA hold of 60 seconds, 15 minutes, and 2 minutes with extension: what does each do to buyers and to inventory?Reveal answer
At 60 seconds 70% of the buyers who meant to pay lost their seats, because payment takes a median of 90 seconds. At 15 minutes almost nobody lost a seat, but abandoned holds locked 32,820 seat-minutes and the pool never sold out in two hours. Two minutes with an extension while a payment is in progress sold out first (1,225 seconds), locked the fewest seat-minutes (5,010) and lost 11.5% of payers.
QuestionWhy does admitting more shoppers per second not make an on-sale faster, and how do you pick the rate?Reveal answer
The seats are the scarce resource and the load is contention on a few rows, so more concurrent shoppers just fight over the same seats and the rest see "sold out" while holds are parked. By Little's law the shoppers inside equal the admission rate times the time they spend, and that should not exceed the orders the inventory can absorb: with 24,000 orders' worth of seats and a five-minute shop, about 80 a second. Adjust it with a control loop on holds in flight, conversion and latency.
QuestionHow do you let a million people watch seat availability without hurting the origin?Reveal answer
Pack the availability of the venue into a small snapshot (two bits per seat, 15,000 bytes for 60,000 seats), rebuild it every second or two from the stream of seat changes, and serve it from the CDN, so the origin sees a handful of requests while about 7.5 GB a second leaves the edge. Push deltas to clients that stay. Treat the snapshot as advisory, because the hold decides.
- John D. C. Little, A Proof for the Queuing Formula: L = λW, Operations Research, 1961: the law behind the admission rate.
- Cloudflare, Waiting Room documentation (opens in a new tab): how an edge waiting room queues, admits and handles returning visitors.
- PostgreSQL, explicit locking (opens in a new tab) and the
FOR UPDATE SKIP LOCKEDclause in the SELECT reference (opens in a new tab). - Martin Kleppmann, How to do distributed locking (opens in a new tab) (2016): why a lock needs a fencing token, and why a cache lock alone is not enough.
- Martin Kleppmann, Designing Data-Intensive Applications (2017), chapter 7: write skew and the isolation levels that do and do not prevent it.
- Alex Xu and Sahn Lam, System Design Interview, Volume 2 (ByteByteGo, 2022): the hotel reservation chapter, covering double booking and inventory by date.