Sell a limited inventory fairly: holds, double-booking, flash-sale traffic and payments.
“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 check | Why it matters |
|---|---|
| Naming the invariant | A 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-waving | Two 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 money | A 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 sale | A 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 consistent | The seat map can be stale. The hold and the sale cannot. Putting the line in the right place is the whole design. |
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.
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.| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | Reserved seats or general admission, hold time, hotel or event or both, flash-sale size, overbooking policy. |
| 2. Estimate | 3 | Reads versus writes, the flash-sale spike, hold attempts per second against what one database can do. |
| 3. API and data | 5 | Seat map, hold, book with an idempotency key. Seats, holds, bookings and hotel inventory tables. |
| 4. High-level design | 8 | CDN read path, waiting room, booking service, inventory store, payment, search on the side. |
| 5. Deep dives | 15 | No double booking, then holds and expiry, then the flash sale, then consistency and hotels. |
| 6. Scale and failures | 7 | Payment works but confirm fails, the hot shard, region loss, bots and refunds. |
| 7. Wrap up | 3 | Recap, where strong consistency lives, what you would build next. |
| Ask | Why you ask it | Typical answer | How 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. |
| Assumption | Value |
|---|---|
| Normal day | 20 million visits, 10 page views each, 1 million bookings |
| Peak versus average | 3 times for views, 10 times for bookings |
| On-sale event | 50,000 seats, 1,000,000 people waiting, 2 seats per order on average |
| Seat map poll | every 5 seconds per waiting user |
| Seat map size | 2 bits per seat (free, held, sold) |
| CDN cache life, edge sites | 2 seconds, 100 edge sites |
| One inventory shard | about 5,000 hold transactions per second (assumption) |
| Hold time | 8 minutes (480 seconds) |
| Hotels | 500,000 properties, 8 room types, 365 days ahead, 40 bytes per row |
| What | Maths | Result |
|---|---|---|
| Normal page views per second | 20,000,000 × 10 ÷ 86,400 | about 2,300 per second (7,000 at a 3× peak) |
| Normal bookings per second | 1,000,000 ÷ 86,400 | about 12 per second (about 120 at a 10× peak) |
| Seat-map polling during the on-sale | 1,000,000 users ÷ 5 seconds | 200,000 requests per second |
| Size of one seat map | 50,000 seats × 2 bits ÷ 8 | 12.5 KB |
| Egress from the CDN for that | 200,000 × 12.5 KB | 2.5 GB per second, about 20 Gbit per second |
| Origin load behind the CDN | 100 edge sites ÷ 2 second cache life | about 50 requests per second |
| Hold attempts if everyone clicks within 10 seconds | 1,000,000 ÷ 10 s, against 5,000 per second | 100,000 per second, 20 times too many |
| Safe admit rate (half capacity, 2 attempts per user) | 5,000 × 50% ÷ 2 | 1,250 users per second |
| Time to let everyone in | 1,000,000 ÷ 1,250 | 800 seconds, about 13 minutes |
| Most holds in flight | 50,000 seats ÷ 2 per order | 25,000 holds (inventory caps it) |
| Expiries if half the buyers walk away | 12,500 holds ÷ 480 seconds | about 26 per second |
| Seat rows for 10,000 live events | 50,000,000 seats × 100 bytes | 5 GB |
| Bookings stored per year | 1,000,000 × 300 bytes × 365 | about 110 GB (330 GB with 3 copies) |
| Hotel inventory rows | 500,000 × 8 × 365 = 1.46 billion rows × 40 bytes | about 58 GB (175 GB with 3 copies) |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| GET | /v1/events/{id}/seats?section=B | none | 200 { 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 header | 201 { 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} | none | 204 | The buyer gives up. Seats go back at once. Idempotent. |
| GET | /v1/hotels/{id}/availability?from=2026-07-01&to=2026-07-05 | none | 200 { roomTypes: [{ type, left, price }] } | Reads a cache or replica. A hint, not a promise. |
| POST | /v1/reservations | { hotelId, roomType, from, to, paymentMethodId } + Idempotency-Key | 201 { reservationId } or 409 (sold out for some night) | Decrements every night in one transaction. Fails as a whole if any night has none left. |
| seats (sharded by event id) | Type | Why it is there |
|---|---|---|
| event_id, seat_id | ids | The key. One row per physical seat. |
| status | enum | AVAILABLE, HELD or SOLD. The compare-and-set looks at this. |
| hold_id, hold_expires_at | id, timestamp | Who holds it and until when. An expired hold counts as free. |
| booking_id | id | Set when sold. Unique per (event_id, seat_id) for confirmed sales: a second line of defence. |
| version | int | Bumped on every change. Lets caches and clients tell old maps from new. |
| holds and bookings | Key fields | Why |
|---|---|---|
| holds | hold_id, user_id, event_id, seat_ids, expires_at, state | One row per hold, so we can expire and release a group together. |
| bookings | booking_id, user_id, hold_id, status, payment_ref, idempotency_key (unique) | The unique key makes a retried booking return the same row. |
| hotel_inventory | hotel_id, room_type, night, total, booked (CHECK booked <= total + overbook_limit) | A count per room type per night. The CHECK is the last guard. |
| reservations | reservation_id, hotel_id, room_type, from, to, status | Spans many nights, so many inventory rows change together. |
-- 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
| Component | What it does |
|---|---|
| CDN and edge | Serves the seat map and static pages. A 2-second cache life turns 200,000 requests a second into about 50 at the origin. |
| Waiting room | Holds users in a virtual line and admits them at a fixed rate, each with a signed admission cookie. Protects the booking path. |
| Booking service | Stateless. Runs the hold transaction, confirms after payment, releases on cancel. The only writer of seat status. |
| Inventory shard | A strongly consistent primary per event (with replicas for failover). Holds the seats, holds and bookings tables. |
| Expiry sweeper | Marks old holds as free and publishes the change. Not needed for correctness, because the hold query already treats an expired hold as free. |
| Payment service | Authorises the card, captures after the seats are confirmed, voids or refunds on failure. Each call has an idempotency key. |
| Outbox and queue | The booking row and its event are written in one transaction. The event feeds caches, search, notifications and the ledger. |
| Seat-map cache and search | Rebuilt from events. Eventually consistent, and fine to be a moment behind. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Check, then write | SELECT 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 lock | SELECT ... 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-set | One 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 behind | Take 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. |
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.
| Isolation level and this statement | What happens |
|---|---|
| Read committed, conditional UPDATE | Enough. The row is locked by the UPDATE, so the second writer waits, then re-checks the WHERE and changes nothing. |
| Read committed, check then write | Not enough. Both read AVAILABLE. This is the race. |
| Serializable, check then write | Safe, but one of the two transactions is aborted with an error and must retry. Correct and slower. |
| Hotel date range | Decrement every night in one transaction under CHECK (booked <= total + limit). A partial failure rolls the whole stay back. |
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Hold forever until the buyer acts | No 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 write | Store 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 hold | A 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 hold | Charge 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. |
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 wrong | State left behind | What the design does |
|---|---|---|
| Buyer pays after the hold expired and the seat was sold to someone else | Authorisation exists, seat is gone | Confirm 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 free | Authorisation exists, seat free | Confirm 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 booking | Saga compensation: void the authorisation. A reconciliation job finds any that were missed. |
| Confirm succeeds, capture fails | Seat sold, money not taken | Retry capture with the same idempotency key. If it keeps failing, release the seat and cancel the booking. |
| Sweeper frees a seat while the buyer confirms | Race on one row | Both are conditional updates on the same row, so one wins. A buyer who loses gets a clear message and a void. |
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
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.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Autoscale and hope | Add 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 reject | Return 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-registration | Collect 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. |
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.
| Layer | What it protects | How |
|---|---|---|
| CDN and seat-map cache | The origin from read load | 2-second cache of a 12.5 KB bitmap. 200,000 requests a second become about 50. |
| Waiting room | The booking path from the spike | Admit 1,250 a second. Position and estimated wait shown to the user. |
| Admission cookie | Fairness and the line itself | Signed, bound to an account, expires in minutes, one live cookie per account. |
| Per-user and per-device limits | Against hoarding | At most N seats per order and per person per event. |
| Bot defence | Against machines beating humans | Challenges at the door, verified accounts, behaviour checks, throttling by device and network. |
| Hot-row relief | The best seats are contended | Shard 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 shedding | The booking path when all else fails | Drop search, recommendations and analytics first. Keep hold and confirm. |
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”.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One global database, everyone writes to it | A 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 elsewhere | Each 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 resolution | Any 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 region | Give 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. |
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 topic | How the design treats it |
|---|---|
| Inventory shape | One row per (hotel, room type, night) with total and booked. Searching a stay reads every night in the range. |
| Booking a stay | Increment booked for every night in one transaction under a CHECK. If any night is full, the whole stay fails. |
| Overbooking | A 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 rates | Price 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 refunds | Cancel decrements booked for every night and applies the policy's refund. Same idempotent saga as a purchase. |
| Outside systems | Channel managers and partner sites sync by events and a nightly reconciliation. Expect drift, detect it, and fix it with a clear winner rule. |
| Time zones | Nights are dates in the hotel's own time zone. Store the property's zone, and never compare local dates across zones. |
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.
| Bottleneck | Fix |
|---|---|
| The inventory shard for the hot event | Admit 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 click | Offer 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 browsers | A 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 slow | Timeouts, 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 storms | Expiry 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 properties | A 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 itself | It 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. |
| Failure | How the design copes |
|---|---|
| Payment is authorised but the confirm fails | Void 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 capture | The 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 fails | Fail 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 down | Promote 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 sold | The 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 delayed | Maps and search lag, and the sale is unaffected. Alert on lag, and rebuild a map from the database if the lag grows. |
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.
| Decision | What we gain | What it costs |
|---|---|---|
| A single writer per event | No cross-region conflicts and a simple invariant. | Far-away buyers pay a round trip, and failover needs care. |
| A stale, cached seat map | The 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 room | Fairness and a flat, safe load on the database. | A wait for users, and one more component that must itself scale. |
| Short holds | Seats return to sale quickly. | Slow payers lose their seats, so refunds and support contacts go up. |
| Authorise, confirm, then capture | We never take money for a seat we cannot give. | More steps and compensation paths to test. |
| A deliberate overbooking limit for hotels | Higher occupancy when guests cancel or do not show. | Sometimes a guest must be relocated, and that costs money and goodwill. |
The core of the question. Say the invariant, then show the mechanism that enforces it.
Multi-step failures. Say what state is left behind and how you recover.
Scale, fairness and bots. Show that you know where the real bottleneck is.
Where strong consistency lives and where it does not. Hotels are the same problem with ranges.
What a senior engineer adds: testing, monitoring and cleanup.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| General admission, no seat numbers | Inventory 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 transfer | A 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-served | Drop 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 events | Collect 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 writes | Pre-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 demand | A 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 purchases | More 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 events | A 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. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts 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. |
| Estimation | No 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. |
| Correctness | Check 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. |
| Failures | Only 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. |
| Scale | Autoscale 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-offs | One 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. |
| Mistake | Do this instead |
|---|---|
| Check the seat, then write it in a second step | One conditional UPDATE that checks and writes together, and verify the changed-row count. |
| Trusting the cached seat map to decide a booking | The map is a hint. The hold on the primary is the decision. |
| Holds with no expiry | Store hold_expires_at, treat an expired hold as free, and run a sweeper only for tidiness. |
| Charging the card before confirming the seat | Authorise, confirm, then capture, and void if the confirm fails. |
| Holding a database transaction open while waiting for the payment provider | Keep transactions to one short statement. Do the slow call outside, and use idempotency keys. |
| Solving the flash sale by autoscaling | Meter 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 seat | Use 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 clicked | Hold them in one statement and sort the ids, so deadlocks cannot happen. |
The authorise, capture, void and refund flow, and idempotent money movement.
Why the hold and the confirm must be all-or-nothing.
Pessimistic and optimistic locking, and what a conditional update relies on.
Which level the hold needs, and where check-then-write breaks.
Making a retried booking or payment safe.
The payment and confirm steps with compensation.
The idea behind a waiting room that protects the booking path.
Per-user and per-device limits at the door.