InterviewDryRun
Lesson 14 · 21 min video · free

Design a Ticket Booking System

When tickets for a big concert go on sale, hundreds of thousands of people arrive in the same minute for a few tens of thousands of seats. This lesson designs seat selection and purchase that never sells a seat twice: short seat holds with expiry, atomic conditional updates, a virtual waiting room to meter the crowd, and a payment flow that releases seats when it fails.

What you will learn

  • The core invariant: a seat is sold at most once. Protect it in the database, not in application code.
  • Hold seats for a few minutes with an expiry; confirm only after payment succeeds.
  • Claim seats with one conditional update, so concurrent buyers cannot both win.
  • A virtual waiting room admits buyers at the rate the system can handle.
  • Serve the seat map from cache; it may be stale, the hold is the real check.
  • Expire holds reliably and release seats if payment fails or times out.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API
  5. Step 4: The data model
  6. Step 5: The booking flow
  7. Step 6: Never selling a seat twice
  8. Step 7: Holds that expire
  9. Step 8: Payment and confirmation
  10. Step 9: The virtual waiting room
  11. Step 10: Serving the seat map
  12. Step 11: Bots and fairness
  13. Step 12: The first ten minutes of an on-sale
  14. Step 13: Failures
  15. Step 14: The follow-up questions
  16. Recap

Short on time? Read the answer outline for design a Ticket Booking System.

Practice this question with Max

The question

Welcome to lesson fourteen of the InterviewDryRun system design course. Today we design a ticket booking system for high-demand events: the moment when tickets for a famous artist's concert go on sale, and half a million fans arrive at once for fifty thousand seats.

This question combines two hard problems. The first is correctness under contention: thousands of people clicking the same seat at the same instant, and exactly one of them must get it. The second is surviving a crowd: a traffic spike so sharp that, without care, the site falls over in the first ten seconds and nobody gets anything. Interviewers like it because a good answer needs both a precise locking story and a system-level traffic story.

Max asks

“Design seat selection and purchase for high-demand concert tickets without overselling.”

That is how Max, our AI interviewer, asks it. The phrase without overselling is the core invariant. Write it at the top of your whiteboard: a seat is sold at most once. Everything else, speed, fairness, user experience, can bend a little. That cannot.

The plan: requirements and numbers, then the API and the data model. Then the booking flow with seat holds, the concurrency deep dive on preventing double booking, hold expiry, payment, the waiting room for the crowd, caching the seat map, bots and fairness, and failures. Then the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Browse eventsFind a show, see prices and sections
  2. 02
    See the seat mapWhich seats are available, roughly live
  3. 03
    Choose and hold seatsUp to a ticket limit per buyer
  4. 04
    Pay and confirmThen receive tickets
  5. 05
    General admission tooStanding areas sold by count, not seat

Start with questions.

Users browse events, open a show, and see a seat map showing which seats are free. They pick seats, up to a limit per person, say six, and those seats are held for them while they pay.

Then they pay, the booking is confirmed and tickets are issued. Ask about general admission: standing areas where there are no seat numbers, just a count of tickets. It changes the data model slightly, from individual seats to a counter, and it is worth handling both.

Ask what happens if the buyer does not finish paying. The answer, nearly always, is that the hold expires after a few minutes and the seats go back on sale. That one answer drives a big part of the design.

Non-functional requirements
  1. 01
    Never oversellStrong consistency for seat state
  2. 02
    Survive the on-sale spikeHundreds of thousands arrive in a minute
  3. 03
    FairFirst come, first served, not fastest bot
  4. 04
    Fast enoughHolding a seat in under a second
  5. 05
    AvailableA crash during the on-sale is very public

The qualities. Never oversell: for seat state, we choose strong consistency, even at the cost of availability. Say it clearly: if the seat database is unreachable, we stop selling rather than risk selling a seat twice.

Survive the spike: a popular on-sale sends hundreds of thousands of users in the first minute. And fairness: real fans should get tickets in roughly the order they arrived, not automated scripts that click a thousand times a second. Fairness is a real requirement here, because unfair sales make headlines.

Speed and availability matter too, but notice the order: correctness first, then survival, then fairness, then speed. Stating your priorities like that is a strong opening.

Step 2: Back-of-the-envelope estimates

One big on-sale
Seats50,000one stadium show
Fans arriving500,000in the first few minutes
Seat map viewshundreds of thousands / min
Hold attemptsthousands / smost on the best seats
Sold out inabout 10 to 20 minutes

Let us size one big on-sale, because a single event is the stress case, not the daily average.

Fifty thousand seats, and say five hundred thousand fans arrive in the first few minutes, ten for every seat. If they all load the seat map and refresh it every few seconds, that is hundreds of thousands of map requests a minute.

Hold attempts: thousands a second at the start, concentrated on the best seats, the front rows, where hundreds of people click the same seats at the same moment. With roughly three seats per buyer, about seventeen thousand buyers succeed, and the show sells out in ten to twenty minutes.

The conclusion from these numbers is interesting. The total data is tiny: fifty thousand seats fits in memory anywhere. The write rate is moderate. The problems are contention, many people fighting over the same rows, and the read storm on the seat map. Neither is solved by adding more database capacity. Both need design.

And the rest of the year is quiet. Most events sell slowly, a few tickets an hour, and the system idles. So we should not size permanent infrastructure for the peak. Instead, scale up the waiting room, map caches and booking services ahead of announced big on-sales, which are scheduled weeks in advance, and use the waiting room as the safety valve if demand is even higher than expected.

Step 3: The API

API
GET  /v1/events/{eventId}/seatmap      → sections, seats, status
POST /v1/events/{eventId}/holds
  Idempotency-Key: ...
  { seatIds: ["A-12", "A-13"] }
→ 201 { holdId, expiresAt }   or  409 { unavailable: ["A-13"] }

POST /v1/holds/{holdId}/checkout  { paymentToken }
→ 200 { bookingId, tickets }  or  402 payment failed
DELETE /v1/holds/{holdId}           // release early

The API mirrors the flow. Read the seat map for an event. Create a hold on a set of seats, which either returns a hold id with an expiry time, or a conflict listing the seats that were not available.

Holds are all or nothing: if a user asks for two seats together and one is taken, they get neither, because two seats in different rows is not what they wanted. The app shows the conflict and refreshes the map.

Then checkout pays for a hold and turns it into a booking. And the user can release a hold early, for example by going back to choose different seats. Every state-changing call carries an idempotency key, for the same reason as in the payments lesson: retries on flaky connections must never create two holds or two charges.

Step 4: The data model

Core tables
TableKeyHolds
eventsevent_idvenue, time, on-sale time, limits
seatsevent_id, seat_idsection, row, price, status, hold_id, version
holdshold_iduser, seats, expires_at, state
bookingsbooking_iduser, seats, payment_id, tickets
ga_inventoryevent_id, areacapacity, held, sold

The data model is small. Events have a venue, a start time, an on-sale time and a per-buyer limit.

The key table is seats: one row per seat per event, with its section, row and price, and a status: available, held or sold. When held, it records which hold owns it. A version number supports optimistic concurrency. Fifty thousand rows per event.

Holds record who holds which seats until when, and bookings record confirmed purchases with their payment. For general admission, there are no seat rows, just a capacity, a held count and a sold count per area.

Where does this live? In a relational database with transactions, because our core invariant needs atomic, consistent updates. The data per event is small enough that one database primary can handle one event's seats, and different events can live on different shards, partitioned by event id.

Notice what is not in the seats table: the list of people who looked at a seat, or clicks that failed. Those are analytics events, written to a log, not to the database that enforces our invariant. Keeping the transactional tables lean means every transaction touches as little as possible, which is exactly what we want when thousands of transactions compete for the same few rows.

Step 5: The booking flow

High-level design
admittedholdchargechangesCLIENTFanEDGEWaiting roomadmits at a set rateSERVICESeat map servicecached, a second staleSERVICEBooking serviceholds, checkoutSTORESeats DBsource of truthSERVICEPayments

Here is the flow end to end. During a big on-sale, fans first land in a virtual waiting room, which admits them into the shop at a controlled rate. We will come back to it, because it is how we survive the spike.

Once admitted, the fan sees the seat map, served by a seat map service from a cache that is at most a second or two behind the database. It may show a seat as free that was just taken. That is fine, because the map is not the check.

The fan picks seats, and the booking service tries to hold them in the seats database. That is the real check, done atomically. If it succeeds, the seats are held for this fan for, say, eight minutes.

