Skip to content

Lesson 37 of 38Case studies

Design Ticketmaster

Design a ticketing system that holds seats for ten minutes, survives a 10 million user on-sale, and never sells the same seat twice.

22 min read0/5 questions

Most systems in this course are hard because of volume: billions of links, trillions of messages. Ticketing is hard for the opposite reason. There are only 50,000 seats in the stadium, and ten million people want them in the same five minutes. Every one of those people is trying to write to the same few thousand rows, and if two of them win the same seat you have a customer at the gate with a ticket that does not work. This is the case study where contention, not size, drives every decision.

We will follow the usual framework: requirements, numbers, API, data model, high-level design, deep dives, then bottlenecks and scale.

Requirements

Functional

  • Browse and search events by artist, venue, city, and date.
  • View an event's seat map with live availability.
  • Pick seats and hold them for about 10 minutes while you pay.
  • Pay, receive tickets, and see them in your account.
  • Release the seats automatically if you walk away or the hold runs out.

Non-functional

  • Never double book. One seat, one ticket. This beats latency and availability every time.
  • Survive an on-sale spike: 10 million users arriving for one popular event.
  • Browsing stays fast and available even when booking is overloaded.
  • Fair: real fans should beat bots, and the order people get in should feel defensible.

Out of scope: resale marketplaces, dynamic pricing, venue management tools, and the ticket scanning app at the gate.

Back-of-the-envelope numbers

Two very different workloads hide in this system: everyday browsing, and the on-sale spike.

QuantityMathResult
Everyday page views100M a day / 86,400about 1,200/s, mostly cacheable
On-sale arrivals10M users in about 10 minutesabout 17,000 new users/s
Seat map polling10M users × 1 request every 5 sabout 2M requests/s if unprotected
Seats for saleone stadiumabout 50,000 rows
Orders possible50,000 seats / about 4 seats per orderabout 12,500 successful buyers

Look at the last two rows next to the others. The data fits in memory on a laptop. But 99.9% of the people who show up will leave without a ticket, and if they all reach the booking database at once, nobody gets a ticket because the database falls over. The design job is to keep load away from those 50,000 rows and to make the few writes that do reach them correct.

API

GET  /v1/events?q=taylor&city=london          -> search results
GET  /v1/events/evt42                          -> event details (CDN cached)
GET  /v1/events/evt42/seats                    -> seat map with availability (short cache)
GET  /v1/events/evt42/availability/stream      -> SSE stream of seat changes
 
POST /v1/events/evt42/holds
Authorization: Bearer <session>
X-Queue-Token: <signed admission token>
{ "seat_ids": ["A1", "A2"] }
 
201 Created
{ "hold_id": "h_9f2", "expires_at": "2026-10-22T19:10:00Z" }
409 Conflict   (one of the seats is taken; nothing is held)
 
POST /v1/holds/h_9f2/checkout
Idempotency-Key: h_9f2-attempt
{ "payment_method": "pm_1Q2w" }
 
DELETE /v1/holds/h_9f2                         -> release early

A hold covers all requested seats or none. Telling a group of four that they got three seats is worse than telling them to try again.

Data model

CREATE TABLE seats (
  event_id   BIGINT      NOT NULL,
  seat_id    TEXT        NOT NULL,          -- "SEC104-ROW-F-12"
  section    TEXT        NOT NULL,
  price_tier SMALLINT    NOT NULL,
  status     TEXT        NOT NULL DEFAULT 'available',  -- available | held | booked
  hold_id    TEXT,
  held_until TIMESTAMPTZ,
  booking_id BIGINT,
  version    INT         NOT NULL DEFAULT 0,
  PRIMARY KEY (event_id, seat_id)
);
 
CREATE TABLE bookings (
  booking_id BIGINT PRIMARY KEY,
  event_id   BIGINT NOT NULL,
  user_id    BIGINT NOT NULL,
  payment_id TEXT   NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL
);
 
