TExcelTAD
Home › System Design › System Design Mini Project

System Design Mini Project

In this project you'll design a concert ticketing system and build a working simulation of it, step by step. Ticket sales are a great system design exercise because they combine a flash crowd (everyone arrives at 10:00:00), scarce inventory that must never be oversold, payments that can fail, and a read-heavy event page.

The plan:

  1. Requirements and estimates
  2. An inventory service that can't oversell, with expiring holds
  3. A virtual waiting room that admits fans at a safe rate
  4. Checkout as a saga with idempotent payments
  5. Caching the event page during the rush
  6. The full simulation, with a metrics report

Every step is a complete program. All randomness comes from random.Random(42) and time is a simulated clock in seconds, so your output will match the one shown.

Step 1: Requirements and estimates

Functional: browse an event page, join the sale, hold seats for a few minutes, pay, receive tickets. Non-functional: never sell a seat twice; stay up under a 100x traffic spike; fair (first come, first served, roughly); a held seat returns to the pool if the fan doesn't pay.

python · try it yourself
fans = 2_000_000                # people who show up for a stadium tour
seats = 60_000
arrival_window_s = 120           # most fans arrive in the first two minutes
page_loads_per_fan = 20          # refreshes while waiting
checkout_s = 180                 # time a fan needs to pay
app_server_rps = 2_000

arrivals_per_s = fans / arrival_window_s
page_rps = arrivals_per_s * page_loads_per_fan
print(f"arrivals: {arrivals_per_s:,.0f} fans/s, page loads: {page_rps:,.0f}/s")
print(f"servers to render pages without caching: {page_rps / app_server_rps:,.0f}")

# How fast can we usefully admit fans? Enough to keep checkouts busy, no more.
concurrent_checkouts = 5_000
admit_rate = concurrent_checkouts / checkout_s            # Little's law: L = λ W
print(f"admit {admit_rate:.0f} fans/s -> sell-out in about {seats / admit_rate / 60:.0f} minutes")
print(f"fans per seat: {fans / seats:.0f}")
arrivals: 16,667 fans/s, page loads: 333,333/s
servers to render pages without caching: 167
admit 28 fans/s -> sell-out in about 36 minutes
fans per seat: 33

The numbers already shape the design. The page must be served from a cache or CDN (167 servers for a static page is silly). And since there are 33 fans per seat, most of them will be disappointed no matter what: the system's job is to be correct and fair, not to admit everybody at once. A waiting room admitting ~28 fans per second keeps the checkout tier at a comfortable load.

text
fans -> CDN (event page) -> waiting room (queue + admission rate) -> checkout API
                                                                       |-> inventory service (holds, atomic)
                                                                       |-> payment service (idempotent)
                                                                       '-> ticket issuing (async, queue)

Step 2: Inventory without overselling

The inventory service owns the seats. A hold reserves seats for a fan for a limited time; paying converts the hold into a sale; an expired hold returns its seats. The check-and-decrement must be atomic: in a real database that's UPDATE ... SET available = available - 2 WHERE available >= 2, or a Redis Lua script. Here a single-threaded method plays that role.

python · try it yourself
class Inventory:
    def __init__(self, seats, hold_seconds=180):
        self.available, self.sold = seats, 0
        self.holds = {}                         # hold id -> (fan, count, expires_at)
        self.hold_seconds = hold_seconds
        self.next_hold = 1

    def expire(self, now):
        for hold_id, (fan, count, expires) in list(self.holds.items()):
            if expires <= now:
                del self.holds[hold_id]
                self.available += count         # seats go back to the pool

    def hold(self, fan, count, now):
        self.expire(now)
        if count > self.available:              # atomic check-and-decrement
            return None
        self.available -= count
        hold_id = f"H{self.next_hold}"
        self.next_hold += 1
        self.holds[hold_id] = (fan, count, now + self.hold_seconds)
        return hold_id

    def confirm(self, hold_id, now):
        self.expire(now)
        if hold_id not in self.holds:
            return False                        # too late: the hold expired
        fan, count, _ = self.holds.pop(hold_id)
        self.sold += count
        return True

