SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design Ticket / Hotel Booking

Sell a limited inventory fairly: holds, double-booking, flash-sale traffic and payments.

⏱ 36 min readHard case studyAdvanced28 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a ticket booking system, like Ticketmaster or BookMyShow. It should also handle hotel rooms.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Naming the invariantA seat is sold to at most one person. A strong candidate says this sentence first, then shows which mechanism enforces it. Everything else is a detour around this one rule.
Concurrency without hand-wavingTwo people click the same seat in the same millisecond. The interviewer wants a compare-and-set, a lock or a unique key, and an honest comparison of them, not “use a distributed lock”.
Holds, expiry and moneyA seat is held while the buyer pays. What if payment finishes after the hold expired? What if payment works and confirming fails? This is where multi-step failures show up.
Surviving a flash saleA million people arrive at 12:00:00 for 50,000 seats. Autoscaling does not fix a hot row. The answer is a waiting room, caching and load shedding.
Knowing what must be strongly consistentThe seat map can be stale. The hold and the sale cannot. Putting the line in the right place is the whole design.

TL;DRThe whole design in 60 seconds

Selling a limited inventory is a correctness problem wearing a scale problem's clothes. The invariant is "a seat is sold to at most one person". We enforce it in one place, an atomic conditional update on a strongly consistent store, and make everything else cheap and stale.

  • Reads are cached and may be stale. The seat map is a small bitmap served from a CDN with a 2-second life. 200,000 requests a second at the edge become about 50 at the origin.
  • The write path is authoritative. A hold is one transaction: UPDATE seats SET status = 'HELD' ... WHERE status = 'AVAILABLE', and it must change as many rows as seats asked for, or it rolls back. Only one buyer can win a seat.
  • Holds expire. A hold has a deadline. An expired hold counts as free (lazy expiry on the write), and a sweeper tidies up. Confirming checks that the hold is still the buyer's.
  • Money goes through a saga. Authorise payment, confirm the seats, then capture. If confirming fails, void the authorisation. Every step carries an idempotency key.
  • Flash sale: a waiting room lets users in at a rate the database can take (about 1,250 a second in our numbers), with signed admission cookies, bot checks and per-user limits.
  • Hotels: inventory is a count per room type per night. A booking decrements every night in one transaction and never goes below zero. Overbooking, if any, is a business rule, not a bug.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Reserved seats or general admission, hold time, hotel or event or both, flash-sale size, overbooking policy.
2. Estimate3Reads versus writes, the flash-sale spike, hold attempts per second against what one database can do.
3. API and data5Seat map, hold, book with an idempotency key. Seats, holds, bookings and hotel inventory tables.
4. High-level design8CDN read path, waiting room, booking service, inventory store, payment, search on the side.
5. Deep dives15No double booking, then holds and expiry, then the flash sale, then consistency and hotels.
6. Scale and failures7Payment works but confirm fails, the hot shard, region loss, bots and refunds.
7. Wrap up3Recap, where strong consistency lives, what you would build next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that would change the design. Hint: think about whether seats are numbered, how long a hold lasts, what happens when payment is slow, and how big the worst moment is.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Are seats numbered and chosen by the buyer, or is it general admission with a count?A numbered seat is a unique row to contend for. General admission is a counter. The counter is easier, and the contention is on one hot row.Both. Concerts have numbered seats, some events are general admission.One inventory model with two shapes: a row per seat, or a row per section with a remaining count.
Do we sell hotel rooms too? Per night or per stay?A hotel booking spans many nights, so one booking touches many inventory rows. It is a different shape of the same problem.Yes. A stay is one to thirty nights, and inventory is counted per room type per night.A second table keyed by (room type, date), and a booking that decrements every night in one transaction.
How long may a buyer hold seats while paying?The hold time is the price of fairness: too long locks seats up, too short makes honest buyers fail.Eight minutes, with one extension of two minutes.A hold has an expiry. Expiry, extension and late payment all need rules.
What does the busiest moment look like?Normal traffic and an on-sale moment are different systems.A million people waiting for 50,000 seats, all arriving within a few seconds.A waiting room, aggressive caching and a hot-shard plan. Autoscaling alone will not do it.
May we ever sell more than we have?Hotels sometimes overbook on purpose. Concerts never may.Never for events. Hotels may allow a small, configurable overbooking.The no-oversell rule is strict for events, and a tunable limit for hotels.
Does the seat map have to be exactly right, second by second?This decides what we may cache.No. If it is a second or two stale and a click fails politely, that is fine.The map is cached and eventually consistent. The hold is the source of truth.
Who pays, and how? Can we refund?Payment is slow and can fail after the seat is held. It brings a saga.Cards through a payment provider. Full refund until a cut-off.Authorise, confirm, capture, with void and refund as compensation. Link to the payment case study.
Do we care about bots and scalpers?Bots turn a fair queue into a race against machines.Yes. Limit tickets per person and keep bots out.Verified accounts, challenges, a signed waiting-room cookie and per-user limits.
Single region or global? How available?Two regions that both sell the same seat will sell it twice.Global users, one home region per event, 99.9% available.A single writer per event. Other regions read from caches and replicas.

Write the scope on the board

Functional (must do)
  • •Browse and search events and hotels, and show a seat map or a calendar of availability
  • •Hold chosen seats or rooms for a short time while the buyer pays
  • •Confirm a booking after payment, and send the ticket or voucher
  • •Release holds that expire, and let buyers cancel and get a refund
  • •Run an on-sale fairly when demand is far above supply
