Global Event Ticketing and Seat Inventory Platform
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect a globally distributed live-event ticketing platform engineered to withstand sudden, massive traffic surges when marquee concerts or sports matches go on sale, while strictly guaranteeing that no seat or capacity slot is ever sold to more than one buyer.
Your system must support four core user capabilities: - Catalog discovery: Visitors can search and filter upcoming events by geographic area, category, and date window, and inspect venue layouts and pricing. - Tiered venue inventory: Each event spans multiple venue sections with distinct ticket prices and seating capacities. - Timed exclusive holds: Selecting seats grants the shopper an exclusive 10-minute reservation window; if payment does not complete before that timer lapses, the reserved inventory automatically re-enters the sellable pool. - All-or-nothing checkout: Completing payment atomically converts an active reservation into a confirmed order and issues booking credentials.
On the operational side, the platform must absorb extreme read and write bursts at on-sale timestamps, enforce strict serializability over inventory so overselling is impossible, and remain available to buyers even if one geographic region suffers degraded or partial data-center capacity.
Scope & Expectations
- External APIs and data schema: Specify the primary HTTP contracts for browsing events, acquiring 10-minute seat holds, and finalizing orders, along with the storage schema modeling venues, sections, seats, holds, and confirmed purchases.
- Contention and hold-expiry mechanics: Explain how concurrent buyers across the globe are prevented from claiming the same inventory simultaneously, and how abandoned 10-minute holds return cleanly without race conditions at checkout time.
- Multi-region topology and consistency trade-offs: Detail how read traffic is isolated from transactional booking writes across regions, and weigh cross-region latency against fault tolerance and zero-oversell guarantees during partial data-center outages.
Step-by-step walkthrough
Clarify requirements, workload split, and assumptions
A global ticketing platform serves two opposite workloads under one roof:
- Browsing (event search, details, seat maps): Massive global read traffic that can safely be 1–2 seconds stale.
- Buying (seat holds and checkout): Much smaller write traffic where correctness is absolute — a seat may never be sold twice.
Separating these two paths completely is the foundation of the architecture.
Functional capabilities
- Catalog discovery: Visitors filter and query upcoming events by metro/coordinates, genre, calendar window, and text query, and inspect venue maps, section pricing, and near-real-time seat availability.
- Inventory models: Venues divide into sections and price tiers supporting both reserved seating (individually addressable seats such as
A-12-7) and general admission (GA) (unnumbered capacity pools such as"Floor Standing: 5,000 tickets"). - 10-minute exclusive hold: Claiming seats locks them exclusively for
10 minutes. Whenever payment is not completed before that deadline lapses, the locked inventory re-enters the open sellable pool automatically. - All-or-nothing checkout: Capturing funds and minting ticket credentials commit or roll back together as one logical unit, yielding an order confirmation and verifiable QR barcodes.
- Fairness & purchase limits: Cap buyers at
8tickets per order and per account per event, and allow at most1live hold per account per event.
Non-functional requirements & explicit assumptions
- Zero overselling (strong consistency): Inventory state must remain strongly consistent even across server crashes, network partitions, or data-center failovers.
- Extreme traffic spikes: Popular stadium drops bring millions of concurrent fans onto a single
event_idat a pre-announced start timestamp. - High availability: The platform continues serving reads and completing ticket sales if an availability zone (AZ — an isolated building/power domain inside a cloud region) fails, and we design multi-region replication so even a complete regional blackout loses zero committed sales and resumes selling within seconds.
- Latency targets: Event search/details
p99 < 300 msglobally;POST /holdsp99 < 500 msworldwide; seat-map availability views up to~2 sstale. - Scale & domain assumptions:
100Mmonthly active users,50,000active events,300Mtickets sold/year (~100Morders). Every event is assigned a home region geographically closest to its physical venue. External payment processors support two-stepauthorize+capturewith idempotency keys (unique client-supplied tokens that guarantee retrying a network request never charges a card twice).
Estimate traffic spikes, storage, and single-row contention
Baseline average 300M tickets / 31.5M seconds/year = ~10 tickets/s (~3 orders/s) -> Average load is tiny; architecture is dictated 100% by hot drops! Hot stadium drop 60,000 seats (~3 tickets/order -> ~20,000 total orders) 2,000,000 fans waiting at T = 00:00 Without a gate: 2M fans click within 10 s -> ~200,000 hold writes/s on ONE event_id, where >99% must fail after fighting over database row locks! With waiting room: Admit 2,000 fans/min (~33 fans/s) into the booking flow: ~2 hold attempts/fan -> ~70 hold writes/s on the inventory shard At 70% conversion -> ~1,400 orders/min -> sells out cleanly in ~15 min Active shoppers (Little's Law = 2,000/min x 5 min avg checkout) = ~10,000 Read traffic during the hot drop Waiting-room poll: 2,000,000 waiting fans polling every 15 s = ~133,000 req/s Seat-map polling: 60,000 seats x 1 bit/seat = 7,500 bytes (7.5 KB compact bitmap!) 10,000 active shoppers polling every 2 s = 5,000 req/s (~37.5 MB/s) Read : Write ratio ~138,000 reads/s vs ~70 hold writes/s -> ~2,000 : 1 Database storage Active seat rows: 50,000 events x 3,000 avg seats x 150 bytes = ~22.5 GB (fits in RAM!) Historical orders: 100M orders/year x 1 KB = ~100 GB/year Single-row lock physics (why row granularity matters) A strongly consistent DB holds a row write lock for at least 1 quorum commit round-trip: 1-region quorum (3 AZs, ~2 ms commit): max ~1 / 0.002 s = ~500 updates/s per row Cross-region quorum (~25 ms RTT -> ~27 ms commit): max ~1 / 0.027 s = ~37 updates/s per rowFour design decisions follow directly from these numbers:
- A virtual waiting room is mandatory. Turning
200,000doomed lock-contending writes/sec into~70orderly writes/sec protects the database better than any amount of hardware scaling. - Never store a large GA section as one integer row. At
27 mscross-region commit latency, a singleavailable_seatsrow caps an entire stadium floor at37holds/sec! Splitting GA capacity across32bucket rows raises throughput to32 * 37 = ~1,184holds/sec. - Encode seat maps as
7.5 KBbitmaps cached in Redis and CDNs so2,000 : 1read spikes never touch the transactional inventory database. - All
22.5 GBof active seat rows fit comfortably in memory across a small sharded database cluster.
- A virtual waiting room is mandatory. Turning
Design the external APIs (discovery, waiting room, holds, checkout)
1. Discovery & Advisory Availability (served from nearest region + CDN edge) GET /v1/events?lat=&lon=&radius_km=&category=&from=&to=&q=&cursor= -> 200 {events: [{event_id, name, venue, start_time, min_price, on_sale_at}], next_cursor} GET /v1/events/{event_id} -> static details, sections, pricing (CDN TTL 60 s) GET /v1/events/{event_id}/availability -> {version, section_counts[], seat_bitmap_b64} (TTL 1-2 s) 2. Virtual Waiting Room (absorbs pre-drop and on-sale surges) POST /v1/events/{event_id}/queue -> 200 {queue_token (HMAC-signed: user, event, position)} GET /v1/events/{event_id}/queue/status -> 200 {admitted_through_pos, est_wait_sec} (CDN TTL 1 s) POST /v1/events/{event_id}/admission {queue_token} -> 200 {admission_token, ttl_sec: 900} 3. Transactional Booking (routed to event's home region; requires valid admission_token) POST /v1/events/{event_id}/holds Header: Idempotency-Key: <uuid> Body: {seat_ids: ["A-12-7", "A-12-8"]} OR {section_id: "GA-FLOOR", quantity: 2} -> 201 {hold_id, seats, expires_at} | 409 {unavailable_seat_ids} | 429 {retry_after} DELETE /v1/holds/{hold_id} -> 204 (early voluntary release) POST /v1/holds/{hold_id}/checkout Header: Idempotency-Key: <uuid> Body: {payment_method_token} -> 202 {order_id, status: "PENDING_PAYMENT"} GET /v1/orders/{order_id} -> 200 {status, confirmation_code, tickets[]}Key API design choices:
- Idempotency keys on every mutating call: Stored in the same database shard as the event so if a mobile client drops offline mid-response and retries
POST /holdsorPOST /checkout, the server returns the exact saved response without creating duplicate holds or double-charging. - Asynchronous
202 Acceptedcheckout: External card networks can spike from300 msto8 sunder load; returning202immediately keeps API threads non-blocking while background checkout workers finish authorization. - Optimistic UI backed by authoritative
409 Conflict: BecauseGET /availabilityis cached for1–2 s, two shoppers may click the same green seat; one wins201 Created, and the second gets409 Conflictwith an immediate map refresh.
- Idempotency keys on every mutating call: Stored in the same database shard as the event so if a mobile client drops offline mid-response and retries
Data model and single-shard partitioning by event
Catalog Tables (read-mostly; asynchronously replicated to all regions) venues venue_id PK, name, lat, lon, timezone, map_layout_uri events event_id PK, venue_id, title, category, start_time, on_sale_at, home_region, status (DRAFT | ON_SALE | SOLD_OUT | CANCELLED) sections (event_id, section_id) PK, name, kind (RESERVED | GA), price_cents, capacity Inventory Shard Tables (co-partitioned by event_id -> 1 event = 1 consensus shard!) seats (event_id, seat_id) PK, section_id, status (AVAILABLE | HELD | PAYMENT_PENDING | SOLD), hold_id, hold_expires_at, order_id, version ga_buckets (event_id, section_id, bucket_id) PK, available_count -- 32 buckets (0..31) holds hold_id PK, event_id, user_id, section_id, seat_ids_or_qty, bucket_id, status (ACTIVE | CHECKING_OUT | CONVERTED | EXPIRED | RELEASED), original_expires_at, expires_at UNIQUE (event_id, user_id) WHERE status IN ('ACTIVE', 'CHECKING_OUT') orders order_id PK, event_id, hold_id UNIQUE, user_id, amount_cents, currency, status (PENDING_PAYMENT | CONFIRMED | PAYMENT_FAILED | REFUNDED), payment_ref, confirmation_code, created_at tickets ticket_id PK, event_id, order_id, seat_id_nullable, status (VALID | VOID), qr_secret UNIQUE (event_id, seat_id_nullable) WHERE status = 'VALID' AND seat_id_nullable IS NOT NULL idempotency (event_id, user_id, idem_key) PK, req_hash, resp_json, created_at outbox (event_id, seq_no) PK, event_type, payload_json, created_atWhy this schema prevents subtle distributed-systems bugs:
- Single-shard transactions by
event_id: Everyseats,ga_buckets,holds,orders,tickets,idempotency, andoutboxrow forevent_id = E1lives inside the exact same shard range, so holds and sales commit in one local ACID transaction without slow cross-shard two-phase commit (2PC). - The
seatsrow is the single source of truth (for reserved seating), backed by a database-enforced partial unique index ontickets (event_id, seat_id)wherestatus = 'VALID'as a last-line-of-defense safety net (settingstatus = 'VOID'on refund allows clean resale). - Transactional Outbox pattern: Every hold, expiry, or sale inserts a row into
outboxinside the same SQL transaction. CDC (Change Data Capture) tails the database commit log and publishesoutboxevents to Kafka, guaranteeing read caches and email workers never miss an update and never publish uncommitted rollbacks.
- Single-shard transactions by
High-level multi-region architecture
Global Users (Web / iOS / Android) | Anycast DNS + Global CDN Edge (caches event pages 60s, seat-map bitmaps 1-2s, queue status 1s) / \ v v +---------------------------------------+ +---------------------------------------+ | Region A (Event E1's Home Region) | | Region B / C (Remote User Regions) | | API Gateway: auth, rate limit, | | API Gateway: auth, rate limit | | HMAC admission_token verification | | - Discovery & search served LOCALLY | | OpenSearch replica + Redis Seat Cache | | - Seat-map bitmaps served LOCALLY | | Waiting Room Service | | - Hold & Checkout writes forwarded -+--+ | Stateless Inventory & Checkout Svc | +---------------------------------------+ | | | |<---------------------------------------------+ | v | | Inventory Consensus Shard Leader | 5-Replica Raft/Paxos Group per Shard Range: | (2 replicas in Region A AZ1 & AZ2) -+-> + 2 replicas in Region B + 1 in Region C | | | (same continent; survives AZ or Region loss!) | Checkout Pool ---> External Payment | | Outbox -> CDC -> Kafka ---------------+-> Regional Bitmap Projectors (update Redis in +---------------------------------------+ all regions), Search Indexer, Hold Sweeper, Ticket QR / Email ServiceEnd-to-end flow of a global fan buying seats:
- Browse locally: A fan in Tokyo viewing a London concert hits the Tokyo CDN edge and Tokyo OpenSearch/Redis replicas (
< 50 ms, zero load on London). - Fair queue: Minutes before
on_sale_at, fans join the waiting room, receive a signedqueue_token, and poll the 1-second CDN-cachedadmitted_through_posinteger. - Gateway admission: Once
position <= admitted_through_pos, the client swaps itsqueue_tokenfor a 15-minute HMAC-signedadmission_tokenverified statelessly at the API gateway. - Authoritative hold:
POST /holdsroutes to London's Inventory Shard Leader (~150 mscross-continent network hop +~27 msquorum commit =< 200 ms, well inside our500 mstarget). - Async checkout:
POST /checkoutlocks the hold intoCHECKING_OUT, authorizes payment withIdempotency-Key = order_id, and commitsSOLD+VALIDtickets in one shard transaction. - Global cache fan-out: CDC streams the
outboxevent to every region's Bitmap Projector, flipping those seat bits from0to1in Redis worldwide within~1–2 s.
- Browse locally: A fan in Tokyo viewing a London concert hits the Tokyo CDN edge and Tokyo OpenSearch/Redis replicas (
Deep dive 1: Concurrency control — preventing double-selling at scale
How do we guarantee two fans on opposite sides of the planet never claim Seat
A-12-7simultaneously? Let's compare a distributed lock manager against database conditional writes:- Why a separate Distributed Lock Manager (e.g., Redis Redlock or ZooKeeper) falls short: Acquiring a lock in Redis and then writing to SQL creates two stateful systems. If Worker 1 grabs a 5-second lock in Redis and then suffers a 6-second JVM garbage-collection pause, the lock expires, Worker 2 grabs the lock and sells Seat
A-12-7, and Worker 1 wakes up and overwrites it! Preventing that requires a fencing token (a monotonically increasing integer passed on every write that the database rejects if a newer token has already written). Once the database checks a version/token on the row, the database itself is already doing the concurrency control — the external lock service just adds latency and another failure point! - Our choice — Single-shard conditional SQL writes: The seat row is simultaneously the lock and the durable record, held locked only for the few milliseconds of the commit.
1. Reserved seats (deadlock-free all-or-nothing conditional
UPDATE):Before running the transaction, the Inventory Service sorts
:seat_idsin ascending lexicographical order (["A-12-7", "A-12-8"]) so two concurrent transactions requesting overlapping seats in reverse order always acquire row locks in identical order and can never deadlock:BEGIN; -- 1. Enforce 1 active hold per user (lazily expiring this user's own stale hold if needed) -- and verify existing VALID tickets + len(:sorted_seat_ids) <= 8. -- 2. Claim all requested seats atomically; DB clock now() is the single time authority UPDATE seats SET status = 'HELD', hold_id = :hold_id, hold_expires_at = now() + INTERVAL '10 minutes', version = version + 1 WHERE event_id = :event_id AND seat_id IN (:sorted_seat_ids) AND (status = 'AVAILABLE' OR (status = 'HELD' AND hold_expires_at < now())); -- Application check: if rows_updated != len(:sorted_seat_ids) -> ROLLBACK and return 409! INSERT INTO holds (hold_id, event_id, user_id, seat_ids_or_qty, status, original_expires_at, expires_at) VALUES (:hold_id, :event_id, :user_id, :sorted_seat_ids, 'ACTIVE', now() + INTERVAL '10 minutes', now() + INTERVAL '10 minutes'); INSERT INTO outbox (event_id, seq_no, event_type, payload_json) VALUES (...); COMMIT;For "Best Available" auto-selection, naive deterministic ranking causes every concurrent request to collide on the exact same top 2 seats; instead, rank the top ~
50candidate pairs and pick randomly among equal-tier pairs (or useSELECT ... FOR UPDATE SKIP LOCKEDinside the shard).2. General Admission sections (
32sharded atomic sub-counters):UPDATE ga_buckets SET available_count = available_count - :qty WHERE event_id = :event_id AND section_id = :section_id AND bucket_id = :chosen_bucket -- start at hash(hold_id) % 32, probe next on 0 rows AND available_count >= :qty;Splitting a
5,000-person floor into32buckets boosts cross-region commit throughput from~37/sto~1,184/s. When total remaining capacity drops below64tickets, a lightweight background task coalesces residual counts intobucket_id = 0so a group buying4tickets never fails when1ticket sits in four separate buckets.- Why a separate Distributed Lock Manager (e.g., Redis Redlock or ZooKeeper) falls short: Acquiring a lock in Redis and then writing to SQL creates two stateful systems. If Worker 1 grabs a 5-second lock in Redis and then suffers a 6-second JVM garbage-collection pause, the lock expires, Worker 2 grabs the lock and sells Seat
Deep dive 2: The 10-minute hold lifecycle and atomic checkout saga
Let's compare the three candidate mechanisms for expiring 10-minute holds:
Expiry mechanism How it works Critical flaw if used alone 1. Cache TTL (Redis EX 600) Key vanishes ~600 s after creation Redis failover loses active holds (causes overselling!); key eviction notifications are best-effort only 2. Delayed Queue / Cron Job Publish "expire hold H" delayed 10 min Queue lag leaves seats stuck; redelivery or clock skew races with checkout at 9:59 3. DB Lazy Expiry + Sweeper hold_expires_at stored on seat row; new GA buckets cannot lazily self-increment (Our choice) holds reclaim expired rows immediately! without the sweeper runningWe combine database lazy expiry for correctness with a 15-second per-shard sweeper for GA buckets and UI freshness (plus a delayed message queue solely for harmless "2 minutes left to pay!" push reminders):
- Reserved seats: Even if the sweeper crashes for an hour, zero seats are stuck or oversold because
POST /holdschecksOR (status = 'HELD' AND hold_expires_at < now())inline! When the sweeper runs (UPDATE seats SET status = 'AVAILABLE' ... WHERE status = 'HELD' AND hold_expires_at < now()), it emitsoutboxevents so regional seat maps turn green again. - GA sections: Every
15 s, the sweeper flips expiredACTIVEGA holds (UPDATE holds SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND expires_at < now() RETURNING bucket_id, qty) and addsqtyback toga_bucketsin the same shard transaction —status = 'ACTIVE'guarantees each expired GA hold returns its tickets exactly once.
Atomic Checkout via a 4-step Saga (solving the
9:59payment-in-flight race!):Never hold a database transaction open across an external HTTP call to Stripe/Adyen. Instead, coordinate two short single-shard SQL transactions around an idempotent payment call:
- Lock hold for payment (Shard Tx 1): Verify using DB
now()that the hold is stillACTIVEandexpires_at > now(), createorders(PENDING_PAYMENT,hold_id UNIQUE), and atomically transitionholdstoCHECKING_OUTandseatstoPAYMENT_PENDING(WHERE hold_id = :hold_id AND status = 'HELD' AND hold_expires_at > now()), extendingexpires_atby+5 minutes. Now neither a rivalPOST /holds(which only reclaims expiredHELDrows, neverPAYMENT_PENDINGrows!) nor the GA sweeper (which only reclaimsACTIVEholds!) can steal the tickets while the bank processes the card at9:59! - External payment
authorize: Call the payment gateway withidempotency_key = order_idand a10 ssocket timeout. Crucial rule: an HTTP timeout means unknown, never declined — query the gateway's status byorder_idbefore releasing anything. - Commit the sale (Shard Tx 2): In one atomic shard commit, flip
holds(CHECKING_OUT -> CONVERTED), flipseats(PAYMENT_PENDING -> SOLD), insertVALIDticketsrows, markordersCONFIRMED, and append theoutboxconfirmation event. (Then asynchronouslycapturethe authorized funds with the same idempotency key.) - Clean compensation on decline or stuck payment: If the card is explicitly declined and
now() < original_expires_at, revertholdstoACTIVEandseatstoHELDwithoriginal_expires_atso the fan can try a second card in their remaining window; ifnow() >= original_expires_at, immediately markEXPIREDand free the seats/GA bucket in the same transaction. If a payment stays unknown past the+5 mingrace window, the sweeper voids/cancels the authorization byorder_idand releases inventory only after the void is confirmed.
- Reserved seats: Even if the sweeper crashes for an hour, zero seats are stuck or oversold because
Deep dive 3: Surviving hot drops and multi-region consistency vs. latency
How the Virtual Waiting Room + Read/Write Separation tame a 2-million-user spike:
- Fair pre-drop lottery (defeating click-speed races): Everyone who joins the waiting room before
on_sale_atreceives an HMAC-signedqueue_tokencontaining a uniformly generated random 64-bit lottery rank; fans arriving afteron_sale_atget sequential numbers behind the pre-drop cohort. Neither hammering refresh nor having a1 msbot ping grants an earlier spot. - Collapsing
133,000polls/sec to near-zero origin load: Waiting clients pollGET /queue/status, which returns a tiny JSON{admitted_through_pos: 18400}cached at CDN edges withTTL = 1 s. Every client computesmy_pos - admitted_through_poslocally! An adaptive admission controller adjusts the admission rate every5 sbased on remaining seats, active shoppers, and checkout latency. - Complete read/write isolation: Search queries hit regional OpenSearch replicas; event details hit CDN (
TTL 60 s); seat maps read regional Redis7.5 KBbitmaps (TTL 1–2 s). Zero browsing requests ever touch the Inventory Shard Leaders.
Multi-region inventory placement — trading off write latency against outage survival:
Multi-region DB topology Commit latency Outage survival Oversell risk A. Single global DB region +150 ms worldwide Full AZ; 1 region Zero B. Home region per event (3 AZ quorum) ~2 ms local Full AZ outage Zero on AZ loss; async + async cross-region standby failover CAN oversell! C. Home region per event, 5-way Raft ~27 ms same- Full AZ loss AND Zero (quorum always holds quorum across 3 regions (2+2+1) continent quorum full Region loss! every committed sale!) D. Active-active multi-leader writes ~2 ms everywhere Any region loss HIGH (split-brain double-sells)- Option D (active-active multi-leader) violates our #1 invariant: two regions accepting local writes for Seat
A-1simultaneously will double-sell it before replication converges. - Option B (
3-AZquorum in the home region) commits in~2 msand satisfies surviving a partial regional data-center (AZ) outage. However, if all ofus-east-1goes dark, promoting an asynchronousus-west-2replica risks reselling seats committed in the final seconds before the crash — meaning Option B must pause sales forus-east-1events during a full regional outage. - Our choice — Option C (
2 + 2 + 1consensus replicas across 3 regions on the same continent, leader pinned to the home region): With2replicas inus-east-1(across 2 AZs),2inus-east-2, and1witness/replica inus-central-1(CockroachDB / Spanner style), any commit needs3 of 5acknowledgments (~27 ms). Because the waiting room throttles writes to~70/sand GA sections use32buckets,27 msis effortless — and if either an AZ or all ofus-east-1vanishes, the remaining3replicas already hold every single committed ticket and elect a new leader inus-east-2within seconds with zero overselling and zero lost orders.
- Fair pre-drop lottery (defeating click-speed races): Everyone who joins the waiting room before
Scaling bottlenecks, failure modes, and trade-off summary
- Scaling mega-events (
100,000+festival passes): Pre-split hotevent_idranges onto dedicated bare-metal consensus nodes beforeon_sale_at. If a single festival needs>5,000writes/sec, shard inventory by(event_id, section_id)and scope each cart to one section so every hold/checkout remains a single-shard transaction. - Payment-provider bulkheads: Isolate checkout worker pools per payment processor (bulkhead pattern — partitioning thread/connection pools so one slow dependency cannot sink unrelated work) and shed waiting-room admission rate automatically if payment latency climbs.
- Failure recovery checklist:
- Home-region AZ or full-region loss: Raft/Paxos re-elects leader on surviving quorum (
Option C); waiting-roomadmitted_through_poswatermark is replicated, and HMAC-signedqueue_token/admission_tokencookies verify statelessly in the failover region; clients safely retry in-flight holds/checkouts with theirIdempotency-Key. - Redis / CDN / OpenSearch outage: Seat maps degrade gracefully or stale slightly (
409protects inventory); core checkout keeps running untouched. - Defense-in-depth reconciliation: A continuous auditor verifies
COUNT(SOLD seats) == COUNT(VALID tickets) == COUNT(CAPTURED order line items)andSUM(ga_buckets) + SUM(live GA holds) + COUNT(VALID GA tickets) == section.capacity.
- Home-region AZ or full-region loss: Raft/Paxos re-elects leader on surviving quorum (
- Core trade-offs recap: Single-shard conditional SQL writes beat external distributed locks; database lazy expiry + sweeper beats fragile cache TTLs; virtual waiting rooms trade a fair queue wait for
3,000xlower write contention;1–2 sstale7.5 KBbitmaps protect strongly consistent inventory leaders; and2+2+1cross-region consensus trades+25 mson rare booking writes for zero-oversell regional disaster recovery.
- Scaling mega-events (
Intuition & how it works
Imagine a world-famous bakery releasing 1,000 limited-edition croissants at 10:00 AM while 200,000 people gather outside. If you throw the doors open so all 200,000 people rush the counter at once, the room jams solid and two overwhelmed cashiers inevitably promise the last croissant to two different buyers. Instead, you post menus and a live chalkboard count outside on the sidewalk so 200,000 fans can browse without bothering the cashiers (read/write separation via CDNs and regional caches), hand everyone outside a lottery ticket and admit only 30 shoppers per minute inside the shop (virtual waiting room), and keep a single master clip-sheet behind the counter where claiming a croissant crosses it off atomically with a 10-minute sticky-note timestamp (single-shard conditional SQL writes + lazy expiry).
The naive design — serving seat maps straight from the primary database, letting millions of users hit POST /holds at once, expiring holds via Redis key TTLs, and accepting local writes across multiple regions — fails under real ticket drops. Read spikes starve checkout transactions, 200,000 simultaneous hold attempts lock-thrash the same event's rows when 99% must fail anyway, active-active multi-region writes double-sell seats before replication catches up, and a Redis failover or a credit card still processing at 9:59 either loses active holds or steals a seat mid-payment.
Trace how our design handles Seat A-1 across four moments during a stadium drop:
10:00:00(Race onPOST /holds): Admitted fans Alice and Bob clickA-1at the exact same millisecond. Both requests route to the event's home-region database shard leader; Alice's conditionalUPDATE seats SET status = 'HELD', hold_expires_at = 10:10:00 WHERE status = 'AVAILABLE'commits first, so Bob'sUPDATEmatches0rows and immediately returns409 Conflict, refreshing his seat map.10:10:02(Lazy expiry without waiting on a timer): Alice closes her laptop without paying. Even before the 15-second background sweeper runs, Carol clicksA-1and herUPDATEsucceeds inline becausestatus = 'HELD' AND hold_expires_at < now(), assigninghold_id = H2until10:20:02.10:19:55(Protecting an in-flight payment): Carol clicks Pay (Idempotency-Key: K9). Checkout Step 1 atomically flipsH2toCHECKING_OUTandA-1toPAYMENT_PENDINGwith a+5 mingrace deadline (10:25:02), blocking any rival hold from stealingA-1at10:20:02while the card network responds.10:19:57(Atomic sale + global bitmap fan-out): Card authorization succeeds; Checkout Step 3 atomically flipsA-1toSOLD, inserts aVALIDticket row, and writes a transactional outbox row (an event written inside the same DB commit) that updates7.5 KBregional Redis seat-map bitmaps worldwide within~1 s.
Key trade-offs
- Database conditional writes vs. an external distributed lock manager. Using
UPDATE seats ... WHERE status = 'AVAILABLE'inside the inventory shard makes the seat row both the lock and the durable record, locked for only milliseconds. Adding a separate Redis or ZooKeeper lock introduces dual-system drift and lease-expiry races during garbage-collection pauses — which require monotonic fencing tokens (increasing sequence numbers verified by the database on write) that force the database to enforce concurrency anyway. - Database lazy expiry + sweeper vs. cache TTLs or delayed job queues. Checking
hold_expires_at < now()inside thePOST /holdsquery makes reserved-seat correctness 100% immune to timer delays or cache failovers, at the minor cost of running a lightweight 15-second sweeper to refresh cached seat-map bitmaps and return expired unnumbered General Admission (GA) bucket counts. - Strict consistency for writes vs. eventual consistency (
1–2 s) for reads. Onlyseats,ga_buckets,holds,orders, andticketsgo through consensus quorum commits. ServingGET /availabilityfrom regional7.5 KBRedis/CDN bitmaps shields the database from2,000 : 1read spikes, trading occasional409 Conflictclicks on stale green seats for massive global scalability. - Same-continent 3-region consensus (
2+2+1, ~27 ms) vs. 1-region 3-AZ quorum (~2 ms). A single-region quorum across 3 availability zones (AZs) (isolated data centers within one metro area) commits in~2 msand survives partial data-center outages, but a full regional blackout either halts sales or risks overselling if failed over to an async standby. Spreading a 5-replica quorum (majority3 of 5agreement) across 3 regions on the same continent adds~25 msper write in exchange for surviving an entire regional outage with zero lost or duplicate sales. - Virtual waiting room vs. unthrottled direct writes. A pre-drop random lottery queue plus rate-controlled admission tokens adds a visible queue screen and an extra edge service, but reduces conflicting database writes by
~3,000x(200,000/s -> ~70/s) while making click speed irrelevant. - Sharded
32-way GA buckets vs. a single section counter. Splitting a GA floor across32rows lifts cross-region throughput from~37to~1,184holds/sec, trading exact single-row simplicity for background bucket rebalancing when fewer than64tickets remain. - Asynchronous checkout saga vs. synchronous payment inside a DB transaction. Coordinating two millisecond shard transactions around an external payment call (saga pattern) with idempotency keys (unique client retry tokens) adds intermediate
PAYMENT_PENDINGstates and timeout reconciliation, in exchange for never holding database locks across slow third-party HTTP calls.
Common mistakes
- Application-level check-then-act (
SELECT statusfollowed byUPDATE). Without an atomicWHERE status = 'AVAILABLE'condition (or row lock), two concurrent threads both readAVAILABLEand double-book the seat. - Deadlocking multi-seat holds by locking seats in caller-supplied order. If Alice requests
["A-1", "A-2"]while Bob requests["A-2", "A-1"], unsorted locking can deadlock; always sortseat_idscanonically before executingUPDATE. - Holding open database transactions during the 10-minute hold or external Stripe call. Database connection pools and row locks exhaust within seconds if held across human think time or multi-second payment calls.
- Relying on Redis
TTLexpiration as the source of truth for holds. Async Redis replication drops holds on primary failover (causing overselling), and lazy key eviction delays freeing expired seats. - Missing the
9:59payment-in-flight race (especially on GA sections). If a user starts paying at9:58and the hold staysACTIVE/HELDwith a10:00expiry, a rival buyer or the GA sweeper reclaims the tickets at10:00right before the card charge succeeds! Moving the hold toCHECKING_OUT/PAYMENT_PENDINGwith a+5 mingrace window prevents this. - Using active-active multi-leader replication for seat inventory. Last-writer-wins conflict resolution on seats is literally overselling.
- Storing a 10,000-person GA floor as a single counter row. One hot row serializes every transaction at
1 / commit_latency(~37 updates/sacross regions). - Skipping a database-level uniqueness backstop. Always enforce a partial unique index
UNIQUE (event_id, seat_id) WHERE status = 'VALID'onticketsso even an application bug cannot mint two valid barcodes for one seat.
Follow-up questions
- What happens to active checkouts and system throughput if your external payment gateway slows down sharply mid-drop, and how do you contain the blast radius? Because
POST /checkoutimmediately returns202 Acceptedasynchronously, front-end API workers never block on card networks. Partition background checkout workers per payment processor using bulkheads (isolated bounded worker pools) and circuit breakers, and treat any HTTP socket timeout strictly as indeterminate — querying status or awaiting webhooks and retrying only with the originalIdempotency-Key = order_idand jittered backoff so no buyer is double-charged. At the same time, dynamically extend thePAYMENT_PENDINGgrace lease (say from+5to+10minutes) so legitimate slow authorizations are not prematurely voided, and wire payment queue depth into the virtual waiting room's admission controller to slow incoming shoppers until the backlog drains. When a secondary processor is available, steer only freshPENDING_PAYMENTorders to the backup gateway — never an order whose initial authorization may still settle on the primary gateway. - Suppose you need to move the live seat-inventory store onto a new schema or database cluster — how do you cut over with near-zero downtime and zero double-sold seats? For in-place schema changes, follow an expand-and-contract sequence using online DDL (
CREATE INDEX CONCURRENTLYorgh-ost): add nullable columns/tables, roll out dual-writing service code, backfill in throttled per-event batches, validate row checksums, switch reads, and drop retired columns afterward. When migrating onto a brand-new database cluster, exploit the fact that inventory is already co-partitioned byevent_idbehind an event-to-shard directory and cut over one event at a time (beginning with low-traffic events outside on-sale windows): replicate live writes via CDC (Change Data Capture), verify exact row-level checksums (seat_id, status, hold_id, order_id), briefly pause writes on that singleevent_idfor1–3 secondswhile the final CDC tail drains, atomically flip its routing pointer to the target cluster (keeping reverse CDC warm for instant rollback), and run an automated post-cutover invariant audit (SOLD seats == VALID tickets). - How do you stop automated scraper and scalper fleets from locking up every available seat via repeated 10-minute holds without paying? Because this denial-of-inventory attack relies on cycling unpaid holds at scale, tie hold scarcity to verified human accounts rather than raw HTTP requests. Require authenticated profiles with progressive trust signals on high-demand drops (verified phone, passkey/device attestation, or pre-drop fan registration), enforce
1waiting-room slot and1active hold (<= 8seats) per account in the database, and bind single-use HMACadmission_tokensto account + TLS/session fingerprint so harvested tokens cannot be replayed across headless bots. Assigning random lottery ranks to all pre-drop waiting-room arrivals neutralizes sub-millisecond bot click speed, while per-account uniqueness blocks queue stuffing beyond verified identities. Layer CDN/edge reputation filtering (IP/ASN/device signals), step-up challenges or 1 USD refundable card pre-checks on anomalous cohorts, and behavioral detectors that revoke holds early and apply cooldown penalties to account clusters showing abnormal hold-expiry ratios.
Follow-up questions
- What happens to active checkouts and system throughput if your external payment gateway slows down sharply mid-drop, and how do you contain the blast radius?
- Suppose you need to move the live seat-inventory store onto a new schema or database cluster — how do you cut over with near-zero downtime and zero double-sold seats?
- How do you stop automated scraper and scalper fleets from locking up every available seat via repeated 10-minute holds without paying?
Similar questions
- In-Memory Relational Table with Transaction Rollback
- Rolling-Window Error Alerting by Endpoint Prefix
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests