A ticket booking system sells a fixed, tiny inventory (one seat can be sold exactly once) to a crowd that can be thousands of times larger than the inventory. On a normal day the load is modest. When a stadium tour goes on sale, a million people hit "buy" in the same minute for 50,000 seats. The interesting problems are therefore about correctness under contention, not about raw data size: never sell a seat twice, let people hold a seat while they pay, survive the stampede, and take money safely even when payments time out. This lesson walks the full eight-step interview framework and explains why a relational database with transactions is the right core here.
Detailed Notes
How to use this lesson
Treat this as a 45-minute interview. All numbers are assumptions you state out loud, not facts about any real company. What the interviewer checks is that your numbers drive your decisions, and that you separate two very different worlds: a quiet normal day, and a flash sale where one event receives most of the traffic.
Step 1: Clarify Requirements
Do not start with boxes. Ask what is being sold and what "correct" means. A good opening: "Is this reserved seating or general admission, and what must never happen? I assume the one thing we must never do is sell the same seat twice."
Functional requirements
Users can search and browse events by city, date, artist or category.
Users can open an event and see a seat map showing which seats are available.
A user can select seats and hold them for a short time (10 minutes) while they pay. A seat hold is a temporary reservation: nobody else can buy that seat, but it is not sold yet.
A user can pay and receive a confirmed booking with tickets.
If the user does not pay in time, the hold expires and the seats become available again.
Extended requirements
Mention these, then ask whether to include them. Do not design them unless asked.
Cancellation and refunds.
Waitlists for sold-out events.
Dynamic pricing that changes prices with demand.
Ticket transfer or resale between users.
Non-functional requirements
Strong consistency for seats: a seat must never be sold twice. This is the number one requirement and it beats availability for the booking operation. If the system is unsure, it must refuse the booking rather than guess.
Availability for browsing: search and event pages should stay up (99.99%) even if booking is degraded. Browse data can be slightly stale.
Low latency: browse p99 under 200 ms; a hold request p99 under 500 ms. (p99 means 99 of 100 requests are faster than that.)
Scalability for flash sales: absorb 1 million users arriving within a minute for one event with 50,000 seats, without falling over and without losing fairness.
Fairness: roughly first come, first served, with bots limited.
Durability: once we confirm a booking and take money, it must never be lost.
Hold timing: a hold lasts 10 minutes and expires reliably.
Consistency decision. Different operations get different guarantees. Browsing: eventual consistency is fine (a seat map that is 2 seconds old is acceptable). Holding and booking: strong consistency, because a stale answer means a double sale. Say this early.
Out of scope
Choosing seats by 3D venue rendering, ticket PDF/QR generation, resale marketplace, tax rules and fraud scoring models. We mention bots and abuse but do not build a full detection pipeline.
Interview tip. Many candidates say "NoSQL for scale" in the first minute. Here the hard part is not scale of data; it is that two people race for one seat. Name that race explicitly and the interviewer knows you understand the problem.
Step 2: Estimate Scale
Back-of-the-envelope estimation means rough calculations to find out which part of the system will be hard. We do it twice: once for a normal day and once for a flash sale. The contrast is the point of this lesson.
Assumptions to state
10 million daily active users on the platform; each views about 10 pages a day (search, event page, seat map).
20 million tickets sold per month, an average of 2 tickets per order, so about 10 million orders a month.
100,000 events a year, averaging 10,000 seats each (a club has 500 seats, a stadium 50,000).
On average only 1 hold in 10 turns into a purchase (people browse, abandon, or lose the race).
A day has about 100,000 seconds. Peak factor for normal days: 3.
Flash sale: 1 million users arrive within 1 minute for one event with 50,000 seats.
Normal-day traffic
text
Page views per day = 10M users x 10 = 100M
Browse reads per second = 100M / 100,000 s = 1,000 / s
Peak browse reads = 1,000 x 3 = 3,000 / s
Tickets per day = 20M / 30 = about 700K
Tickets per second = 700K / 100,000 s = about 7 / s
Hold attempts per second = 7 x 10 (1 in 10 buys) = about 70 / s
Peak hold attempts = 70 x 3 = about 200 / s
So what? A normal day is a read-heavy, low-write system: about 150 reads for every ticket sold. Two hundred holds per second is trivial for one relational database. The normal day is not why this design is hard.
Flash-sale traffic
text
Arrivals per second = 1M users / 60 s = about 17K / s
Competition = 1M users / 50K seats = 20 users per seat
Hold attempts if everyone clicks once in that minute = about 17K / s on ONE event
Seventeen thousand writes per second aimed at the same 50,000 rows is about 6 times the normal-day browse peak and nearly 100 times the normal peak hold rate (200/s), and every request needs a lock on rows that others want too. A single database would spend its time waiting on locks, and 95% of those users will lose anyway. This is the whole motivation for a virtual waiting room (a queue that lets users in at a controlled rate), designed in Step 6.
Reservation QPS with a waiting room
text
Admit rate = 100 users / s (chosen, see Step 6)
Time to admit in 10 minutes = 100 x 600 s = 60K users
Shoppers active at once = 100 users/s x 300 s stay = about 30K
Hold attempts after queue = 100 users/s x 3 tries = about 300 / s
Reduction = 17K / 300 = about 50x
So what? The waiting room turns an unmanageable 17K/s spike into about 300 writes per second, which a single database partition handles easily. We throttle in front of the database instead of buying a database 50 times bigger. A rough sanity check: 60K admitted users, 40% of whom buy 2 seats, is 48K seats, about one event's inventory in around 10 minutes.
Ticketmaster: Normal Day vs Flash SaleEstimation
Request load
1Musers for 50K seats
given
17K/sarrivals
÷ 60 s
20users per seat
÷ 50K seats
100/sadmitted by waiting room
chosen rate
~300/sholds hit the database
× 3 tries each
Seat storage
~1 TB
1B seat rows/year × 100 B = 100 GB/yr; plus 60 GB/yr orders; 5 years
Size is small; partition by event for contention, not capacity
Normal-day traffic
3K reads/s
100M page views ÷ 100,000 s = 1,000/s × 3 peak; about 200 holds/s at peak
Replicas and a cache; one primary is enough
Flash-sale reservations
17K → 300/s
1M users in 1 minute vs 100 admitted per second × 3 tries
Use a waiting room: about 50x fewer writes
Key point. The hard part is the flash-sale spike on one event, not data size. Throttle the spike; storage is only about 1 TB.
A normal day needs about 200 holds per second. A flash sale aims 17,000 per second at one event until a waiting room throttles it.
Storage
text
Seat rows per year = 100K events x 10K seats = 1 billion
Seat storage per year = 1B x 100 bytes = 100 GB
Five years = 500 GB
Orders per year = 10M x 12 = 120M
Orders + payments = 120M x 500 bytes = 60 GB / year
Five years = 300 GB
Total = about 800 GB, call it 1 TB
So what? A terabyte is small. We do not need to partition because of size. We partition by event for two other reasons: to spread write contention, and to limit the blast radius (how much breaks when one machine fails) of a hot event. Interviewers love this: the storage number is small and you say so.
Seat map size and real-time updates
text
Seat map snapshot = 50K seats x 1 byte status = 50 KB
Seat changes during flash = about 300 / s (holds, releases, bookings)
One batched update per second = 300 x 10 bytes = about 3 KB
Push traffic to viewers = 30K viewers x 3 KB / s = about 90 MB/s
So what? One 50 KB snapshot is cacheable at a CDN, and deltas are small. But pushing every change to every viewer costs about 90 MB/s, so we batch changes once per second, and send each viewer only the section they are looking at.
Interview tip. Always finish an estimate with "so what". Here: "normal load is easy, flash load is a lock-contention problem, storage is small, so I partition for contention rather than size."
Step 3: Define the APIs
An API is the contract between clients and the service. Pay attention to the order of operations: browse, hold, pay. Each step has a different consistency need.
Browse and search
http
GET /v1/events?city=Mumbai&date=2026-12-01&q=coldplay&cursor=...&limit=20
GET /v1/events/{event_id}
GET /v1/events/{event_id}/seats?section=A
These are cacheable, read-only and paginated with a cursor (an opaque token that marks where the next page starts, which stays stable when new rows arrive). The seat endpoint returns seat id, section, row, number, price and status.
Hold seats
http
POST /v1/events/{event_id}/holds
Authorization: Bearer <token>
Queue-Pass: <signed pass from the waiting room>
Content-Type: application/json
{
"seat_ids": ["A-12-5", "A-12-6"]
}
201 Created: payment succeeded and seats are booked.
402 Payment Required: the payment was declined; the hold stays until it expires so the user can retry another card.
410 Gone: the hold expired before payment completed.
202 Accepted: the payment provider has not answered yet; poll GET /v1/orders/{id} for the final status.
Design decision: idempotency. An idempotent operation gives the same result if repeated. A user double-clicks "Pay" or the phone retries after a timeout, and without protection they are charged twice. The client sends a unique Idempotency-Key; the server stores the first result under that key and returns it again for any repeat.
Release
http
DELETE /v1/events/{event_id}/holds/{hold_id} # user gives the seats back
How the API shapes the architecture
Browsing is high volume, read-only and tolerant of staleness: it gets caches and read replicas. Holding and ordering are low volume (after throttling), must be strongly consistent and need transactions: they go to the primary database directly. Two services with two different scaling plans.
Step 4: Define the Data Model
Start from access patterns:
List seats of an event with status (the seat map).
Hold N seats atomically: all or none, only if they are free.
Confirm a booking: move held seats to booked and record the order together.
Find expired holds and release them.
Look up an order by id or by user.
Patterns 2 and 3 touch several rows and must succeed or fail as one unit. That is a transaction, and it is the main reason for the database choice below.
Fields and why each exists
For the seats table:
event_id + seat_id: the composite primary key. event_id is also the partition key, so all seats of one event live together and a hold transaction stays on one machine.
status: available, held or booked. The state machine in Step 6.
held_by: the user holding the seat. Used to check "is this hold really mine" at payment.
hold_expires_at: when the hold stops counting. The key to expiry without a race.
booking_id (order id): which order owns the seat once booked.
version: a number that increases on every change. It supports optimistic concurrency (Step 6).
price_cents, section, row_label, seat_number: what the user sees and pays.
For orders and payments: status tracks the saga (pending, confirmed, failed, refunded), and a uniqueidempotency_key column makes duplicate payment attempts impossible at the database level.
The Data ModelData model
eventsRelational DB
PKevent_idbigint
partition key for all event data
IDXnamevarchar
also copied to the search index
venue_idbigint
IDXstarts_attimestamp
on_sale_attimestamp
when the waiting room opens
statusscheduled | on_sale | sold_out
Read mostly; cached and served from replicas.
seatsRelational DB (primary)
PKevent_idbigint
partition key
PKseat_idvarchar(12)
e.g. A-12-5
statusavailable | held | booked
FKheld_bybigint
user holding the seat
IDXhold_expires_attimestamp
expired holds count as available
FKbooking_idbigint
set when booked
versionint
bumped on every change
price_centsint
The contested table. All changes use conditional UPDATEs.
ordersRelational DB
PKorder_idbigint
IDXuser_idbigint
'my tickets' lookup
FKevent_idbigint
statuspending | confirmed | failed | refunded
saga state
total_centsint
UQidempotency_keyuuid
blocks double charge
Written as pending before the card is charged.
paymentsRelational DB
PKpayment_idbigint
FKorder_idbigint
UQprovider_refvarchar
PSP transaction id
amount_centsint
statuspending | succeeded | failed | refunded
Used by reconciliation against the provider's records.
seats.event_idevents.event_id· many to one
seats.booking_idorders.order_id· many to one
payments.order_idorders.order_id· many to one
Key point. event_id is the partition key, so every hold or booking transaction stays on one shard.
Seats are keyed by (event_id, seat_id); orders and payments carry unique idempotency keys.
Which database?
Reason from requirements, not from fashion:
A hold touches several rows atomically, and a booking touches seats, the order and the payment record together. That needs ACID transactions (atomic, consistent, isolated, durable).
The system needs row-level locking or conditional updates to stop two buyers from taking one seat.
Data is relational and small (about 1 TB): events have seats, orders have payments.
Queries are simple, but the correctness requirement is strict.
So the source of truth is a relational database such as PostgreSQL, partitioned by event_id. A NoSQL store can also do conditional writes on a single item, but multi-seat atomic holds and the order record together are awkward there. Search is the exception: a search index (an inverted index, a structure that maps each word to the events containing it) is a separate read-optimized copy for text queries. It is not the source of truth.
Relational (PostgreSQL)
Key-value / NoSQL
Multi-seat atomic hold
One transaction
Transaction support is limited or costly
Prevent double booking
Row lock or conditional UPDATE
Conditional write per item
Ad-hoc queries (reports, support)
Easy
Hard
Scaling
Partition by event, 1 TB is small
Scales out easily
Trade-off thinking. NoSQL's edge is horizontal scale, but our data is only about 1 TB and the load is throttled to about 300 writes per second. We do not need that scale, and we do need transactions. Choose the tool for the constraint that actually binds.
Step 5: High-Level Design
The golden rule: separate browsing from booking. They have opposite needs: browse is read-heavy and stale-tolerant, booking is write-sensitive and must be exact.
Browse Path and Booking PathArchitecture
Key point. Two paths, two consistency levels: eventual for browsing, strong for booking.
Browsing is read-heavy and tolerates stale data. Booking is write-sensitive and uses the primary database.
Components and why each exists
API gateway / load balancer: entry point for TLS, authentication, rate limiting and routing. A load balancer spreads requests across identical servers and skips failed ones.
Browse service (read path): stateless service for search and event pages. It reads from a cache first, then from read replicas (copies of the database that serve reads and lag the primary slightly).
Cache: in-memory copy of hot events and seat snapshots so most browse requests never reach the database.
Booking service (write path): runs holds and orders. It is the only component that changes seat state.
Seat database (primary): the single source of truth for seat state, partitioned by event_id.
Payment service: wraps the external payment service provider (PSP), a company that charges cards. It adds idempotency and retries.
Searching by text is done on a separate search index fed from the database, so a heavy query never competes with a booking transaction.
Hold Seats, Then PayRequest flow
BrowserBooking serviceSeat databasePaymentprovider1POST /holds [A-12-5, A-12-6]2conditional UPDATEonly if available or hold expired32 rows updated4201 hold_id, expires_at5POST /orders +Idempotency-Key6charge (idempotent)order saved as pending first7payment succeeded8held to bookedonly if hold still mine9201 order confirmed
The hold is one conditional update. Payment happens only after the hold exists.
Request flow
Browse.
Client calls GET /v1/events/{id}/seats.
The browse service returns the cached snapshot; on a miss it reads a replica and fills the cache.
After that, seat changes arrive by push (Step 6.5).
Hold and book.
Client sends POST /holds with a queue pass.
The booking service runs one transaction that flips the seats from available to held and sets an expiry.
Client sends POST /orders with an idempotency key.
The payment service charges the card.
On success, the booking service flips seats from held to booked and stores the order.
Step 6: Deep Dive
Interviewers go straight to the hard part: "Two users click the last seat at the same instant. What happens?" We spend the time on the seat state machine, double-booking prevention, the waiting room, payment safety and real-time updates.
6.1 The seat state machine
Every seat is in exactly one of three states, and only certain transitions are legal.
Seat State MachineArchitecture
Availablefree to holdHeld10 minute TTLBookedpayment confirmedReleasedexpired or failedholdpayment okexpire / failreset
Key point. Every transition is a conditional UPDATE on the current state; illegal jumps match zero rows.
Three states. Expiry is part of the row, so an expired hold counts as available even before the sweeper runs.
Available to held: a user holds the seat. Sets held_by and hold_expires_at = now + 10 minutes.
Held to booked: payment succeeded and the same user still owns an unexpired hold.
Held to available: the user released it, payment failed, or the hold expired.
Booked is terminal in this design. A refund or cancellation is an extended feature that moves the seat back to available through its own audited path.
Why a hold at all? Without it, a user would pick seats, spend three minutes typing card details and then learn the seat was sold. Without a time limit, a user who walks away would block seats forever. A hold with a TTL (time to live, a timer after which something expires) balances both.
6.2 How do we expire holds without a race?
The naive design is a background job that scans for expired holds and resets them. It has two flaws: the job may run late (the seat stays blocked and looks unavailable), and it can race with a payment that is completing at the same moment.
The robust approach: expiry is a fact stored in the row, not an event someone must process. Every query treats a held seat whose hold_expires_at is in the past as available:
text
A seat is takeable when:
status = 'available'
OR (status = 'held' AND hold_expires_at < now())
So even if the cleanup job is late or down, correctness is intact: an expired hold simply stops blocking anyone. A sweeper background job (a periodic cleanup job) still resets expired rows to available and publishes the update so seat maps refresh, but the sweeper only affects freshness and tidiness, never correctness.
Optionally a cache such as Redis holds a TTL key per hold as a fast path for the UI countdown, but the database row remains the authority.
Interview tip. If you say "I'll set a Redis key with a TTL and treat expiry as the lock", the interviewer will ask what happens when Redis loses the key or the clocks disagree. Keep the authoritative timer in the database.
6.3 Preventing double booking
This is the heart of the interview. Two requests try to hold seat A-12-5 at the same moment. Both read "available". Both try to write "held". Without protection both succeed: that is a race condition (the outcome depends on who gets there first). We need mutual exclusion on that seat. Three standard techniques:
Three Ways to Stop a Double BookingComparison
Row lock
SELECT ... FOR UPDATE
1
Begin transaction
lock seat rows, sorted by id
2
Check status
available or expired hold?
3
Update to held
set holder and expiry
4
Commit
others waiting now proceed
Easy to reason about
Good for multi-step logic
Waiters queue up under contention
Deadlock risk if lock order differs
Use when the decision needs several reads
Version column
optimistic concurrency
1
Read seat and version
no lock taken
2
Decide in the application
seat looks free
3
UPDATE ... WHERE version = v
writes only if unchanged
4
0 rows updated?
someone won; retry or fail
No locks held while thinking
Great when conflicts are rare
Heavy retries in a flash sale
Two round trips minimum
Good for low-contention data
Conditional UPDATE
check and change at once
1
Send one UPDATE
WHERE status is available
2
Database serializes per row
only one writer matches
3
Compare rows updated
must equal seats requested
4
Mismatch? Roll back
return 409, all or nothing
One round trip
Locks held for microseconds
Losers fail fast
Logic must fit in one statement
Recommended default for seat holds
Key point. For hot seats, check and change in one conditional UPDATE and let the loser fail fast.
All three are correct. They differ in round trips and in behaviour under heavy contention.
Option A: pessimistic locking with a row lock. Inside a transaction, run SELECT ... FOR UPDATE on the seat rows. The database locks those rows: any other transaction asking for them waits until the first commits or rolls back. Then check the status and update.
text
BEGIN;
SELECT * FROM seats
WHERE event_id = :e AND seat_id IN (:seats)
ORDER BY seat_id -- same order everywhere avoids deadlock
FOR UPDATE;
-- if any row is not takeable: ROLLBACK, return 409
UPDATE seats SET status = 'held', held_by = :u,
hold_expires_at = now() + interval '10 minutes'
WHERE event_id = :e AND seat_id IN (:seats);
COMMIT;
Always lock rows in the same order (sorted by seat id), otherwise two buyers who each want seats 5 and 6 in opposite orders can deadlock (each waits for the other forever; the database detects it and aborts one).
Option B: optimistic concurrency with a version column. Read the seat and its version without locking, decide, then write only if the version has not changed. If someone else changed it, the update touches zero rows and we retry or fail.
text
UPDATE seats
SET status = 'held', held_by = :u, version = version + 1, ...
WHERE event_id = :e AND seat_id = :s AND version = :version_we_read;
-- rows updated = 0 -> somebody got there first
Option C: single conditional UPDATE (compare-and-set). Skip the read. Put the availability check inside the update, so the database makes the check and the change in one atomic step.
text
UPDATE seats
SET status = 'held', held_by = :u, version = version + 1,
hold_expires_at = now() + interval '10 minutes'
WHERE event_id = :e AND seat_id IN (:seats)
AND (status = 'available'
OR (status = 'held' AND hold_expires_at < now()));
-- rows updated must equal the number of seats requested;
-- otherwise ROLLBACK and return 409 (all or nothing)
The database serializes writers on each row, so only one concurrent update can match the WHERE. The loser sees fewer rows updated than requested and rolls back. This needs one round trip, holds locks for a very short time and is our recommended default.
Row lock (A)
Version column (B)
Conditional UPDATE (C)
Round trips
2 or more
2 or more, plus retries
1
Behaviour under heavy contention
Waiters queue, latency grows
Many retries, wasted work
Losers fail fast
Complexity
Deadlock ordering
Retry logic
Simplest
Best when
Complex multi-step logic inside the transaction
Conflicts are rare
Hot seats, simple state change
Which to pick. In a flash sale, contention is very high, so optimistic retries (B) waste work and pessimistic waiting (A) builds latency. A conditional UPDATE (C) is cheap and fails fast. Use A when a transaction must read and reason about several rows before deciding (for example "best available seats together" with FOR UPDATE SKIP LOCKED, which skips seats someone else has locked instead of waiting). B suits low-contention edits, such as a user editing profile data.
Do not solve this with an application-level lock in a single server's memory: with many booking servers it protects nothing. Do not use a distributed lock as the only guard either; it can expire mid-operation. The database check is the final safety net.
Isolation level. At the default READ COMMITTED, the conditional UPDATE is already safe because the row is re-checked after the other transaction commits. Raising to SERIALIZABLE is unnecessary and slower for this pattern.
6.4 The virtual waiting room
A virtual waiting room is a queue in front of the booking system. Users who arrive first receive a position and wait; the system lets them in at a rate the backend can handle.
Key point. Throttle before the database: the backend sees admitted users only, never the full crowd.
A million users queue cheaply at the edge. The admitter releases 100 per second with a signed pass.
How it works:
When the sale page loads, each user gets a queue ticket with a random number drawn at arrival (or a position in order of arrival). The waiting page is a static page served from a CDN, so a million users cost almost nothing.
The client polls the waiting room every few seconds (or receives a push) for its status: "you are number 48,210".
An admitter moves users from the queue at 100 per second, issuing each a signed pass: a token (for example a JWT, signed with a server secret and containing user id, event id and an expiry) that the booking service verifies without a database lookup.
Booking APIs reject requests without a valid pass (403). A pass is valid for, say, 10 minutes, which fits the hold TTL.
The queue itself lives in an in-memory ordered store (a sorted set keyed by arrival time or random draw) because it must absorb 17K inserts per second.
Choosing the admit rate. Pick it from backend capacity and shopping time: 100 users per second with about 5 minutes of dwell time gives 30K shoppers at once and about 300 holds per second. Adjust it live: if the database p99 rises, slow admission; if it is idle and seats remain, speed up. Admission control is the pressure valve for the whole system.
Fairness. Strict first-come, first-served rewards fast connections and bots. Many systems instead give everyone who arrives in the first minute a random position, so refreshing frantically does not help. State this choice and its trade-off: random draw is fairer to slow connections, FIFO feels more intuitive.
Trade-off thinking. The waiting room protects the database but adds a component and a poor-feeling wait. The alternative is scaling every tier for a spike that lasts minutes, which is far more expensive and still cannot make 1 million users succeed for 50,000 seats. Throttling is cheaper and more honest.
6.5 Seat map browsing and real-time updates
Browsing is where the 17K per second arrivals land (or, with a waiting room, where users view the event before the sale).
Cache the static part (venue layout, section shapes, prices) at a CDN. It rarely changes.
Cache the dynamic part (seat status) as a snapshot of about 50 KB per event in an in-memory cache with a 1 to 2 second TTL, built from a read replica. Thirty thousand viewers share one snapshot rather than each querying the database.
Push deltas. After the snapshot, the client keeps a WebSocket (a long-lived two-way connection) or server-sent events (a one-way server push stream) open. When a seat changes, the booking service publishes an event to a message queue (a durable buffer for messages); push servers subscribe per event and per section and send a batched update once per second. About 3 KB per second per viewer.
Eventual consistency is acceptable here. The map may show a seat as free that was just taken. The hold request fails with 409 and the UI refreshes it. The map is advice, the database is the law.
Reconnect rule. If a client misses updates, it refetches the snapshot, then resumes deltas using a version number.
Browse at normal scale: put replicas behind the browse service and cache event pages for about 60 seconds. Replica lag is a small number of seconds, which is acceptable for search and listings but never for the hold decision, which always uses the primary.
6.6 Payment flow: idempotency and compensation
Charging a card is an external call that can be slow, can fail, or can succeed while our server never hears back. We cannot put one database transaction around "our database and the card network". Instead we use a saga: a chain of local steps where each step has a compensation (an action that undoes it) if a later step fails.
text
Step 1 Hold seats compensation: release the hold
Step 2 Create order (pending) compensation: mark order failed
Step 3 Charge the card compensation: refund the charge
Step 4 Mark seats booked, (point of no return)
order confirmed
Rules that keep it safe:
Idempotency key everywhere. The order carries the client's key and the call to the PSP carries a key derived from the order id, so any retry of "charge" returns the same result and never charges twice. A unique index on the key makes the database enforce it.
Persist intent before acting. Write the order as pending before calling the PSP. If our server crashes mid-call, a recovery job finds pending orders and asks the PSP what happened.
Extend the hold when payment starts. When the user submits payment, move the hold expiry forward by 2 to 3 minutes so a slow bank page cannot lose the seat mid-charge.
Confirm with a conditional update. Final step:
text
UPDATE seats SET status = 'booked', booking_id = :o, version = version + 1
WHERE event_id = :e AND seat_id IN (:seats)
AND status = 'held' AND held_by = :u;
-- rows updated must equal seats in the order
Webhooks and reconciliation. A webhook is a callback the PSP sends to us when a payment finishes. We accept it (idempotently) and a nightly reconciliation job compares PSP records with our orders to catch anything missed.
6.7 Failure races you must discuss
Payment timeout. We called the PSP and got no answer. We do not know whether the card was charged. Mark the order pending, return 202, and ask the PSP by idempotency key. If charged, confirm; if not, release the hold.
Hold expires while payment is in flight. The card is charged after the hold ended and another user took the seat. The confirm update matches zero rows. The compensation runs automatically: refund and tell the user. Extending the hold at payment start makes this rare, but the refund path must exist.
Double click or retry. The same idempotency key returns the stored result. No second charge.
Server crash after charge, before confirm. The pending order and the PSP webhook or the recovery job finish the booking.
Sweeper and payment collide. The sweeper's update has the condition hold_expires_at < now(); the payment extension raises the expiry first, so the sweeper matches no rows. Both use conditional updates, so whoever commits first wins and the other safely does nothing.
6.8 Partitioning by event
Every seat operation names one event, and no query needs seats from two events at once. So we partition (shard) by event_id: hash(event_id) chooses the shard, using the consistent hashing idea from the partitioning lesson so adding a shard moves few events.
Benefit: a hold transaction always stays on one shard, so no distributed transaction is needed. A hot event only slows its own shard.
Problem: one mega event (50,000 seats, 1 million users) is a hot partition. The waiting room limits it to about 300 writes per second, which one shard handles. For even larger events, give the event a dedicated shard, or sub-partition by (event_id, section) so each section locks independently (holds spanning two sections then need care).
Replication: each shard has a primary and replicas in other zones. Booking reads and writes use the primary; browse reads use replicas.
6.9 Bots and abuse
Bots buy seats the instant a sale opens, then scalpers resell them. Defenses stack:
Rate limit per user, IP and device at the gateway (token bucket from the rate limiting lesson).
Bot challenge (a CAPTCHA, a puzzle that is easy for humans and hard for scripts) before entering the waiting room.
Verified accounts with phone confirmation, created well before the sale. One queue slot per account.
Purchase limits per event (for example 6 tickets) checked inside the hold transaction.
Signed queue passes tied to a user and device so passes cannot be shared or sold.
Detection: flag accounts with inhuman click speed or many accounts from one IP range, and revoke passes.
No defense is perfect. Say that you aim to raise the cost for attackers and watch metrics for anomalies.
Step 7: Bottlenecks and Failure Handling
Bottlenecks
Primary seat database under a flash sale.Cause: thousands of conflicting writes. Mitigation: waiting room, conditional UPDATE that fails fast, short transactions, dedicated shard for mega events.
Seat map reads.Cause: a million users fetching the snapshot. Mitigation: CDN for static layout, short-TTL cached snapshots, one database read per second per event, push only batched deltas.
Waiting room store.Cause: 17K inserts per second. Mitigation: in-memory store, replicate it, shard queues per event, serve the waiting page from a CDN.
Push connection count.Cause: 30K or more open connections. Mitigation: spread across servers, each holding a few thousand; viewers subscribe only to their section.
Payment provider limits.Cause: PSP rate limits or slowness. Mitigation: the admit rate already caps checkout, timeouts and retries with backoff and jitter, and a circuit breaker so a slow PSP does not exhaust our threads.
Failures
Booking server fails. It is stateless, so the load balancer routes around it. Holds are in the database, so none are lost.
Primary database fails. A replica is promoted. Holds and bookings briefly fail (503 with Retry-After) while browsing continues from cache. Because replication can lag, make the booking commit synchronous to one replica so a confirmed booking survives a primary failure.
Cache fails. Browse falls back to replicas with request coalescing (many simultaneous misses cause one read). Rate limit the fallback.
Waiting room fails. Fail closed for booking (without passes, no one gets in) rather than open, otherwise the stampede hits the database. Keep a standby and persist queue positions.
Zone fails. Every tier runs in at least two zones.
Push fails. Clients fall back to polling the cached snapshot every few seconds.
Graceful degradation. Under extreme load, disable search and recommendations, keep seat selection and checkout alive.
What to monitor: hold success rate and 409 rate, hold and order p99 latency, database lock waits and replica lag, queue length and admit rate, payment success and timeout rate, pending-order age, number of expired holds waiting for the sweeper, and refund count (a spike signals the hold-expiry race).
Interview tip. Pick two failures you would worry about most, here payment timeout and primary failover, and walk through what the user sees and which data is safe. That beats reciting ten failures.
Step 8: Final Design Walkthrough
Final DesignArchitecture
Browse pathBooking pathClientWaiting roomqueue + signed passGateway + LBauth, rate limitBrowse serviceCache + CDNsnapshotsRead replicasasync copy of DBBooking serviceholds, ordersSeat databasesharded by eventSeat map pushWebSocket / SSEPayment serviceidempotent, sagapasson misschanges
Solid arrows are synchronous requests. Dashed arrows are asynchronous or fallback paths.
Request flow
Browse: client, gateway, browse service, cache (replica on a miss), seat map. Flash sale: client enters the waiting room, receives a signed pass, then reaches the booking service. Hold: conditional UPDATE inside one transaction on the event's shard; seats become held with a 10-minute expiry. Pay: order saved as pending, payment service charges with an idempotency key, conditional UPDATE moves seats to booked, order confirmed.
Data flow
Seat state, orders and payments live in the relational database, partitioned by event_id and replicated. Hot event pages and seat snapshots live in the cache. Seat changes flow from the booking service through a queue to push servers and out to open seat maps. Queue state and passes live in the waiting room store.
Background processing
The sweeper resets expired holds and publishes the update. A recovery job resolves pending orders by asking the payment provider. A reconciliation job compares provider records with orders. A search indexer copies event changes into the search index. Anti-bot jobs review suspicious accounts.
Critical design decisions
Relational database with transactions, because a hold or booking changes several rows that must succeed or fail together.
A conditional UPDATE guards each seat, so double booking is impossible no matter how many servers race.
Holds with a stored expiry time, so correctness never depends on a cleanup job running on time.
A virtual waiting room, cutting a 17K per second spike to about 300 writes per second.
Saga with idempotency keys and refunds, because we cannot make a card charge and a database commit one transaction.
Partition by event, keeping every booking on one shard and containing hot events.
Strong consistency for booking, eventual consistency for browsing, using each where it matters.
If time remains, discuss multi-region: keep each event's booking primary in one home region (so seat state has one authority), serve browsing from every region with replicas and CDN, and route a user's booking calls to the event's home region.
Common Interview Questions
Chapter quiz
Advanced Platform Designs · 6 questions
1.With 3 million online drivers sending a location every 4 seconds, how many location updates arrive per second?
2.Why does searching only the rider's own cell not work for finding nearby drivers?
3.Why does the design separate a metadata service from the block store?
4.With 7.5 million concurrent viewers at an average of 2.5 Mbps, what is the average egress?
5.Why is a relational database a good source of truth for seat state?
6.What is the safest way to implement seat hold expiry?