The fan pays. On success, the booking service turns the hold into a booking and the seats become sold. On failure, or if the timer runs out, the hold is released and the seats are available again. The two-step structure, hold then pay, is the classic answer: it stops people losing a seat while typing their card number, without letting anyone sit on seats forever.

Step 6: Never selling a seat twice

Claiming seats atomically
BEGIN
UPDATE seats
   SET status = 'held', hold_id = :hold, held_until = now() + 8 min
 WHERE event_id = :event
   AND seat_id IN ('A-12', 'A-13')
   AND (status = 'available'
        OR (status = 'held' AND held_until < now()))
-- rows updated must equal 2, else ROLLBACK and return 409
COMMIT

Now the heart of the question. Two fans click seat A twelve at the same instant. How do we guarantee only one gets it? The wrong answer is: read the seat, see it is available, then write it as held. Two requests can both read available before either writes, and both think they won. That race is exactly how systems oversell.

The right answer is a single conditional update: set the seat to held, only where it is currently available, or held with an expired hold. The database runs that check and the write as one atomic step, with a row lock. One request updates the row; the other finds the condition no longer true and updates nothing. Then we check how many rows changed. If we asked for two seats and only one changed, we roll back the whole transaction and report a conflict. All or nothing.

Interviewers often ask about alternatives, so mention them. Pessimistic locking, selecting the rows for update first, works too, but holds locks for longer. Optimistic locking with a version number works, and is the same idea as our conditional update. A distributed lock service is possible, but unnecessary here, and adds a second system that can disagree with the database. The principle to state: put the invariant where the data lives, and let the database enforce it.

General admission uses the same idea with a counter: increase the held count by three only if held plus sold plus three is at most the capacity. One atomic conditional update, so a thousand concurrent requests can never push the area over capacity.

What about contention on the hottest seats? Hundreds of requests for the front row all queue on a handful of row locks. Each transaction is tiny, a millisecond or two, so a single database handles thousands of these a second. And the waiting room keeps the number of concurrent buyers within that range. That is how the two halves of the design fit together.

One last guard belongs in the schema itself. Add a unique constraint so that a seat can appear in at most one confirmed booking. Even if some future code path has a bug, the database will refuse the second sale. Defence in depth for the one rule that must never break costs nothing, and interviewers like hearing it.

Step 7: Holds that expire

Releasing seats reliably
  1. 01
    Expiry is in the dataheld_until stored on the seat row
  2. 02
    Lazy releaseAn expired hold counts as available in the claim query
  3. 03
    SweeperEvery few seconds, reset expired holds and update the map
  4. 04
    Grace for paymentPayment in progress extends the hold slightly

Holds must expire reliably, or seats get stuck in held forever after a browser closes. The safest approach is to store the expiry time on the seat row itself, rather than relying on a timer in some server's memory that disappears if the server crashes.

Then expiry works even if nothing else runs: the claim query we just wrote treats a held seat with a past expiry time as available. So a new buyer can take an expired seat immediately, in the same atomic update.

On top of that, a sweeper job runs every few seconds, resets expired holds to available, and publishes the change so the seat map shows those seats again. The sweeper is for the map's sake; correctness does not depend on it.

One subtlety: what if a fan submits payment at second seven fifty-nine, and the hold expires while the payment is being processed? When checkout starts, mark the hold as paying and extend it by a minute, using the same conditional update, only if it is still held by this fan. Then payment can finish without someone else grabbing the seat mid-charge.

Step 8: Payment and confirmation

Checkout safely
  1. 01
    Idempotent chargeHold id as the payment idempotency key
  2. 02
    Confirm atomicallySeats held by this hold become sold
  3. 03
    Payment failsRelease the hold, or let the user retry within time
  4. 04
    Charged but hold lostDetect and refund automatically

Checkout uses everything from the payments lesson. Call the payment service with an idempotency key derived from the hold, so a double click or a retry never charges twice.

When payment succeeds, confirm in one transaction: change the seats from held by this hold to sold, and create the booking. Again a conditional update: only seats still held by this hold. Then issue tickets, by email and in the app, asynchronously.

If the payment is declined, let the user try another card while the hold lasts, or release the hold so others can buy.

And the nasty edge case: the payment succeeds, but by the time we try to confirm, the hold has gone, perhaps because of a long payment timeout. The seats might already belong to someone else. We must never oversell to fix it. Instead, detect it, refund the payment automatically, and tell the user honestly. Keep this case rare with the paying extension we described, but always handle it. Interviewers will ask.