Non-functional (how well)
  • •Correct: never sell the same seat twice, and never take money for a seat we cannot give
  • •Fast: seat map in under 200 ms, hold in under 300 ms at p99
  • •Available: 99.9%, and browsing keeps working when booking is under strain
  • •Scalable: 1,000,000 users and 50,000 seats on one event, and 12 bookings a second on a normal day
  • •Fair: first in the line gets served first, and one person cannot buy 100 tickets
Out of scope (say it)
  • •Recommendations, pricing engines and dynamic pricing
  • •Resale and ticket transfer
  • •Running the payment network itself (see Design a Payment System)
  • •Venue operations such as scanning tickets at the door
🎤
Say it out loud
“Let me confirm the scope. We sell numbered seats for events and nights in hotel rooms. A buyer holds seats for eight minutes while paying, then we confirm and send a ticket. Events must never be oversold, and hotels may overbook a little by policy. The hard case is an on-sale with a million people for 50,000 seats. The seat map can be a second stale, but the hold and the sale must be exact. We have one home region per event. Payments go through a provider, and I will treat that as a separate service. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: normal page views and bookings per second, the seat-map traffic when a million people wait, how many hold attempts one database can take, and how fast a waiting room must let people in.

Assumptions (say them first)

AssumptionValue
Normal day20 million visits, 10 page views each, 1 million bookings
Peak versus average3 times for views, 10 times for bookings
On-sale event50,000 seats, 1,000,000 people waiting, 2 seats per order on average
Seat map pollevery 5 seconds per waiting user
Seat map size2 bits per seat (free, held, sold)
CDN cache life, edge sites2 seconds, 100 edge sites
One inventory shardabout 5,000 hold transactions per second (assumption)
Hold time8 minutes (480 seconds)
Hotels500,000 properties, 8 room types, 365 days ahead, 40 bytes per row

The arithmetic, line by line

WhatMathsResult
Normal page views per second20,000,000 × 10 ÷ 86,400about 2,300 per second (7,000 at a 3× peak)
Normal bookings per second1,000,000 ÷ 86,400about 12 per second (about 120 at a 10× peak)
Seat-map polling during the on-sale1,000,000 users ÷ 5 seconds200,000 requests per second
Size of one seat map50,000 seats × 2 bits ÷ 812.5 KB
Egress from the CDN for that200,000 × 12.5 KB2.5 GB per second, about 20 Gbit per second
Origin load behind the CDN100 edge sites ÷ 2 second cache lifeabout 50 requests per second
Hold attempts if everyone clicks within 10 seconds1,000,000 ÷ 10 s, against 5,000 per second100,000 per second, 20 times too many
Safe admit rate (half capacity, 2 attempts per user)5,000 × 50% ÷ 21,250 users per second
Time to let everyone in1,000,000 ÷ 1,250800 seconds, about 13 minutes
Most holds in flight50,000 seats ÷ 2 per order25,000 holds (inventory caps it)
Expiries if half the buyers walk away12,500 holds ÷ 480 secondsabout 26 per second
Seat rows for 10,000 live events50,000,000 seats × 100 bytes5 GB
Bookings stored per year1,000,000 × 300 bytes × 365about 110 GB (330 GB with 3 copies)
Hotel inventory rows500,000 × 8 × 365 = 1.46 billion rows × 40 bytesabout 58 GB (175 GB with 3 copies)
What the numbers tell us about the design
  • •The data is tiny (5 GB of seats). This is not a storage problem. It is a contention and a thundering-herd problem.
  • •200,000 reads a second sounds scary and is not: a 12.5 KB map behind a 2-second CDN cache costs the origin about 50 requests a second.
  • •The danger is the write side. 100,000 hold attempts a second is 20 times what one shard can do, and most of them hit the same few good seats. Autoscaling app servers does not help, because the database row is the bottleneck.
  • •So a waiting room is not optional. It meters users down to about 1,250 a second, which the database can take with headroom.
  • •Holds in flight can never exceed the number of seats (25,000 orders). Inventory itself bounds the size of the hold table, which keeps expiry cheap.
🎤
Say it out loud
“Let me do the maths. A normal day is about 2,300 page views and 12 bookings a second. The on-sale is the problem: a million people polling a 12.5 kilobyte seat map every five seconds is 200,000 requests a second, but with a two-second CDN cache the origin sees about 50. The real risk is holds: if everyone clicks within ten seconds, that is 100,000 attempts a second against a shard that does about 5,000, so I need a waiting room that admits about 1,250 users a second. The data is only 5 gigabytes, so this is a contention problem, not a storage problem.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the three calls a buyer makes: look at the map, hold seats, confirm. Then the table that stops two buyers taking one seat. Which column and which WHERE clause make the second buyer lose?

Endpoints

