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

  1. 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

    1. 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.
    2. 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").
    3. 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.
    4. 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.
    5. Fairness & purchase limits: Cap buyers at 8 tickets per order and per account per event, and allow at most 1 live 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_id at 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 ms globally; POST /holds p99 < 500 ms worldwide; seat-map availability views up to ~2 s stale.
    • Scale & domain assumptions: 100M monthly active users, 50,000 active events, 300M tickets sold/year (~100M orders). Every event is assigned a home region geographically closest to its physical venue. External payment processors support two-step authorize + capture with idempotency keys (unique client-supplied tokens that guarantee retrying a network request never charges a card twice).
  2. 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 row
    

    Four design decisions follow directly from these numbers:

    1. A virtual waiting room is mandatory. Turning 200,000 doomed lock-contending writes/sec into ~70 orderly writes/sec protects the database better than any amount of hardware scaling.
    2. Never store a large GA section as one integer row. At 27 ms cross-region commit latency, a single available_seats row caps an entire stadium floor at 37 holds/sec! Splitting GA capacity across 32 bucket rows raises throughput to 32 * 37 = ~1,184 holds/sec.
    3. Encode seat maps as 7.5 KB bitmaps cached in Redis and CDNs so 2,000 : 1 read spikes never touch the transactional inventory database.
    4. All 22.5 GB of active seat rows fit comfortably in memory across a small sharded database cluster.
  3. 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 /holds or POST /checkout, the server returns the exact saved response without creating duplicate holds or double-charging.
    • Asynchronous 202 Accepted checkout: External card networks can spike from 300 ms to 8 s under load; returning 202 immediately keeps API threads non-blocking while background checkout workers finish authorization.
    • Optimistic UI backed by authoritative 409 Conflict: Because GET /availability is cached for 1–2 s, two shoppers may click the same green seat; one wins 201 Created, and the second gets 409 Conflict with an immediate map refresh.
  4. 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_at
    

    Why this schema prevents subtle distributed-systems bugs:

    • Single-shard transactions by event_id: Every seats, ga_buckets, holds, orders, tickets, idempotency, and outbox row for event_id = E1 lives 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 seats row is the single source of truth (for reserved seating), backed by a database-enforced partial unique index on tickets (event_id, seat_id) where status = 'VALID' as a last-line-of-defense safety net (setting status = 'VOID' on refund allows clean resale).
    • Transactional Outbox pattern: Every hold, expiry, or sale inserts a row into outbox inside the same SQL transaction. CDC (Change Data Capture) tails the database commit log and publishes outbox events to Kafka, guaranteeing read caches and email workers never miss an update and never publish uncommitted rollbacks.
  5. 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 Service
    

    End-to-end flow of a global fan buying seats:

    1. 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).
    2. Fair queue: Minutes before on_sale_at, fans join the waiting room, receive a signed queue_token, and poll the 1-second CDN-cached admitted_through_pos integer.
    3. Gateway admission: Once position <= admitted_through_pos, the client swaps its queue_token for a 15-minute HMAC-signed admission_token verified statelessly at the API gateway.
    4. Authoritative hold: POST /holds routes to London's Inventory Shard Leader (~150 ms cross-continent network hop + ~27 ms quorum commit = < 200 ms, well inside our 500 ms target).
    5. Async checkout: POST /checkout locks the hold into CHECKING_OUT, authorizes payment with Idempotency-Key = order_id, and commits SOLD + VALID tickets in one shard transaction.
    6. Global cache fan-out: CDC streams the outbox event to every region's Bitmap Projector, flipping those seat bits from 0 to 1 in Redis worldwide within ~1–2 s.
  6. 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-7 simultaneously? 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_ids in 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 ~50 candidate pairs and pick randomly among equal-tier pairs (or use SELECT ... FOR UPDATE SKIP LOCKED inside the shard).

    2. General Admission sections (32 sharded 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 into 32 buckets boosts cross-region commit throughput from ~37/s to ~1,184/s. When total remaining capacity drops below 64 tickets, a lightweight background task coalesces residual counts into bucket_id = 0 so a group buying 4 tickets never fails when 1 ticket sits in four separate buckets.

  7. 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 running
    

    We 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 /holds checks OR (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 emits outbox events so regional seat maps turn green again.
    • GA sections: Every 15 s, the sweeper flips expired ACTIVE GA holds (UPDATE holds SET status = 'EXPIRED' WHERE status = 'ACTIVE' AND expires_at < now() RETURNING bucket_id, qty) and adds qty back to ga_buckets in 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:59 payment-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:

    1. Lock hold for payment (Shard Tx 1): Verify using DB now() that the hold is still ACTIVE and expires_at > now(), create orders (PENDING_PAYMENT, hold_id UNIQUE), and atomically transition holds to CHECKING_OUT and seats to PAYMENT_PENDING (WHERE hold_id = :hold_id AND status = 'HELD' AND hold_expires_at > now()), extending expires_at by +5 minutes. Now neither a rival POST /holds (which only reclaims expired HELD rows, never PAYMENT_PENDING rows!) nor the GA sweeper (which only reclaims ACTIVE holds!) can steal the tickets while the bank processes the card at 9:59!
    2. External payment authorize: Call the payment gateway with idempotency_key = order_id and a 10 s socket timeout. Crucial rule: an HTTP timeout means unknown, never declined — query the gateway's status by order_id before releasing anything.
    3. Commit the sale (Shard Tx 2): In one atomic shard commit, flip holds (CHECKING_OUT -> CONVERTED), flip seats (PAYMENT_PENDING -> SOLD), insert VALID tickets rows, mark orders CONFIRMED, and append the outbox confirmation event. (Then asynchronously capture the authorized funds with the same idempotency key.)
    4. Clean compensation on decline or stuck payment: If the card is explicitly declined and now() < original_expires_at, revert holds to ACTIVE and seats to HELD with original_expires_at so the fan can try a second card in their remaining window; if now() >= original_expires_at, immediately mark EXPIRED and free the seats/GA bucket in the same transaction. If a payment stays unknown past the +5 min grace window, the sweeper voids/cancels the authorization by order_id and releases inventory only after the void is confirmed.
  8. 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_at receives an HMAC-signed queue_token containing a uniformly generated random 64-bit lottery rank; fans arriving after on_sale_at get sequential numbers behind the pre-drop cohort. Neither hammering refresh nor having a 1 ms bot ping grants an earlier spot.
    • Collapsing 133,000 polls/sec to near-zero origin load: Waiting clients poll GET /queue/status, which returns a tiny JSON {admitted_through_pos: 18400} cached at CDN edges with TTL = 1 s. Every client computes my_pos - admitted_through_pos locally! An adaptive admission controller adjusts the admission rate every 5 s based 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 Redis 7.5 KB bitmaps (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-1 simultaneously will double-sell it before replication converges.
    • Option B (3-AZ quorum in the home region) commits in ~2 ms and satisfies surviving a partial regional data-center (AZ) outage. However, if all of us-east-1 goes dark, promoting an asynchronous us-west-2 replica risks reselling seats committed in the final seconds before the crash — meaning Option B must pause sales for us-east-1 events during a full regional outage.
    • Our choice — Option C (2 + 2 + 1 consensus replicas across 3 regions on the same continent, leader pinned to the home region): With 2 replicas in us-east-1 (across 2 AZs), 2 in us-east-2, and 1 witness/replica in us-central-1 (CockroachDB / Spanner style), any commit needs 3 of 5 acknowledgments (~27 ms). Because the waiting room throttles writes to ~70/s and GA sections use 32 buckets, 27 ms is effortless — and if either an AZ or all of us-east-1 vanishes, the remaining 3 replicas already hold every single committed ticket and elect a new leader in us-east-2 within seconds with zero overselling and zero lost orders.
  9. Scaling bottlenecks, failure modes, and trade-off summary

    • Scaling mega-events (100,000+ festival passes): Pre-split hot event_id ranges onto dedicated bare-metal consensus nodes before on_sale_at. If a single festival needs >5,000 writes/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-room admitted_through_pos watermark is replicated, and HMAC-signed queue_token/admission_token cookies verify statelessly in the failover region; clients safely retry in-flight holds/checkouts with their Idempotency-Key.
      • Redis / CDN / OpenSearch outage: Seat maps degrade gracefully or stale slightly (409 protects 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) and SUM(ga_buckets) + SUM(live GA holds) + COUNT(VALID GA tickets) == section.capacity.
    • 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,000x lower write contention; 1–2 s stale 7.5 KB bitmaps protect strongly consistent inventory leaders; and 2+2+1 cross-region consensus trades +25 ms on rare booking writes for zero-oversell regional disaster recovery.

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:

  1. 10:00:00 (Race on POST /holds): Admitted fans Alice and Bob click A-1 at the exact same millisecond. Both requests route to the event's home-region database shard leader; Alice's conditional UPDATE seats SET status = 'HELD', hold_expires_at = 10:10:00 WHERE status = 'AVAILABLE' commits first, so Bob's UPDATE matches 0 rows and immediately returns 409 Conflict, refreshing his seat map.
  2. 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 clicks A-1 and her UPDATE succeeds inline because status = 'HELD' AND hold_expires_at < now(), assigning hold_id = H2 until 10:20:02.
  3. 10:19:55 (Protecting an in-flight payment): Carol clicks Pay (Idempotency-Key: K9). Checkout Step 1 atomically flips H2 to CHECKING_OUT and A-1 to PAYMENT_PENDING with a +5 min grace deadline (10:25:02), blocking any rival hold from stealing A-1 at 10:20:02 while the card network responds.
  4. 10:19:57 (Atomic sale + global bitmap fan-out): Card authorization succeeds; Checkout Step 3 atomically flips A-1 to SOLD, inserts a VALID ticket row, and writes a transactional outbox row (an event written inside the same DB commit) that updates 7.5 KB regional 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 the POST /holds query 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. Only seats, ga_buckets, holds, orders, and tickets go through consensus quorum commits. Serving GET /availability from regional 7.5 KB Redis/CDN bitmaps shields the database from 2,000 : 1 read spikes, trading occasional 409 Conflict clicks 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 ms and 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 (majority 3 of 5 agreement) across 3 regions on the same continent adds ~25 ms per 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 across 32 rows lifts cross-region throughput from ~37 to ~1,184 holds/sec, trading exact single-row simplicity for background bucket rebalancing when fewer than 64 tickets 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_PENDING states and timeout reconciliation, in exchange for never holding database locks across slow third-party HTTP calls.

Common mistakes

  • Application-level check-then-act (SELECT status followed by UPDATE). Without an atomic WHERE status = 'AVAILABLE' condition (or row lock), two concurrent threads both read AVAILABLE and 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 sort seat_ids canonically before executing UPDATE.
  • 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 TTL expiration 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:59 payment-in-flight race (especially on GA sections). If a user starts paying at 9:58 and the hold stays ACTIVE / HELD with a 10:00 expiry, a rival buyer or the GA sweeper reclaims the tickets at 10:00 right before the card charge succeeds! Moving the hold to CHECKING_OUT / PAYMENT_PENDING with a +5 min grace 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/s across regions).
  • Skipping a database-level uniqueness backstop. Always enforce a partial unique index UNIQUE (event_id, seat_id) WHERE status = 'VALID' on tickets so 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 /checkout immediately returns 202 Accepted asynchronously, 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 original Idempotency-Key = order_id and jittered backoff so no buyer is double-charged. At the same time, dynamically extend the PAYMENT_PENDING grace lease (say from +5 to +10 minutes) 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 fresh PENDING_PAYMENT orders 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 CONCURRENTLY or gh-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 by event_id behind 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 single event_id for 1–3 seconds while 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 1 waiting-room slot and 1 active hold (<= 8 seats) per account in the database, and bind single-use HMAC admission_tokens to 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

Similar questions

More Addepar interview questions

All 3 Addepar questions →