Step 9: The virtual waiting room

Metering the crowd
jointokenCLIENT500,000 fansEDGEEdgestatic queue pageQUEUEQueue serviceposition per fanSERVICEAdmissionN per minute, signed tokenSERVICEShopmap, holds, checkout

Now the crowd. If half a million people hit the seat map and booking services in the same minute, those services will collapse, no matter how correct they are. The proven answer is a virtual waiting room.

Fans who arrive before or at the on-sale time are shown a lightweight queue page, served from the edge, which costs almost nothing. Each fan gets a position. Fairness rule: everyone who arrives before the sale starts gets a random position, so refreshing early or using a fast script gives no advantage; after the start, positions are first come, first served.

An admission service lets people in at a controlled rate, say two thousand per minute, matched to what the booking system can handle. Each admitted fan receives a signed, time-limited token, and the shop only serves requests that carry a valid token. Everyone else sees their position and an estimated wait.

The waiting room turns an impossible spike into a steady, manageable flow. It also improves fairness and gives honest feedback: you are number forty-two thousand, about twenty minutes. When the show sells out, the waiting room tells everyone at once, instead of letting them discover it one failed click at a time. Say that this is a product decision as much as an engineering one.

Step 10: Serving the seat map

A map that does not melt the database
  1. 01
    Snapshot per eventCompact bitmap of seat status, rebuilt every second
  2. 02
    Push updatesChanged seats streamed to open maps
  3. 03
    Section summariesSeats left per section and price
  4. 04
    Stale is fineThe hold is the real check

Admitted users still load and refresh the seat map constantly. Do not query the seats table for every view. Instead, keep a compact snapshot per event: a bitmap with one bit or two per seat, fifty thousand seats in a few kilobytes, rebuilt every second from the database's changes, and served from cache.

Open maps can receive updates as seats are held and sold, over a lightweight push connection or by polling the small snapshot every few seconds. Showing seats disappear in near real time reduces failed clicks, which reduces load on the booking path.

Most users first choose by section and price, so serve section summaries, like forty seats left in section B, which are even cheaper. And state the principle again: the map is allowed to be stale by a second or two, because the atomic hold is the only check that matters. Separating the display from the decision is what lets us cache aggressively without risking correctness.

Step 11: Bots and fairness

Keeping it fair
  1. 01
    Per-buyer limitsTickets per account, card, and address
  2. 02
    Verified accountsPhone verification before big on-sales
  3. 03
    Bot signalsRates, devices, behaviour; challenges when suspicious
  4. 04
    Hold limitsOne active hold per user

Bots are the enemy of fairness. They buy the best seats in seconds and resell them at many times the price. Start with limits enforced on the server: tickets per account, per payment card, per delivery address, checked when holding and when confirming.

For big on-sales, require accounts to be verified in advance, for example with a phone number, and even pre-register fans for a lottery-style access code. Pre-registration lets you know the real demand ahead of time and spread access fairly.

At runtime, score requests for bot behaviour, from request rates, device fingerprints and interaction patterns, and challenge suspicious ones. And allow only one active hold per user, so a script cannot hold hundreds of seats while it decides. The waiting room's random ordering for early arrivals removes the advantage of speed. Together, these make the sale fair enough for real fans.

Finally, check limits again at confirmation, not only at hold time, because a determined buyer can open several sessions. The confirm transaction counts the buyer's existing bookings for the event and refuses to go over the limit.

Step 12: The first ten minutes of an on-sale

A big on-sale, minute by minute
TimeWhat happensWhat protects us
minus 30 minfans join the waiting roomstatic page at the edge
0:00random order fixed; admission startssigned tokens, fixed rate
0:00 to 0:05front sections held within secondsconditional updates, small transactions
0:05 to 0:15holds expire and seats returnexpiry in rows, sweeper
sold outeveryone told at oncewaiting room closes

Let us put all of this together by walking through an actual on-sale, minute by minute, because it shows the interviewer that the pieces work as one system.

Half an hour before the sale, fans start arriving. They are placed in the waiting room, a static page served from the edge, which costs us almost nothing however many arrive. Our booking services see no traffic at all.