MethodPathRequestResponseNotes
GET/v1/events/{id}/seats?section=Bnone200 { version, free: [..], held: [..], sold: [..] } (a compact bitmap)Cached at the CDN for about 2 seconds. Eventually consistent on purpose. Never trust it to book.
POST/v1/holds{ eventId, seatIds: [..], admissionToken }201 { holdId, expiresAt } or 409 { taken: [..] }The one place that decides who gets a seat. All-or-nothing: if any seat is gone, none is held. Needs the signed waiting-room cookie. Idempotency-Key so a retry returns the same hold.
POST/v1/bookings{ holdId, paymentMethodId } + Idempotency-Key header201 { bookingId, tickets } or 402, 409 (hold lost), 410 (hold expired)Authorises payment, confirms the seats if the hold is still the buyer's, then captures. A retry with the same key returns the same booking.
DELETE/v1/holds/{holdId}none204The buyer gives up. Seats go back at once. Idempotent.
GET/v1/hotels/{id}/availability?from=2026-07-01&to=2026-07-05none200 { roomTypes: [{ type, left, price }] }Reads a cache or replica. A hint, not a promise.
POST/v1/reservations{ hotelId, roomType, from, to, paymentMethodId } + Idempotency-Key201 { reservationId } or 409 (sold out for some night)Decrements every night in one transaction. Fails as a whole if any night has none left.

Data model

seats (sharded by event id)TypeWhy it is there
event_id, seat_ididsThe key. One row per physical seat.
statusenumAVAILABLE, HELD or SOLD. The compare-and-set looks at this.
hold_id, hold_expires_atid, timestampWho holds it and until when. An expired hold counts as free.
booking_ididSet when sold. Unique per (event_id, seat_id) for confirmed sales: a second line of defence.
versionintBumped on every change. Lets caches and clients tell old maps from new.
holds and bookingsKey fieldsWhy
holdshold_id, user_id, event_id, seat_ids, expires_at, stateOne row per hold, so we can expire and release a group together.
bookingsbooking_id, user_id, hold_id, status, payment_ref, idempotency_key (unique)The unique key makes a retried booking return the same row.
hotel_inventoryhotel_id, room_type, night, total, booked (CHECK booked <= total + overbook_limit)A count per room type per night. The CHECK is the last guard.
reservationsreservation_id, hotel_id, room_type, from, to, statusSpans many nights, so many inventory rows change together.
The two statements that carry the invariant
-- Hold seats: all or nothing, one transaction
UPDATE seats
   SET status = 'HELD', hold_id = :hold, hold_expires_at = now() + interval '8 minutes', version = version + 1
 WHERE event_id = :e AND seat_id IN (:ids)
   AND (status = 'AVAILABLE' OR (status = 'HELD' AND hold_expires_at < now()));
-- rows changed must equal the number of seats asked for, else ROLLBACK and return 409

-- Hotel: take one room of a type for every night in the stay
UPDATE hotel_inventory SET booked = booked + 1
 WHERE hotel_id = :h AND room_type = :t AND night BETWEEN :from AND :to - 1
   AND booked < total + :overbook_limit;
-- rows changed must equal the number of nights, else ROLLBACK
📝Which store, and why
The inventory needs transactions (hold several seats together or none), a conditional update, and a unique constraint, so a relational database, or a store with the same guarantees, owns it. We shard by event id so one event lives on one primary and a hold is a single-shard transaction. The data is small (5 GB of seats), so the shard is about throughput, not size. The seat map, search and recommendations live elsewhere and are allowed to be stale.
🎤
Say it out loud
“The buyer asks for the map, which is a cached bitmap, then posts a hold with seat ids, then posts a booking with an idempotency key. The seats table has a status, a hold id and a hold expiry. A hold is one transaction: an UPDATE that only changes rows that are available or whose hold has expired, and it must change exactly as many rows as seats requested, or we roll back. That single statement is the invariant. Hotels use a count per room type per night, and a stay decrements every night in one transaction under a CHECK so the count never goes below the limit.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw it for two paths: a million people looking at the map, and one person taking a seat. Which boxes may be stale, and which one may not?
Ticket booking: high-level design
👥Buyers1,000,000 at 12:00
→↓HTTPS
🌍CDN + edgeseat map, static, 2 s cache
→↓miss
🚪Waiting roomadmit 1,250 per second
Booking path (strong)
🎟️Booking servicehold, confirm, release
🗄️Inventory shardone primary per event
⏱️Expiry sweeperfrees old holds
Money (saga)
💳Payment serviceauthorise, capture, void
📨Outbox + queuebooking events
Reads (eventual)
🗺️Seat-map cacheRedis or CDN, rebuilt from events
🔎Search indexevents and hotels
🏨Hotel availabilitycache or replica
After the sale
🔔Notificationsticket, receipt
🧾Ledger, auditwho bought what
Reads go through the CDN and may be stale. The hold goes through the waiting room to one strongly consistent shard per event. Payment runs as a saga.
ComponentWhat it does
CDN and edgeServes the seat map and static pages. A 2-second cache life turns 200,000 requests a second into about 50 at the origin.
Waiting roomHolds users in a virtual line and admits them at a fixed rate, each with a signed admission cookie. Protects the booking path.
Booking serviceStateless. Runs the hold transaction, confirms after payment, releases on cancel. The only writer of seat status.
Inventory shardA strongly consistent primary per event (with replicas for failover). Holds the seats, holds and bookings tables.
Expiry sweeperMarks old holds as free and publishes the change. Not needed for correctness, because the hold query already treats an expired hold as free.
Payment serviceAuthorises the card, captures after the seats are confirmed, voids or refunds on failure. Each call has an idempotency key.
Outbox and queueThe booking row and its event are written in one transaction. The event feeds caches, search, notifications and the ledger.
Seat-map cache and searchRebuilt from events. Eventually consistent, and fine to be a moment behind.
Write path (follow one request)
  1. A buyer joins the waiting room and gets a position. When admitted, the room sets a signed cookie that expires in a few minutes.
  2. The buyer picks seats and posts /v1/holds with the cookie and an idempotency key. The service checks the cookie, the per-user limit and the rate limit.
  3. The service runs one transaction on the event's shard: UPDATE only the free seats, count the changed rows, and roll back unless all of them changed.
  4. On success it records the hold with an expiry and returns holdId and expiresAt. On failure it returns 409 with the seats that were taken.
  5. The buyer pays. POST /v1/bookings authorises the card, then runs a second transaction: confirm the seats only if the hold still belongs to this buyer and has not expired.
  6. If the confirm works, capture the payment and write the booking and an outbox row. If it fails, void the authorisation. The outbox event updates caches and sends the ticket.