inv = Inventory(seats=5)
h1 = inv.hold("ana", 2, now=0)
h2 = inv.hold("ben", 2, now=10)
h3 = inv.hold("cara", 2, now=20)              # only 1 seat left
print("holds:", h1, h2, h3, "| available:", inv.available)
print("ana pays at t=100:", inv.confirm(h1, now=100))
print("ben pays at t=200 (expired at 190):", inv.confirm(h2, now=200))
h4 = inv.hold("cara", 2, now=200)             # ben's seats came back
print("cara retries:", h4, "| available:", inv.available, "| sold:", inv.sold)
holds: H1 H2 None | available: 1
ana pays at t=100: True
ben pays at t=200 (expired at 190): False
cara retries: H3 | available: 1 | sold: 2

Every seat is either available, held, or sold, and the totals always add up to 5. Ben was too slow, so his seats went to Cara.

Step 3: The virtual waiting room

Instead of letting 2 million fans hammer the checkout API, the waiting room gives each fan a queue position on arrival and lets them through at a fixed rate with a token bucket. Fans who arrived earlier are admitted earlier.

python · try it yourself
import random
from collections import deque

class WaitingRoom:
    def __init__(self, admit_per_s, burst):
        self.queue, self.rate, self.capacity = deque(), admit_per_s, burst
        self.tokens, self.last = burst, 0.0

    def join(self, fan, now):
        self.queue.append((fan, now))
        return len(self.queue)                    # position shown to the fan

    def admit(self, now):
        self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        admitted = []
        while self.queue and self.tokens >= 1:
            self.tokens -= 1
            admitted.append(self.queue.popleft())
        return admitted

rng = random.Random(42)
room = WaitingRoom(admit_per_s=5, burst=5)
arrivals = sorted(rng.uniform(0, 3) for _ in range(40))     # 40 fans within 3 seconds
waits, i = [], 0
for tick in range(12):                                       # one tick per second
    now = float(tick)
    while i < len(arrivals) and arrivals[i] <= now:
        room.join(f"fan{i}", arrivals[i])
        i += 1
    for fan, joined_at in room.admit(now):
        waits.append(now - joined_at)
    print(f"t={tick:2}s queue length {len(room.queue):2}, admitted so far {len(waits):2}")
print(f"first fan waited {waits[0]:.1f}s, last fan waited {waits[-1]:.1f}s")
t= 0s queue length  0, admitted so far  0
t= 1s queue length  8, admitted so far  5
t= 2s queue length 17, admitted so far 10
t= 3s queue length 25, admitted so far 15
t= 4s queue length 20, admitted so far 20
t= 5s queue length 15, admitted so far 25
t= 6s queue length 10, admitted so far 30
t= 7s queue length  5, admitted so far 35
t= 8s queue length  0, admitted so far 40
t= 9s queue length  0, admitted so far 40
t=10s queue length  0, admitted so far 40
t=11s queue length  0, admitted so far 40
first fan waited 1.0s, last fan waited 5.1s