CREATE TABLE tickets (
  event_id   BIGINT NOT NULL,
  seat_id    TEXT   NOT NULL,
  booking_id BIGINT NOT NULL REFERENCES bookings,
  PRIMARY KEY (event_id, seat_id)           -- the last line of defense
);

Everything starts with event_id, so a single event's rows live together on one shard. The tickets primary key is a safety net: even if every layer above has a bug, the database will refuse to issue a second ticket for (evt42, A1).

Events, venues, and performers live in a separate catalog database. They change rarely and are read constantly, which makes them perfect for a CDN and a search index.

High-level design

Ticketing architecture
Protected zoneFanFanCDN: event pagesCDNevent pagesWaiting room: admits N/minWaiting roomadmits N/minAPI gateway: checks tokenAPI gatewaychecks tokenCatalog: search indexCatalogsearch indexBooking svc: holds, checkoutBooking svcholds, checkoutAvailability: Redis + SSEAvailabilityRedis + SSESeats DB: by event_idSeats DBby event_idPayment svc: PSPPayment svcPSPbrowsejoin queuesigned tokentoken + requestconditional updateauthorizechangesSSE

Browsing. Event pages and search results come from the CDN and the catalog's search index. None of it touches the seats database.

1/7

Notice the shape: the expensive, contended part (the purple zone) is small, and everything in front of it exists to protect it.

Deep dive 1: holding a seat without double booking

Two fans click seat A1 within the same millisecond. Exactly one must win. You have four common options, and interviewers like to hear you compare them.

Pessimistic locking. Inside a transaction, SELECT ... FROM seats WHERE event_id = ? AND seat_id = ANY(?) FOR UPDATE, check they are all available, update them, commit. The second fan's transaction waits on the row lock, then sees held and fails. Correct, but every waiting transaction holds a database connection while it waits. With thousands of fans on the same popular section, connections pile up behind a few locks. The rule that matters: never hold a lock across user think time. The lock lasts milliseconds; the 10 minute hold is data, not a lock.

For "best available" seating, where the fan does not pick a seat, FOR UPDATE SKIP LOCKED LIMIT 4 is the trick: each request skips rows another transaction is already grabbing, so concurrent buyers spread out instead of queueing on the same rows.

Optimistic concurrency. Read the seat and its version, then UPDATE seats SET status = 'held', version = version + 1 WHERE seat_id = ? AND version = ?. Zero rows changed means someone beat you. No locks are held while you think, which is great under low contention. Under on-sale contention, most attempts lose and retry, so the database does a lot of wasted work.

A status column with held_until. Fold the check into one atomic statement, and treat an expired hold as available in the query itself. No cron job has to sweep expired holds first: the next buyer's WHERE clause does it. Run this simulation of two fans and one seat.

Pythonseat_hold.py
import sqlite3 db = sqlite3.connect(":memory:")db.execute("""CREATE TABLE seats ( event_id TEXT, seat_id TEXT, status TEXT NOT NULL DEFAULT 'available', holder TEXT, held_until INTEGER, PRIMARY KEY (event_id, seat_id))""")db.execute("INSERT INTO seats (event_id, seat_id) VALUES ('evt42', 'A1')") HOLD_SECONDS = 600 def hold(user, now): # One atomic statement: take the seat if it is free OR its hold has expired. cur = db.execute(""" UPDATE seats SET status = 'held', holder = ?, held_until = ? WHERE event_id = 'evt42' AND seat_id = 'A1' AND (status = 'available' OR (status = 'held' AND held_until < ?))""", (user, now + HOLD_SECONDS, now)) return cur.rowcount == 1 def confirm(user, now): # Only the current, unexpired holder may book. cur = db.execute(""" UPDATE seats SET status = 'booked' WHERE event_id = 'evt42' AND seat_id = 'A1' AND status = 'held' AND holder = ? AND held_until >= ?""", (user, now)) return cur.rowcount == 1 print("t=0 ana holds: ", hold("ana", 0))print("t=100 ben holds: ", hold("ben", 100))print("t=700 ben holds: ", hold("ben", 700), "(ana's hold expired at 600)")print("t=710 ana confirms:", confirm("ana", 710), "-> void ana's card authorization")print("t=720 ben confirms:", confirm("ben", 720))print(db.execute("SELECT status, holder FROM seats").fetchone())
Output
Press Run (⌘ Enter) to see what happens.