Read path (follow one request)
  1. A user opens an event page. The CDN serves the page and a compact seat bitmap with a short cache life.
  2. The browser polls the map every few seconds. The CDN answers almost every poll. About 50 a second reach the origin cache.
  3. The origin map comes from a cache rebuilt from booking events, so it trails the truth by a second or so.
  4. The user picks seats from a map that may be a moment old. The hold in step 2 above is the real check.
  5. If a seat was taken meanwhile, the hold returns 409 and the page refreshes the map and suggests the nearest free seats.
  6. Hotel searches read a search index and an availability cache. They show a hint (“3 rooms left”). The reservation call decides.
🎤
Say it out loud
“Here is the picture. Browsing is cheap and stale: a CDN serves a tiny seat bitmap with a two-second life. For an on-sale, a waiting room admits users at about 1,250 a second with signed cookies. The booking service does the hold as one conditional UPDATE on the event's single shard and rolls back unless every requested seat changed. Payment is a saga: authorise, confirm the seats if the hold is still the buyer's, then capture, and void if the confirm fails. An outbox publishes events that rebuild the seat map, the search index and the notifications.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

No double booking: the one rule that must hold

The problem: The invariant is: a seat is sold to at most one person. Two buyers click the same seat in the same millisecond. Both read AVAILABLE. If both then write, both think they won. Picking several seats makes it worse: two buyers each want seats 5 and 6, and lock them in opposite order.

OptionHow it worksGoodBad
Check, then writeSELECT the seat, see AVAILABLE, then UPDATE it to HELD in a second statement.Easy to write. Looks fine in testing, with one user.A race. Both buyers pass the check before either writes. This is the bug the visualizer shows.
Pessimistic row lockSELECT ... FOR UPDATE on the seat rows inside a transaction, then UPDATE.Simple to reason about. The second buyer waits, then sees HELD.Buyers queue on the same row. Locking several seats in different orders deadlocks. Locks held while the app does other things hurt throughput.
Optimistic compare-and-setOne UPDATE ... WHERE status = 'AVAILABLE' (or hold expired). Check how many rows changed. Zero means someone beat you.No lock held across round trips. One atomic statement. The loser is told at once. Scales well.Under heavy contention many attempts fail and must be retried or reported. You must check the changed-row count.
Redis lock or SETNX in front, database behindTake a short Redis key per seat first (with a TTL), then write to the database.Very fast filter that keeps most losers off the database.Redis is not the source of truth. A lost key or a failover can let two through. The database still needs its own conditional write.
Pick
An atomic, all-or-nothing conditional UPDATE in the database, with a unique constraint as the last guard

The compare-and-set puts the check and the write into the same statement, so there is no gap to race through. We ask for all seats in one UPDATE and compare the changed-row count with the number requested. If it is short, we roll back, so a buyer never ends up with half an order.

Two extra guards cost almost nothing. A unique constraint on (event_id, seat_id) for confirmed bookings means even a bug in the hold logic cannot sell a seat twice. And for several seats we sort the seat ids before updating, so two buyers always touch rows in the same order and cannot deadlock. A Redis filter is allowed as an optimisation to shed load, but never as the authority.

🧠The invariant, and what enforces it
Invariant: a seat has at most one confirmed owner. Enforced by: (1) the conditional UPDATE with the changed-row check on holds, (2) the unique constraint on confirmed bookings, (3) confirm only if the hold is still this buyer's. Everything else (cache, queue, waiting room) is allowed to be wrong without selling a seat twice.
Isolation level and this statementWhat happens
Read committed, conditional UPDATEEnough. The row is locked by the UPDATE, so the second writer waits, then re-checks the WHERE and changes nothing.
Read committed, check then writeNot enough. Both read AVAILABLE. This is the race.
Serializable, check then writeSafe, but one of the two transactions is aborted with an error and must retry. Correct and slower.
Hotel date rangeDecrement every night in one transaction under CHECK (booked <= total + limit). A partial failure rolls the whole stay back.
🎤
Say it out loud
“The invariant is that a seat has at most one confirmed owner, and I want one mechanism to enforce it. I would not check then write, because two buyers can both pass the check. I would use a single conditional UPDATE that only changes rows that are available, and compare the changed-row count with the seats requested, rolling back if it is short. I sort the seat ids so two buyers cannot deadlock. A unique constraint on confirmed bookings is the last guard. Redis can shed load in front, but it is never the authority.”
5.2

Holds, expiry and the late payment

The problem: A hold must end, or abandoned carts lock seats for ever. But ending it creates new races: the buyer pays one second after the hold expired, or the sweeper frees a seat in the instant the buyer confirms, or payment works and the confirm fails.