The burst of 40 fans is spread into a steady 5 per second. In production, the queue position lives in a signed token (so a refresh doesn't lose your place) and the waiting page is a static file on the CDN that polls a lightweight status endpoint.

Step 4: Checkout as a saga with idempotent payments

Checkout spans two services: inventory (hold → confirm) and payments. There is no transaction across both, so we use a saga: hold seats, charge the card, confirm the hold; if the charge fails, compensate by releasing the hold. The payment call carries an idempotency key, so a retried request after a timeout never charges twice.

python · try it yourself
class Payments:
    def __init__(self):
        self.charged, self.results = [], {}

    def charge(self, key, fan, amount, outcome):
        if key in self.results:                       # idempotent replay
            return self.results[key]
        if outcome == "declined":
            result = "declined"
        else:
            self.charged.append((fan, amount))
            result = "ok"
        self.results[key] = result
        if outcome == "timeout":                      # charged, but the response is lost
            raise TimeoutError
        return result

class Inventory:
    def __init__(self, seats):
        self.available, self.sold, self.holds = seats, 0, {}

    def hold(self, fan, n):
        if n > self.available:
            return None
        self.available -= n
        self.holds[fan] = n
        return fan

    def release(self, hold):
        self.available += self.holds.pop(hold)

    def confirm(self, hold):
        self.sold += self.holds.pop(hold)

inv, pay = Inventory(seats=6), Payments()

def checkout(fan, seats, outcome):
    hold = inv.hold(fan, seats)
    if not hold:
        return "sold out"
    key = f"checkout-{fan}"                            # one key per checkout, reused on retries
    for attempt in range(3):
        try:
            result = pay.charge(key, fan, 50 * seats, outcome if attempt == 0 else "ok")
            break
        except TimeoutError:
            continue
    if result != "ok":
        inv.release(hold)                              # compensation
        return f"payment {result}, seats released"
    inv.confirm(hold)
    return "tickets issued"

for fan, seats, outcome in [("ana", 2, "ok"), ("ben", 2, "declined"), ("cara", 2, "timeout"),
                            ("dev", 2, "ok"), ("eli", 2, "ok")]:
    print(f"{fan:<5} {checkout(fan, seats, outcome)}")
print("charges:", pay.charged)
print("sold:", inv.sold, "available:", inv.available)
ana   tickets issued
ben   payment declined, seats released
cara  tickets issued
dev   tickets issued
eli   sold out
charges: [('ana', 100), ('cara', 100), ('dev', 100)]
sold: 6 available: 0

Cara's first response was lost, the retry replayed the stored result, and she was charged exactly once. Ben's declined card released his seats, which Dev then bought.

Step 5: Caching the event page

Thousands of fans refresh the event page every second. Its content (artist, venue, price levels, "few tickets left") changes rarely, so a cache with a short TTL absorbs almost all of it. Only the remaining-seats indicator needs to be fresh-ish, and a few seconds of staleness is fine.

python · try it yourself
import random

class PageCache:
    def __init__(self, ttl):
        self.ttl, self.value, self.expires = ttl, None, -1.0
        self.hits = self.misses = 0

    def get(self, now, render):
        if now < self.expires:
            self.hits += 1
            return self.value
        self.misses += 1                       # one render per expiry (request coalescing)
        self.value, self.expires = render(now), now + self.ttl
        return self.value

rng = random.Random(42)
requests = sorted(rng.uniform(0, 60) for _ in range(50_000))   # 50k page loads in a minute

for ttl in [0, 1, 5]:
    cache = PageCache(ttl)
    for t in requests:
        cache.get(t, render=lambda now: f"<page rendered at {now:.0f}s>")
    total = cache.hits + cache.misses
    print(f"TTL {ttl}s: {cache.misses:6,} renders, hit ratio {cache.hits / total:6.2%}")
TTL 0s: 50,000 renders, hit ratio  0.00%
TTL 1s:     60 renders, hit ratio 99.88%
TTL 5s:     12 renders, hit ratio 99.98%

With a 1-second TTL the origin renders the page about 60 times a minute instead of 50,000 times. Combined with a CDN in front, the event page is no longer a scaling problem at all.

Step 6: The full simulation

Now we wire everything together: 3,000 fans arrive in a burst for 500 seats; the waiting room admits 20 per second; each admitted fan holds 1-4 seats, takes a random time to pay, and some cards are declined or abandoned. Holds expire after 60 seconds. The report checks the property that matters most: no overselling.

python · try it yourself
import random
from collections import deque

rng = random.Random(42)
SEATS, FANS, ADMIT_PER_S, HOLD_S = 500, 3_000, 20, 60

available, sold = SEATS, 0
holds = {}                               # fan -> (seats, expires_at, pays_at, outcome)
queue = deque(sorted((rng.uniform(0, 30), f"fan{i}") for i in range(FANS)))
waiting, admitted = deque(), []
stats = {"declined": 0, "abandoned": 0, "expired": 0, "orders": 0}

for t in range(0, 600):
    while queue and queue[0][0] <= t:                     # arrivals join the waiting room
        waiting.append(queue.popleft())
    for _ in range(min(ADMIT_PER_S, len(waiting))):       # admission at a fixed rate
        if available == 0:
            break                       # everything is held: pause until holds are paid or expire
        joined, fan = waiting.popleft()
        admitted.append(t - joined)
        want = min(rng.randint(1, 4), available)
        available -= want
        outcome = rng.choices(["ok", "declined", "abandon"], weights=[85, 5, 10])[0]
        holds[fan] = (want, t + HOLD_S, t + rng.randint(15, 70), outcome)
    for fan, (n, expires, pays_at, outcome) in list(holds.items()):
        if t >= expires:                                  # too slow or walked away
            del holds[fan]
            available += n
            stats["expired" if outcome == "ok" else "abandoned"] += 1
        elif t == pays_at and outcome != "abandon":
            del holds[fan]
            if outcome == "ok":
                sold += n
                stats["orders"] += 1
            else:
                available += n
                stats["declined"] += 1
    assert sold + available + sum(h[0] for h in holds.values()) == SEATS   # invariant
    if sold == SEATS:
        print(f"sold out at t={t}s")
        break

admitted.sort()
print(f"seats sold: {sold}/{SEATS} (oversold: {max(0, sold - SEATS)})")
print(f"orders: {stats['orders']}, declined: {stats['declined']}, "
      f"abandoned: {stats['abandoned']}, slow payers expired: {stats['expired']}")
print(f"fans admitted: {len(admitted)}, still in the queue at sell-out: {len(waiting) + len(queue)}")
print(f"waiting-room time: median {admitted[len(admitted) // 2]:.0f}s, max {admitted[-1]:.0f}s")
sold out at t=297s
seats sold: 500/500 (oversold: 0)
orders: 223, declined: 17, abandoned: 28, slow payers expired: 51
fans admitted: 319, still in the queue at sell-out: 2681
waiting-room time: median 6s, max 275s

The invariant sold + available + held == SEATS is checked on every tick, and the report confirms zero overselling. Whenever every remaining seat was held, admission paused instead of letting in fans who would find nothing; abandoned holds and slow payers' expired holds flowed back into the pool and went to the next fans in line. The sale sold out after about five minutes, and the 2,681 fans still queued can be told immediately rather than waiting forever.

What you built, and where to go next

Requirement Mechanism in the design
Survive the flash crowd CDN + cached event page, waiting room with token-bucket admission
Never oversell Atomic holds in one inventory service, invariant checks
Fairness FIFO queue positions in the waiting room
Payments that fail or time out Saga with compensation, idempotency keys
Seats not stuck forever Expiring holds

Extensions to try:

  • Seat maps: instead of a counter, hold specific seats (UPDATE seats SET hold = ? WHERE id IN (...) AND hold IS NULL). What changes for contention?
  • Sharding inventory: split a 60,000-seat stadium into sections owned by different shards. How do you keep "best available" fast?
  • Bots: add a per-account and per-IP rate limiter in front of the waiting room, and a cap of 4 tickets per account.
  • Failures: make the inventory service crash at t=30 and recover with its holds from a write-ahead log.

Test yourself

Why does the design admit fans through a waiting room at a fixed rate?

  1. To sell tickets more slowly on purpose
  2. To keep the checkout and inventory tiers at a safe load and serve fans in arrival order
  3. Because CDNs require it
  4. To avoid caching

What guarantees that no seat is sold twice in the simulation?

  1. The CDN
  2. Atomic check-and-decrement holds in a single inventory owner, checked by an invariant
  3. The payment service
  4. Random arrival times

In the checkout saga, what happens when a card is declined?

  1. The order is kept anyway
  2. The hold is released as a compensating action
  3. The fan is charged twice
  4. The inventory is reset