Check rowcount, never a separate SELECT followed by an UPDATE. Read-then-write in two statements is the classic race: both fans read available, both write held, and the last write wins silently. You still want a background job that resets stale held rows to available, but only so the seat map looks right. Correctness never depends on it.

A Redis hold in front of the database. SET hold:evt42:A1 user123 NX EX 600 sets the key only if it does not exist (NX) and expires it after 600 seconds (EX). Redis answers in well under a millisecond and expiry is built in, so it absorbs the stampede. For several seats at once, use a Lua script so the all-or-nothing check runs atomically. The catch: Redis replication is asynchronous, so a failover can lose a hold, and two fans can each believe they hold A1. That is acceptable only if the database stays the source of truth: the final booking is a conditional update plus the tickets primary key, so the loser of that rare race gets a clear error at checkout instead of a duplicate ticket.

Quick check
Holds expire after 10 minutes. A cron job runs every minute to set expired holds back to available. What goes wrong if correctness depends on that job?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

What does this print?

seats = {"A1": None}

def hold(seat, user):
  if seats[seat] is None:
      seats[seat] = user
      return True
  return False

results = [hold("A1", u) for u in ["ana", "ben", "ana"]]
print(results.count(True), seats["A1"])
Need a nudge? Hints walk you through it.

The seat state machine

A seat has three states. Every move between them is a conditional update that names the state it expects to come from, which is the same guard you saw for payments.

Seat lifecycle
availableheldbookedholdexpire / releasepayrefund

currentwaitingdone

Every seat starts available. The only legal move is hold.

1/5

Deep dive 2: the virtual waiting room

No amount of database tuning lets 50,000 rows absorb 2 million requests a second. The fix is to stop most of those requests from existing. A virtual waiting room sits in front of the booking flow for hot events and turns a stampede into a steady stream.

How it works:

  1. When a fan opens the event during the on-sale, they get a queue position instead of the seat map. Fans who arrived in the minutes before the start are often shuffled randomly, so refreshing at 09:59:59 is not an advantage. After that it is first come, first served.
  2. The queue page polls a cheap endpoint (or holds an SSE connection) for its position. This endpoint is served from a separate, horizontally scaled tier, often at the CDN edge, and never touches booking.
  3. An admission controller lets N users per minute through. N is set from what the booking service can handle, and it adapts: if seats are selling out, admit more slowly; when holds expire, admit a few more.
  4. An admitted fan receives a signed token: an HMAC or JWT containing user_id, event_id, and an expiry. The gateway verifies the signature locally, so checking a token costs no database read. A token copied to another account fails, because the user inside it does not match the session.

The waiting room is also your fairness story. Everyone sees a position and an estimated wait, and the system can stop admitting the moment the event sells out instead of letting a million people discover it one 409 at a time.

Deep dive 3: the read path and live availability

Admitted fans want to see which seats are still free. The seat map has two parts with very different change rates.

  • Static layout: sections, rows, coordinates, prices. It changes when the venue changes. Serve it from the CDN with a long cache life.
  • Availability: which seats are free right now. Keep it as a compact structure per event in Redis, such as a bitmap or one hash per section, updated whenever a seat changes state. API reads hit this, with a TTL of a second or two if it is built from the database.

Polling every few seconds multiplied by thousands of admitted users still adds up, so push changes instead. Each admitted client opens a Server-Sent Events stream. The server batches seat changes and sends one small message per second, like {"held": ["A1","A2"], "available": ["C7"]}. SSE fits well here: it is one-way, runs over ordinary HTTP, and reconnects automatically. Push only to admitted users, not to the millions in the queue.

The map will always be slightly stale. That is fine, because the hold query is the real check. A fan who clicks a seat that was taken half a second ago gets a quick 409 and a refreshed map.