OptionHow it worksGoodBad
Hold forever until the buyer actsNo expiry. Seats stay held until paid or cancelled.Simple.Abandoned carts lock inventory for ever. Bots hold every seat. The visualizer shows seats stuck for good.
Expiry timestamp, lazy check on writeStore hold_expires_at. A hold query treats an expired hold as free. A sweeper tidies up later.Correct even if the sweeper is late or down. No timer per hold.The seat map shows the seat as held a little longer than needed, until the sweeper publishes the release.
Redis key with a TTL per holdA key per seat with an expiry. When it disappears, the seat is free.Automatic expiry. Fast.A second source of truth. A Redis failover can free held seats or keep them. The database must still decide.
Pay first, then holdCharge the card, then try to take the seat.No holds at all.Takes money and then may have to refund when the seat is gone. Poor for buyers and for fees. Fine only for general admission with a deep stock.
Pick
A hold with an expiry timestamp, treated as free once expired, a sweeper for tidiness, and a confirm that checks ownership

The expiry lives in the row, so the database alone answers the question "is this seat free right now?". The sweeper is a convenience that makes the map accurate sooner, not a requirement for correctness. That is why a late sweeper is harmless.

For the late payment, confirm is a conditional update too: set status SOLD only WHERE hold_id is this buyer's AND the hold has not expired AND status is HELD. If it changes zero rows, we do not issue a ticket and we void or refund the payment. We also allow one short extension when a payment is in flight, and we never let a hold be extended more than once.

What goes wrongState left behindWhat the design does
Buyer pays after the hold expired and the seat was sold to someone elseAuthorisation exists, seat is goneConfirm changes 0 rows, so we void the authorisation and tell the buyer. No money is taken.
Buyer pays after the hold expired but the seat is still freeAuthorisation exists, seat freeConfirm may take it if the seat is AVAILABLE and the policy allows, else void. Policy choice, stated aloud.
Payment authorised, confirm fails (crash or 409)Authorisation without a bookingSaga compensation: void the authorisation. A reconciliation job finds any that were missed.
Confirm succeeds, capture failsSeat sold, money not takenRetry capture with the same idempotency key. If it keeps failing, release the seat and cancel the booking.
Sweeper frees a seat while the buyer confirmsRace on one rowBoth are conditional updates on the same row, so one wins. A buyer who loses gets a clear message and a void.
Confirm only if the hold is still this buyer's
UPDATE seats
   SET status = 'SOLD', booking_id = :b, version = version + 1
 WHERE event_id = :e AND seat_id IN (:ids)
   AND status = 'HELD' AND hold_id = :hold AND hold_expires_at >= now();
-- rows changed must equal the seats in the hold, else: void the payment authorisation
🎤
Say it out loud
“A hold has an expiry in the row, and the hold query treats an expired hold as free, so the database alone decides and a late sweeper is harmless. Confirming is a conditional update as well: sold only if the hold is still this buyer's and has not expired. If it changes no rows we void the payment. The order is authorise, confirm, then capture, so we never take money for a seat we cannot give. A reconciliation job finds any authorisation without a booking.”
5.3

Surviving the flash sale

The problem: A million people arrive at the same second for 50,000 seats. 100,000 hold attempts a second would hit a shard that does about 5,000. More app servers do not help, because every request needs the same few database rows. Bots make it worse, and everyone wants the same good seats.

OptionHow it worksGoodBad
Autoscale and hopeAdd app servers as load grows.Easy to say.The database is the bottleneck, not the app. Extra servers only create more contention and a bigger outage.
Rate limit and rejectReturn 429 above a limit.Protects the system.Unfair: the winners are whoever retries fastest, which means bots. The experience is a wall of errors.
Waiting room (virtual queue)Put users in a line at the edge, admit them at a fixed rate, give each a signed, time-limited admission cookie.Fair (by arrival), predictable load, honest wait time. Protects the booking path completely.More to build. The line itself must scale, and the admission token must be hard to forge or share.
Lottery or pre-registrationCollect requests for a window, draw winners at random, then let winners buy.Very fair, no race at all, easy on the system.Not first come, first served. A product decision. Needs verified identities to stop gaming.
Pick
A waiting room that admits users at a rate the shard can take, with signed admission cookies, per-user limits, bot checks and a cached seat map

The numbers decide this. One shard handles about 5,000 holds a second. If each admitted user makes two attempts and we run at half capacity, we admit about 1,250 users a second, so a million people take about 13 minutes to enter. That wait is honest, and we show it. The line absorbs the spike at the edge, where requests are cheap, so the expensive booking path sees a flat, steady load.

The pieces that make it hold up: a signed, short-lived cookie proves a user was admitted (and is tied to an account, so it cannot be shared); the seat map is cached so browsing costs the origin almost nothing; a per-user limit (say 6 tickets) and bot challenges keep it fair; and a load-shedding switch drops lowest-priority work (search, recommendations) before the booking path suffers.