At the on-sale time, positions for everyone already waiting are fixed in a random order, and admission begins at the rate we tested, a couple of thousand fans a minute. Admitted fans open the seat map from cache and try to hold seats. The front sections go within seconds: hundreds of conditional updates on the same rows, each one a millisecond, each one either winning or getting a clean conflict and a refreshed map.

Over the next few minutes, some fans fail to pay, or abandon. Their holds expire, the sweeper returns the seats, the map shows them again, and the admission service, seeing seats come back, keeps admitting. Monitoring watches hold success rate, checkout latency and database load, and adjusts the admission rate up or down.

When the last seat is sold, the waiting room switches to a sold out message for everyone still queued, perhaps with an option to join a waitlist for returns. Nobody spent twenty minutes clicking on seats that no longer existed. That is what a well-designed on-sale feels like from the outside: calm, even when the demand is ten times the supply.

Step 13: Failures

What breaks
  1. 01
    Seats DB primary failsSynchronous replica takes over; pause holds briefly
  2. 02
    Payment provider slowExtend holds, queue confirmations
  3. 03
    Waiting room failsFail closed: admit nobody rather than everyone
  4. 04
    Ticket issuing failsBooking is confirmed; issue later, retry

If the seats database primary fails, a synchronous replica takes over, so no confirmed hold or sale is lost. During the few seconds of failover, holds fail and users retry. We prefer that pause over any risk of two primaries both selling seats.

If the payment provider slows down, holds that are in payment are extended, and the admission rate is lowered, so fewer new users pile into a slow checkout.

If the waiting room itself fails, fail closed: admit nobody, rather than letting half a million people straight through to the shop. A delayed sale is embarrassing; a collapsed sale is much worse.

And if issuing tickets fails after a confirmed booking, the booking stands, because it is recorded, and tickets are issued later by a retrying job. The user sees a confirmed booking immediately, with tickets to follow.

Step 14: The follow-up questions

Max asks

“Why not use an in-memory store with a lock per seat instead of the database?”

It can be faster, and some designs use an in-memory store for holds. But then the seat state lives in two places, and if they disagree after a crash or a failover, we can oversell. If I used one, I would make it the only source of truth for holds, with durable replication, and still record final sales in the database with a conditional update. For fifty thousand seats, the database alone is fast enough, so I would keep it simple.

Max asks

“How would you let a group of friends buy seats together?”

One person holds the block of seats, up to a group limit, and invites friends to pay for their own seats within the hold time, with the hold extended while invitations are pending. If a friend does not pay in time, the organiser can pay for that seat or release it. It is the same hold and confirm machinery, with a split payment step.

Max asks

“How would you design the resale of tickets?”

A resale listing is a ticket moving back into a market, so it goes through the same hold and checkout flow, with the seller's ticket as the inventory instead of a fresh seat. When it sells, the old ticket is invalidated and a new one issued, so only one valid ticket exists per seat. Price caps and seller limits enforce the anti-scalping policy.

Max asks

“How would you test that the system never oversells?”

Three ways. A concurrency test that fires thousands of parallel hold requests at the same seats against a real database, and checks that every seat ends up with at most one owner. A load test before each big on-sale, at more than the expected peak, through the waiting room. And an invariant check in production: a job that continuously verifies that no seat appears in two bookings and that sold counts never exceed capacity, alerting instantly if they do.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsNever oversell; survive the spike; fair
  2. 02
    5 to 10: numbers, API, dataSmall data, huge contention; seats with status
  3. 03
    10 to 25: correctnessHold then pay; conditional update; expiry in the row
  4. 04
    25 to 35: the crowdWaiting room with tokens; cached seat map
  5. 05
    35 to 45: the restPayment edge cases, bots, failures

On the clock: five minutes of requirements, with the invariant written at the top: a seat is sold at most once. Five minutes for numbers, the API and the seats table, showing that the problem is contention, not size.

Fifteen minutes on correctness: holds then payment, a single conditional update to claim seats, all or nothing, and expiry stored in the data so it survives crashes.

Ten minutes on the crowd: a waiting room that admits buyers at a safe rate with signed tokens, and a cached seat map that may be stale because the hold is the real check. And the last ten on payment edge cases, bots and failures. If you keep the invariant in the database and the crowd outside the shop, you have the answer interviewers want.

The race condition at the heart of this question is easy to describe and easy to get subtly wrong when an interviewer pushes. Practicing out loud makes the explanation crisp. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson fifteen.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.