Deep dive 4: payment and the expired hold

The checkout has to coordinate two systems that cannot share a transaction: your seats database and the payment provider. Get the order wrong and you either charge people for seats they do not get, or give away seats nobody paid for.

The safe order uses the authorize then capture split from the payments case study:

Put it in order5 steps

Put a safe checkout in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Now the classic follow-up: what if payment succeeds after the hold has expired? Ana's bank takes 40 seconds to approve 3-D Secure, her hold ends during that time, and Ben grabs the seat. When Ana's authorization returns, the confirm step finds held_until in the past or holder = ben, updates zero rows, and Ana's authorization is voided. You saw exactly this in the simulation above.

Two refinements make it rarer and kinder:

  • Extend on checkout. When the fan submits payment, move the hold to a payment_pending state with a short extension, say two extra minutes, using a conditional update that only succeeds if they still hold it. Most bank delays then finish inside the window.
  • Handle the leftovers. If a provider sends a late success webhook for a checkout you already gave up on, and the money was captured, refund automatically and tell the user. A reconciliation job, as in the payments lesson, catches anything the webhook path missed.
Quick check
Your checkout captures the payment first, then marks the seats booked. Under load, the seat update sometimes fails. What is the right fix?
Need a nudge? A hint rules out a wrong answer.

Bots, fairness, and limits

On-sales attract bots that buy seats for resale. You cannot stop them completely, but you can make each layer expensive for them.

  • At the queue: a CAPTCHA or proof-of-work challenge on entry, device and browser checks, and one queue position per account.
  • Signed tokens tied to the account and event, with short expiry, so a bot farm cannot reuse one admission across many sessions.
  • Rate limits per account, per IP range, and per payment card on the hold and checkout endpoints, using the token bucket from the rate limiting lesson.
  • Per-account limits enforced in the database, such as a maximum of four tickets per account per event, checked inside the booking transaction.
  • Verified presales: fans register days in advance and are vetted, which moves the bot fight away from the busiest minute.

Bottlenecks, failures, and 10x scale

  • Shard by event_id. All of one event's seats live on one shard, so a hold for four seats is a single-shard transaction. Different events spread across shards.
  • The hot event is one shard, and that is fine. 50,000 rows are tiny. The danger is request rate, and the waiting room controls request rate. Size the admission rate to what one shard can do with headroom, and give the biggest events their own dedicated shard.
  • Redis failure. If the hold cache dies, fall back to database holds and slow admission down. Never fall back to "skip the check".
  • Search across events, artists, and venues runs on an inverted index fed by change data capture from the catalog. See the Search and Inverted Indexes lesson for how that index works.
  • 10x (100 million fans for a global tour): run waiting rooms per region, split the tour into separate on-sale windows per city, and scale the edge tier. The booking core barely changes, because the waiting room keeps its load constant no matter how many people arrive.
Match the pairs0/5 matched

Match each technique to the problem it solves.

Choose an item, then its match on the other side.

Ticketing is a fitting place to finish the case studies, because it needs almost every block at once: a CDN and a waiting room at the edge, rate limits, a cache in front of a strongly consistent database, payments, and queues behind it. The wrap-up that follows takes that habit of combining blocks and walks one more design from first question to last trade-off.

Key terms
seat hold
A temporary claim on a seat, stored as data with an expiry time, so the fan can pay without anyone else taking it.
conditional update
An UPDATE whose WHERE clause includes the expected current state, so it changes zero rows if someone else got there first.
virtual waiting room
A queue in front of a hot flow that admits users at a controlled rate and hands each one a signed admission token.
SKIP LOCKED
A row-locking option that skips rows already locked by other transactions, so concurrent workers grab different rows.
optimistic concurrency
Detecting conflicts at write time with a version check instead of locking rows while a user decides.
authorize then capture
Holding the money first and only taking it after the order is confirmed, so a failed confirmation can be voided.
Server-Sent Events
A one-way HTTP stream from server to browser, used here to push seat availability changes.