LayerWhat it protectsHow
CDN and seat-map cacheThe origin from read load2-second cache of a 12.5 KB bitmap. 200,000 requests a second become about 50.
Waiting roomThe booking path from the spikeAdmit 1,250 a second. Position and estimated wait shown to the user.
Admission cookieFairness and the line itselfSigned, bound to an account, expires in minutes, one live cookie per account.
Per-user and per-device limitsAgainst hoardingAt most N seats per order and per person per event.
Bot defenceAgainst machines beating humansChallenges at the door, verified accounts, behaviour checks, throttling by device and network.
Hot-row reliefThe best seats are contendedShard by event, then split by section if one event outgrows a shard. Offer “best available” so users do not all pick the same seat.
Load sheddingThe booking path when all else failsDrop search, recommendations and analytics first. Keep hold and confirm.
💡Try it in the visualizer
Switch to "Check, then book" and raise the waiting room rate. With a rate of 1 per tick, double bookings vanish, but only because the line serialised everyone. That is luck, not a fix: the atomic hold is what protects the seat, the waiting room protects the servers.
🎤
Say it out loud
“Autoscaling does not help, because the bottleneck is a few database rows, not the app servers. A million people at once means about 100,000 hold attempts a second against a shard that does 5,000. So I put a waiting room at the edge that admits about 1,250 users a second with a signed admission cookie, which means a 13-minute line that we show honestly. The seat map is cached so browsing is almost free. I add per-user limits and bot checks, and a load-shedding switch that drops search before it drops holds. The atomic hold still protects the seat. The waiting room only protects the servers.”
5.4

Reads, writes, regions and consistency

The problem: Most traffic is reads (looking at maps and search results) and they can be stale, but the write must be exact. Users are global, and two regions that both sell the same seat will sell it twice. Search, caches and the seat map must agree closely enough that users are not constantly told “sorry, taken”.

OptionHow it worksGoodBad
One global database, everyone writes to itA single primary far from some users.Simple, one source of truth.High latency for far-away users, and one region is a single point of failure.
Single writer per event (home region), replicas elsewhereEach event has a home shard in one region. Other regions serve cached reads and send holds to the home region.No cross-region write conflicts. The invariant stays simple. Reads are local.Far users pay a round trip on the hold. If the home region fails, we need a tested failover.
Multi-writer with conflict resolutionAny region sells any seat, and conflicts are merged later.Local writes everywhere. Survives region loss without failover.Two regions will sell the same seat, and “merge” means an apology and a refund. Wrong for a hard inventory limit.
Pre-allocate inventory per regionGive each region a block of seats (or a share of the count) to sell on its own.Local writes and no overselling. Good for general admission and hotel counts.Unsold blocks strand in a quiet region, so you need a rebalancing step. Hard for specific numbered seats.
Pick
A single writer per event in its home region, cached and replicated reads everywhere, and an outbox to keep caches and search up to date

The cost of a wrong write is high (an oversold seat and an angry customer), and the cost of a stale read is low (a polite "seat taken, here are the nearest"). So we put strong consistency exactly where it matters, one primary per event, and let everything else be eventually consistent.

Caches and search are rebuilt from booking events, published through an outbox so a booking row and its event cannot disagree. Each map carries a version, so the client can tell a fresh map from an old one. Search results are a hint: a hotel shows "3 rooms left", and the reservation call is the one that decides. For hotels with outside systems (channel managers, other sites) we accept that inventory can drift, and reconcile on a schedule.

Hotel-specific topicHow the design treats it
Inventory shapeOne row per (hotel, room type, night) with total and booked. Searching a stay reads every night in the range.
Booking a stayIncrement booked for every night in one transaction under a CHECK. If any night is full, the whole stay fails.
OverbookingA business rule: allow booked up to total plus a small limit, tuned per property. The CHECK enforces the limit, so it is deliberate, not an accident.
Prices and ratesPrice is read at hold time and frozen with the reservation, so a change mid-checkout does not change what the buyer agreed to.
Cancellation and refundsCancel decrements booked for every night and applies the policy's refund. Same idempotent saga as a purchase.
Outside systemsChannel managers and partner sites sync by events and a nightly reconciliation. Expect drift, detect it, and fix it with a clear winner rule.
Time zonesNights are dates in the hotel's own time zone. Store the property's zone, and never compare local dates across zones.
🎤
Say it out loud
“I put strong consistency in exactly one place: one primary per event, in a home region, where the hold happens. Everything else is eventually consistent. Caches and search are rebuilt from booking events through an outbox, and the map carries a version. A wrong write costs an oversold seat, a stale read costs a polite 'seat taken', so that is the right place to draw the line. I avoid multi-writer, because two regions would sell the same seat. For hotels, inventory is a count per room type per night, a stay decrements every night in one transaction under a CHECK, and overbooking is a deliberate limit.”
VisualizerA hall of 48 seats, 30 buyers: race, hold and expiryStart with “Check, then book” and see seats sold twice. Switch to the atomic hold, then add the expiry sweeper and move the hold time. Then add a waiting room and watch the wait grow while the load stays flat.
How is a seat taken?
The hall: 48 seats at the end of the script (40 ticks). Grey = free, amber = still held, green = sold, red = sold twice.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Seats sold
13
of 48
Sold twice
10
double bookings
Told “taken”
1
lost the race, cleanly
Held for ever
6
abandoned, never freed
Released and resold
0
by the expiry sweeper
Paid after expiry
0
refunded
Average wait
0 ticks
longest 0
10 seats were sold to two buyers. Each buyer read “free”, then wrote “mine”, and nothing made the second write fail. The read and the write must be ONE atomic step. A compare-and-set (UPDATE ... WHERE status = 'AVAILABLE') lets only one writer win.

A teaching model with a fixed script and no random numbers: 30 buyers, 20 of them in 10 pairs who want the same seat in the same tick, 6 who take a seat and walk away, 3 who pay 9 ticks after taking a seat, and 1 who arrives late. Paying takes 3 ticks. In “no protection” mode the buyers in one tick all read first and write second, which is what a race looks like.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Run the worst hour. The hot shard is melting, a payment provider is slow, a region drops, and bots are in the queue. What breaks first, and what do you do about it?

