The problem, stated properly
Design a ticket booking system (BookMyShow, Ticketmaster): users browse events and seat maps, select seats, pay, and receive a confirmed ticket. It looks like a simple CRUD app until you add the two facts that make it one of the hardest interview problems: inventory cannot oversell (one seat, one owner, ever), and demand is brutally spiky (a Coldplay on-sale does 10x normal traffic in 90 seconds, almost all of it hammering the same few thousand seats).
Scale first
- Normal traffic: browsing dominates, maybe 50K QPS of event/seat-map reads against a few hundred bookings/sec. Read-heavy, cacheable.
- On-sale traffic: a stadium concert releases ~50K seats to ~2 million simultaneous users. That is a 40:1 contention ratio on inventory, with everyone querying the same seat map at once. Reads spike to millions of QPS; writes must stay strictly serialized per seat.
- The invariant: for N seats there must never be more than N confirmed tickets, under any combination of retries, double-clicks, payment timeouts, and server crashes.
The core mechanism: the seat-hold state machine
Seats move through states, and every transition is atomic:
- AVAILABLE: anyone can see it on the seat map.
- HELD (soft lock): a user selects it. The seat is held for a fixed window (typically 5-10 minutes) while they pay. If payment never completes, the hold expires and the seat returns to AVAILABLE automatically. Holds are usually stored in Redis:
SET seat:12345 user:789 NX EX 600, one atomic command that both checks availability and writes the hold. The TTL is the expiry mechanism, so a crashed payment flow can never strand a seat forever. - BOOKED (hard lock): payment succeeded. The hold converts into a permanent booking row in the database, written transactionally: only if the seat is currently held by this same user.
The money path must be idempotent end to end: payment webhooks retry, users double-click, networks drop. Every booking carries a client-generated idempotency key; a duplicate submission returns the original booking instead of charging twice.
Why optimistic concurrency wins here (and where it loses)
Two ways to stop double-booking:
- Pessimistic locking (SELECT FOR UPDATE): lock the seat row during the whole purchase. Safe but deadly at on-sale scale: thousands of users queue on the same rows, lock wait times explode, and a user who abandons checkout holds a lock until timeout. Fine for low-contention inventory, wrong for hot seats.
- Optimistic with Redis holds: the atomic SET NX does the mutual exclusion in memory, the DB only sees one final writer per seat, and contention evaporates. This is the standard production answer. The database still enforces the invariant last: a unique constraint on (event_id, seat_id) on the bookings table means even if every layer above it has a bug, the storage layer cannot oversell. Defense in depth is the point.
Surviving the on-sale: the waiting room
You cannot let 2 million browsers hammer your seat map. Real systems put a virtual waiting room in front: users join a queue at the edge (a CDN-level or gateway-level token dispenser), and the system admits users at the rate the booking backend can actually serve (say 2,000 sessions/sec). Everyone else sees "you are 14,203rd in line" with an ETA. This converts an unbounded thundering herd into a bounded, measurable flow. Fairness details matter: queue positions are assigned by lottery after an initial grace window (kills bot speed advantage), tokens are single-use, and admitted sessions are fingerprinted to slow scalpers.
Reads at on-sale scale
The seat map is the hottest read in the building and it changes constantly (every hold and booking grays out seats). Serving it from the DB is impossible. The standard shape: the seat map renders from a cached snapshot (CDN or Redis), refreshed every few seconds from the authoritative store, and the client re-validates the specific seats it wants at selection time. Users tolerate "these seats were just taken" at checkout; they do not tolerate a spinning seat map. Eventual consistency on the display, strong consistency on the write: that split is the whole design in one sentence.
Production failure modes
- Orphaned holds: user closes the tab mid-payment. The Redis TTL recovers the seat, but if you implemented holds without TTLs (a common bug), inventory leaks permanently.
- Payment succeeded, booking failed: charge went through, DB write crashed. You need a reconciliation job that matches payment records to bookings and auto-refunds or auto-completes. Money and inventory must reconcile to zero diff every night.
- Race between hold-expiry and payment-complete: payment lands at second 601 of a 600-second hold. Policy decision: extend holds while a payment is in-flight, or reject and refund. Pick one explicitly; discovering your accidental choice in production is how you end up on Twitter.
- Bots and scalpers: on-sales are adversarial. Rate limits per IP/account/device fingerprint, CAPTCHAs at admission, and resale restrictions are part of the system, not an afterthought.
Common interview traps
- Letting the payment call happen inside a database transaction. Network calls inside transactions hold locks for hundreds of milliseconds and collapse throughput.
- Designing holds without expiry. Every soft state needs a TTL or a janitor.
- Forgetting idempotency on the booking endpoint. Retries are guaranteed; double charges are optional.
- Claiming strong consistency for the seat map display. Millions of readers do not need, and cannot have, up-to-the-millisecond accuracy.
Interview Q&A
Q: Walk me through exactly what happens when two users click the same seat at the same instant.
A: Both requests hit Redis. The seat hold is one atomic command: SET seat:42 user:A NX EX 600. Redis executes commands sequentially, so exactly one of the two SETs returns OK; the other returns nil and that user instantly sees "seat just taken." The winner pays, and the booking write carries a unique (event, seat) constraint, so even a hypothetical Redis failure cannot produce two confirmed tickets. One atomic primitive in memory, one unique constraint on disk, and the invariant holds.
Q: How does the waiting room decide the admission rate?
A: Work backwards from booking capacity. If payment + booking completes in ~2 seconds end to end and you can run 1,000 concurrent purchase flows safely, admit ~500 new users per second (leaving headroom for retries). Monitor downstream latency and error rate and close the valve when they rise: the queue length is your buffer, the admission rate is your throttle. This is just a token bucket applied to humans.
Problem ko sahi se samjho
Ticket booking system design karo (BookMyShow, Ticketmaster): users events aur seat maps dekhte hain, seats select karte hain, payment karte hain, confirmed ticket paate hain. Ye simple CRUD app lagta hai jab tak do facts na aayein jo ise interview ke sabse mushkil problems mein se ek banate hain: inventory oversell nahi ho sakti (ek seat, ek malik, kabhi bhi do nahi), aur demand brutally spiky hai (Coldplay on-sale 90 second mein normal traffic ka 10x karta hai, aur lagbhag saara load unhi kuch hazaar seats pe).
Pehle scale
- Normal traffic: browsing dominate karti hai, maan lo 50K QPS event/seat-map reads, kuch sau bookings/sec ke against. Read-heavy, cacheable.
- On-sale traffic: ek stadium concert ~50K seats ko ~2 million simultaneous users ke saamne kholta hai. Inventory pe 40:1 contention ratio, aur sab ek hi seat map ko ek saath query kar rahe hain. Reads millions of QPS tak spike; writes har seat pe strictly serialized rehni chahiye.
- Invariant: N seats ke liye kabhi bhi N se zyada confirmed tickets nahi, chahe kitne bhi retries, double-clicks, payment timeouts aur server crashes aa jayein.
Core mechanism: seat-hold state machine
Seats states ke through guzarte hain, aur har transition atomic hai:
- AVAILABLE: koi bhi seat map pe dekh sakta hai.
- HELD (soft lock): user ne select kiya. Seat fixed window (typically 5-10 minute) ke liye hold, jab tak wo payment karta hai. Payment complete nahi hua to hold expire ho ke seat wapas AVAILABLE. Holds aksar Redis mein hote hain:
SET seat:12345 user:789 NX EX 600, ek atomic command jo availability check aur hold dono karta hai. TTL hi expiry mechanism hai, to crashed payment flow seat ko kabhi hamesha ke liye stranded nahi kar sakta. - BOOKED (hard lock): payment success. Hold database mein permanent booking row ban jaata hai, transactionally likha gaya: sirf tab jab seat abhi bhi isi user ke paas held ho.
Money path end to end idempotent hona chahiye: payment webhooks retry karte hain, users double-click karte hain, networks girti hain. Har booking pe client-generated idempotency key; duplicate submission original booking return kare, double charge nahi.
Optimistic concurrency yahan kyun jeet-ti hai (aur kahan haarti hai)
Double-booking rokne ke do tareeke:
- Pessimistic locking (SELECT FOR UPDATE): poori purchase ke dauran seat row lock karo. Safe par on-sale scale pe kaatil: hazaaron users same rows pe queue karte hain, lock wait times explode, aur checkout abandon karne wala user timeout tak lock pakde rakhta hai. Low-contention inventory ke liye theek, hot seats ke liye galat.
- Optimistic with Redis holds: atomic SET NX memory mein mutual exclusion karta hai, DB ko har seat pe sirf ek final writer dikhta hai, aur contention gayab. Ye standard production answer hai. Database phir bhi aakhir mein invariant enforce karti hai: bookings table pe (event_id, seat_id) ka unique constraint ka matlab upar ke har layer mein bug ho to bhi storage layer oversell nahi kar sakti. Defense in depth hi point hai.
On-sale survive karna: waiting room
2 million browsers ko apne seat map pe nahi chhod sakte. Real systems aage ek virtual waiting room lagate hain: users edge pe queue mein judte hain (CDN-level ya gateway-level token dispenser), aur system users ko utni rate se admit karta hai jitni booking backend asal mein serve kar sakta hai (maan lo 2,000 sessions/sec). Baaki sab dekhte hain "aap 14,203 number pe hain" ETA ke saath. Ye unbounded thundering herd ko bounded, measurable flow mein badal deta hai. Fairness details matter karte hain: initial grace window ke baad queue positions lottery se assign hoti hain (bots ka speed advantage khatam), tokens single-use hain, aur admitted sessions fingerprint hote hain scalpers ko slow karne ke liye.
On-sale scale pe reads
Seat map building ka sabse hot read hai aur lagatar badalta hai (har hold aur booking seats ko gray karta hai). DB se serve karna impossible hai. Standard shape: seat map cached snapshot se render hota hai (CDN ya Redis), har kuch second mein authoritative store se refresh, aur client selection time pe apni specific seats re-validate karta hai. Users checkout pe "ye seats abhi li gayi" tolerate kar lete hain; spinning seat map tolerate nahi karte. Display pe eventual consistency, write pe strong consistency: ye split hi poora design ek sentence mein hai.
Production mein kya tootta hai
- Orphaned holds: user payment ke beech tab band kar deta hai. Redis TTL seat recover kar leta hai, par agar holds bina TTL ke implement kiye (common bug), to inventory permanently leak hoti hai.
- Payment hua, booking fail: charge ho gaya, DB write crash. Reconciliation job chahiye jo payment records ko bookings se milaye aur auto-refund ya auto-complete kare. Paisa aur inventory har raat zero diff pe reconcile hone chahiye.
- Hold-expiry aur payment-complete ki race: payment 600-second hold ke second 601 pe aaya. Policy decision: in-flight payment ke dauran holds extend karo, ya reject karke refund. Ek consciously choose karo; production mein apni accidental choice discover karna wahi tareeka hai jisse log Twitter pe pahunchte hain.
- Bots aur scalpers: on-sales adversarial hain. Per IP/account/device fingerprint rate limits, admission pe CAPTCHA, aur resale restrictions system ka hissa hain, afterthought nahi.
Common interview traps
- Payment call ko database transaction ke andar rakhna. Transactions ke andar network calls locks ko hundreds of milliseconds tak pakadte hain aur throughput collapse karte hain.
- Holds bina expiry design karna. Har soft state ko TTL ya janitor chahiye.
- Booking endpoint pe idempotency bhoolna. Retries guaranteed hain; double charges optional hain.
- Seat map display ke liye strong consistency maangna. Millions of readers ko up-to-the-millisecond accuracy ki zaroorat bhi nahi aur mil bhi nahi sakti.
Interview Q&A
Q: Do users bilkul same instant pe same seat click karein to exactly kya hota hai?
A: Dono requests Redis pe aati hain. Seat hold ek atomic command hai: SET seat:42 user:A NX EX 600. Redis commands sequentially execute karta hai, to do SETs mein se exactly ek OK return karta hai; doosra nil aur us user ko turant "seat just taken" dikhta hai. Winner payment karta hai, aur booking write pe (event, seat) ka unique constraint hai, to hypothetical Redis failure bhi do confirmed tickets produce nahi kar sakti. Memory mein ek atomic primitive, disk pe ek unique constraint, aur invariant hold.
Q: Waiting room admission rate kaise decide karta hai?
A: Booking capacity se ulta chalo. Agar payment + booking end to end ~2 second mein complete hota hai aur tum 1,000 concurrent purchase flows safely chala sakte ho, to ~500 naye users per second admit karo (retries ke liye headroom chhod ke). Downstream latency aur error rate monitor karo aur wo badhein to valve band karo: queue length tumhara buffer hai, admission rate tumhara throttle. Ye bas humans pe laga hua token bucket hai.