What breaks first, and the fix

BottleneckFix
The inventory shard for the hot eventAdmit users at the waiting-room rate, keep transactions short (no network calls inside them), index (event_id, status), and split a huge event by section across shards.
The best seats attract every clickOffer best-available so people do not all choose seat A1, and show the nearest free seats when a hold fails instead of an error.
Seat-map polling from a million browsersA 2-second CDN cache of a compact bitmap, and push a delta over a WebSocket or server-sent events for users who are in the booking path.
The payment provider is slowTimeouts, a hold time long enough to cover them, retry with the same idempotency key, and a second provider as a fallback. Never keep a database transaction open while waiting for a card.
Sweeper and release stormsExpiry is lazy, so the sweeper only tidies. Run it in small batches by event, and publish releases in bulk so caches do not thrash.
Hotel searches over many nights and propertiesA search index with a rough availability summary, and exact counts only at reservation time. Cache by (property, date range) with a short life.
The waiting room itselfIt is a separate, simple service on the edge. Keep its state small (a sorted position and a token), and let the CDN or edge workers serve the line page.

What if a part fails?

FailureHow the design copes
Payment is authorised but the confirm failsVoid the authorisation (saga compensation). A reconciliation job lists authorisations with no booking and voids them, so no money is stuck.
The booking service crashes between confirm and captureThe booking row is in a PENDING_CAPTURE state. On restart (or from the outbox) we retry capture with the same idempotency key. After several failures we release the seats and cancel.
The inventory primary failsFail over to a synchronous replica. Holds in flight are in the database, so they survive. Writes pause for seconds, and the waiting room slows admission while it happens.
The home region of an event goes downPromote the replica region for events that have a standby, fence the old primary with a bumped epoch, and prefer to stop selling over double selling.
The cache shows a seat as free that is soldThe hold returns 409. We refresh the map and offer the nearest alternatives. The cost is a retry, not an oversold seat.
The event bus or outbox is delayedMaps and search lag, and the sale is unaffected. Alert on lag, and rebuild a map from the database if the lag grows.
What to monitor
  • •Hold success rate, and 409 (seat taken) rate, per event
  • •Hold-to-booking conversion and the share of holds that expire unpaid
  • •Waiting-room queue length, admit rate and wait time
  • •Shard latency (p99), lock waits and the number of rolled-back hold transactions
  • •Authorisations without a booking (should be near zero), and capture failures
  • •Event and cache lag: how far the seat map trails the database
Security and abuse
  • •Signed, short-lived admission cookies bound to an account, so they cannot be shared or replayed
  • •Bot defence: challenges, account age, device and network checks, and per-account and per-card limits
  • •Never trust the client for price, seat status or hold ownership: check them on the server on every call
  • •Protect payment data by sending it straight to the payment provider (card details never touch our servers), which keeps most of the payment-card compliance burden small
  • •Make tickets hard to forge: signed, rotating barcodes, and tie them to the booking in the database

Step 7Wrap upabout 3 min

Reads are cached and stale on purpose. The only place that decides who gets a seat is one atomic conditional update on a strongly consistent shard, with a unique constraint as a last guard. Holds expire in the row, confirm checks ownership, and payment is a saga with void and refund as compensation. A waiting room meters a million people down to the rate one shard can take, and one home region per event keeps writes conflict-free.

Trade-offs you made

DecisionWhat we gainWhat it costs
A single writer per eventNo cross-region conflicts and a simple invariant.Far-away buyers pay a round trip, and failover needs care.
A stale, cached seat mapThe origin is nearly idle even with a million people watching.Some clicks fail with “seat taken”. We soften it with nearest-seat suggestions.
A waiting roomFairness and a flat, safe load on the database.A wait for users, and one more component that must itself scale.
Short holdsSeats return to sale quickly.Slow payers lose their seats, so refunds and support contacts go up.
Authorise, confirm, then captureWe never take money for a seat we cannot give.More steps and compensation paths to test.
A deliberate overbooking limit for hotelsHigher occupancy when guests cancel or do not show.Sometimes a guest must be relocated, and that costs money and goodwill.
If we had more time, we would…
  • •Best-available seat search, group seating (seats together) and accessibility seating rules.
  • •Resale and transfer, with the same invariant and a new owner on the ticket.
  • •Dynamic pricing and a fairer lottery for the biggest events.
  • •Multi-region standby with a rehearsed, fenced failover.
  • •A load-test harness and race-condition tests that replay the on-sale with real concurrency.
🎤
Say it out loud
“To recap: the seat map is cached and stale on purpose, and the only thing that decides a seat is one atomic conditional update on one shard per event, backed by a unique constraint. Holds expire in the row, confirm checks that the hold is still the buyer's, and payment is authorise, confirm, capture, with a void if anything fails. A waiting room turns a million people into 1,250 a second. Hotels use per-night counts under a CHECK, and any overbooking is a deliberate limit. Next I would add best-available search, resale, and a rehearsed regional failover.”

Q&ACross-questions (28)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Stopping the double booking

The core of the question. Say the invariant, then show the mechanism that enforces it.

Holds, expiry and payment

Multi-step failures. Say what state is left behind and how you recover.

The flash sale

Scale, fairness and bots. Show that you know where the real bottleneck is.

Consistency, regions and hotels

Where strong consistency lives and where it does not. Hotels are the same problem with ranges.

Operating it and proving it works

What a senior engineer adds: testing, monitoring and cleanup.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
General admission, no seat numbersInventory becomes a counter per section. The hold is UPDATE ... SET remaining = remaining - n WHERE remaining >= n. All contention is on one hot row, so split the counter into several sub-counters (sharded counters) and draw from the nearest one.
Add resale and ticket transferA ticket gets an owner, and a transfer is a conditional update of the owner. We add a ticket history for audit and fraud checks, and a price cap or fee rules as a product policy.
The sale must be strictly first-come, first-servedDrop the randomising at the start, order the waiting room by arrival time, and accept that bots with fast connections have an edge. Add stronger verification to compensate.
Make it a lottery for the biggest eventsCollect entries for a window, draw winners at random with verified identities, and give each winner a private purchase window. No race, no waiting room pressure, and a very different feel.
Multiple regions must accept writesPre-allocate inventory shares to each region for counted stock. For numbered seats keep a single writer per event, because multi-writer needs merge rules that mean overselling.
Dynamic pricing: price rises with demandA pricing service sets a price per section at hold time, frozen with the hold. Keep it out of the transaction, and cache the price for a short, fixed time so all buyers in a window see the same one.
Hold time must be much longer (30 minutes) for big purchasesMore inventory is locked at any moment, so cap holds per user, show a visible countdown, and offer an extension only once. Expect a lower conversion rate for the last seats in a sale.
Add a waitlist for sold-out eventsA queue per event. When a seat is released (cancel or expiry), offer it to the next person with a short private hold. It reuses the same hold and expiry mechanism.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing at once. Never asks about holds, overbooking or the size of an on-sale.Asks about seat types, hold time, payment and the busiest moment, and writes the scope down.Also settles the overbooking policy, the hotel shape, fairness and bots, and says what is out of scope.
EstimationNo numbers, or only the number of users.Gets reads and bookings per second and sees the on-sale spike.Shows 200,000 map polls become 50 at the origin, 100,000 holds are 20 times too many, and sets the admit rate from the shard's capacity.
CorrectnessCheck then write, or a vague distributed lock.Uses a conditional update or a row lock, and says what the loser sees.States the invariant, uses an all-or-nothing conditional UPDATE, sorts seat ids, adds a unique constraint, and names which mechanism enforces what.
FailuresOnly the happy path.Handles hold expiry and a failed payment.Walks through payment ok but confirm fails, late payment, a crash between steps, a primary failover and the reconciliation job.
ScaleAutoscale the servers.Caches reads, adds a queue or rate limit.A waiting room metered to shard capacity, hot-section sharding, best-available to spread the load, load shedding and honest wait times.
Trade-offsOne solution presented as the only one.Compares locking with compare-and-set.Puts strong consistency in exactly one place, explains single-writer versus multi-writer, and states the cost of each choice.

AvoidCommon mistakes on this question

MistakeDo this instead
Check the seat, then write it in a second stepOne conditional UPDATE that checks and writes together, and verify the changed-row count.
Trusting the cached seat map to decide a bookingThe map is a hint. The hold on the primary is the decision.
Holds with no expiryStore hold_expires_at, treat an expired hold as free, and run a sweeper only for tidiness.
Charging the card before confirming the seatAuthorise, confirm, then capture, and void if the confirm fails.
Holding a database transaction open while waiting for the payment providerKeep transactions to one short statement. Do the slow call outside, and use idempotency keys.
Solving the flash sale by autoscalingMeter users at the edge with a waiting room, and cache the read side.
Using Redis alone as the source of truth for who owns a seatUse it as a fast filter. The database decides, with a unique constraint behind it.
Locking several seats one at a time, in the order the buyer clickedHold them in one statement and sort the ids, so deadlocks cannot happen.

Revise60-second revision sheet

  • ✔Invariant: a seat has at most one confirmed owner. Say it first.
  • ✔Enforce it: one conditional UPDATE, check rows changed, all-or-nothing, plus a unique constraint on confirmed bookings.
  • ✔Holds: expiry stored in the row. An expired hold counts as free. The sweeper only tidies.
  • ✔Confirm: only if the hold is still this buyer's and not expired. Otherwise void the payment.
  • ✔Money: authorise, confirm, capture. Void or refund as compensation. Idempotency key on every step.
  • ✔Flash sale: 200,000 map polls need a CDN (about 50 reach the origin). 100,000 holds a second need a waiting room (about 1,250 users a second).
  • ✔Consistency: strong for inventory and holds, eventual for the map, search and notifications.
  • ✔Regions: one writer per event. Never two regions selling the same seat.
  • ✔Hotels: a count per room type per night, decremented for every night in one transaction under a CHECK. Overbooking is a deliberate limit.
  • ✔One line: “Cache the reading, serialise the deciding, and never take money for a seat you cannot give.”

Read these topics next

Design a Payment System→

The authorise, capture, void and refund flow, and idempotent money movement.

ACID Transactions→

Why the hold and the confirm must be all-or-nothing.

Locking and MVCC→

Pessimistic and optimistic locking, and what a conditional update relies on.

Transaction Isolation Levels→

Which level the hold needs, and where check-then-write breaks.

Idempotency→

Making a retried booking or payment safe.

SAGA Pattern→

The payment and confirm steps with compensation.

Back Pressure→

The idea behind a waiting room that protects the booking path.

Design a Rate Limiter→

Per-user and per-device limits at the door.

← Previous
Design a Payment System
Next →
Design a Search Engine