Skip to content
Katabench
Try free
10 min read The Katabench team

Design a ticketing system: holds, queues, flash sales

Design a ticketing system where 64 buyers cannot get 44 tickets for 20 seats: one conditional write per hold, and a confirm that sells a whole order or nothing.

Forty-four tickets for twenty seats. That was the result of pointing 64 concurrent buyers at a common first checkout on PostgreSQL 17: read the seat, and if it says available, mark it sold and issue a ticket. Three or four buyers wanted each seat, and seat A-0003 sold four times, because a read shows the state of a seat without claiming it, and in a flash sale everyone arrives in the same second wanting the same rows.

Fixing that is one of three separate problems. Something has to limit how many people reach the seat tables at once, each seat needs one owner while payment happens elsewhere, and the seat map has to reach a very large audience without that audience touching the database.

Size the sale before drawing it

These are assumptions for a mid-sized arena on-sale, chosen to make the arithmetic visible. The checkout capacity in particular should come from your own load test.

Text
Assume: 18,000 seats, 250,000 fans in line at on-sale, 500 buyers/minute through
        checkout, 2.5 seats per order, 4 minutes average in checkout

orders to sell out:     18,000 / 2.5        = 7,200
time to sell out:       7,200 / 500         = 14.4 minutes
fans who get nothing:   250,000 - 7,200     = 242,800
buyers in checkout:     500 x 4             = 2,000 at once
seats on hold at once:  2,000 x 2.5         = 5,000, or 28% of the house

About 97% of the line cannot get a seat whatever you build, so the most useful thing the system can do for most people is tell them early. And 28% of the building is on hold at any moment, so the hold's duration is a business number: double the time in checkout and more than half the house is locked by people who may never pay.

The line paces buyers. The seat row decides who wins.

  1. 250,000

    fans in line at on-sale

  2. 500/min

    admitted, paced by checkout capacity

  3. 2,000

    buyers in checkout at once

  4. 5,000

    seats on hold at once, 28% of the house

  1. available

    Anyone may claim it, including a seat whose hold has lapsed.

  2. held

    One hold_id and an expiry, written in a single conditional statement.

  3. sold

    Confirm sells every seat in the order under one hold_id, or none of them.

Payment lands after someone else retook a seat

Confirm returns fewer rows than the order holds, so it rolls back and the authorization is cancelled. No seat has two owners, and no party gets part of an order.

Expiry is a predicate on the claim, so a lapsed hold is claimable the moment its time passes, with no background job involved.

The waiting room turns a spike into a rate

A waiting room converts an arrival spike into a steady flow the checkout can survive. Each fan gets a position when they join. A pacing loop advances a "now serving" number at the capacity you measured, 500 a minute here. When a fan's position comes up, they receive a signed, short-lived pass.

Polling is the first cost. Cloudflare's Waiting Room documentation describes a browser refreshing about every 20 seconds to update its estimate, and that interval at this scale is 250,000 / 20 = 12,500 requests a second, from people who are not buying anything. So the answer has to be cheap: one "now serving" integer cached at the edge for a few seconds, compared against a position the client already holds in a signed token.

A waiting room that only guards the page can be walked around by anyone with the checkout URL, which gets shared the moment a sale starts, so the design has to make a copied link worthless. Bots with thousands of accounts are a separate problem for a rate limiter.

Pacing is also a control: if checkout latency climbs, slow the "now serving" counter and everyone already inside recovers. This is queue-based load leveling with a person standing in each slot.

A hold is one conditional write

Once a buyer is inside, double-selling has to become impossible. The claim and the check must be the same statement:

SQL
WITH wanted AS (
    SELECT seat_id
    FROM seats
    WHERE seat_id = ANY($1)
      AND (status = 'available'
           OR (status = 'held' AND hold_expires_at <= now()))
    ORDER BY seat_id
    FOR UPDATE
)
UPDATE seats AS s
   SET status = 'held',
       hold_id = $2,
       hold_expires_at = now() + $3
  FROM wanted
 WHERE s.seat_id = wanted.seat_id
RETURNING s.seat_id;

The application compares the returned count with the number requested and rolls back on a mismatch, so a party of four gets four seats or none. Same 64 buyers, same 20 seats, with this statement: 20 holds granted, 44 refused, 20 distinct holds. Then a harder case, with 200 overlapping four-seat requests over 40 seats, about half of them listing the seats in reverse: 8 granted, 192 refused, zero partial holds and zero deadlocks. The ORDER BY inside the locking read is what keeps lock acquisition consistent, for the reason database deadlocks explains.

The second branch of the WHERE means a lapsed hold is claimable the instant it lapses, whether or not anything has cleaned it up. In the test, a second buyer was refused while a one-second hold was live and granted it 1.5 seconds later, with no sweeper running. A background job can still tidy rows for the seat map, but correctness does not depend on it.

Best available should not queue behind locks

Many buyers ask for "two seats in this section" rather than a specific pair. Written as ORDER BY seat_id LIMIT 2 FOR UPDATE, every concurrent buyer goes for the same first rows and waits in line behind whoever holds them. PostgreSQL's SKIP LOCKED takes the next free rows instead. Inside the hold statement, the select becomes:

SQL
SELECT seat_id
FROM seats
WHERE section = $1
  AND (status = 'available'
       OR (status = 'held' AND hold_expires_at <= now()))
ORDER BY seat_id
LIMIT 2
FOR UPDATE SKIP LOCKED

With 60 concurrent buyers and 2,000 seats in the section, plain FOR UPDATE took 355, 249 and 234 ms, and SKIP LOCKED took 35, 41 and 24 ms. All 60 buyers got two seats either way. That is three runs of each in a laptop container, so only the order of magnitude should travel. With nothing but lapsed holds in a section and no sweeper, the same select still returned two seats. The documentation warns that SKIP LOCKED gives an inconsistent view and suits queue-like access, and this is that case: nobody needs the absolute lowest seat number. Do not use it for a specific seat, because a skipped row there would falsely read as gone.

Payment after the hold

Payment takes minutes and runs in someone else's system, so no database transaction can span it. The hold is the bridge. Build the payment's idempotency key from hold_id plus an attempt number, so a double click cannot charge twice and a declined card can still try again. Stripe's API, as one example, saves the result of the first request with a given key and replays it for retries, errors included, which is why the attempt number has to be there.

Confirmation needs the same discipline as the hold, across the whole order:

SQL
BEGIN;

WITH mine AS (
    SELECT seat_id
    FROM seats
    WHERE hold_id = $1
      AND status = 'held'
    ORDER BY seat_id
    FOR UPDATE
)
UPDATE seats AS s
   SET status = 'sold',
       hold_expires_at = NULL
  FROM mine
 WHERE s.seat_id = mine.seat_id
RETURNING s.seat_id;

-- Rows returned = seats in the order: COMMIT. Anything else: ROLLBACK.

Each path a four-seat payment can take, on PostgreSQL 17:

Text
hold still live:                 4 of 4 rows, committed
hold lapsed, nobody retook it:   4 of 4 rows, committed
hold lapsed, one seat retaken:   3 of 4 rows, rolled back, 0 sold
hold lapsed, all four retaken:   0 of 4 rows, rolled back, 0 sold
duplicate webhook after a sale:  0 of 4 rows, 4 already sold under this hold

The count comparison is what keeps a party together. A bare UPDATE ... WHERE hold_id = $1 on the third path returned UPDATE 3 and sold three seats of a party of four. A hold that lapsed but stayed intact still confirms, because refunding a payment for seats that are still free helps nobody. A retaken seat has a new hold_id, which works like a fencing token: the late arrival can no longer change that row.

A short count on its own does not mean "refund", because the duplicate webhook also comes up short. The handler should reread the order, and if every seat is sold under this hold_id, treat the event as already done. Idempotency in API design covers that shape. Racing a confirm against a retake of two of its seats for 500 rounds gave 189 orders fully sold, 311 not sold, none partly sold and zero deadlocks, with both statements locking in seat order.

Separating authorization from capture makes the failure path gentler. Stripe documents placing a hold on a payment method and capturing later, typically within 7 days for an online card payment. Authorize first, confirm the seat, then capture. If the confirm comes up short and the seats are not sold under this hold, you cancel an authorization, which is a smaller thing to explain to a customer than a refund. End the checkout page's own timer before the hold's expiry, so a buyer finishing on time cannot lose the race by a few seconds.

A four-seat confirm with one seat retaken returned 3 of 4 rows. Comparing that count with the order and rolling back left 0 seats sold.

The seat map can be stale

The map is the most-read data in the system and the least important to get exactly right, because the hold is the arbiter. A buyer who clicks a seat that went two seconds ago gets a quick refusal and picks another. That tolerance means the map can be a cached snapshot, so read traffic and write contention never meet.

Under the assumptions above, 2,000 buyers refreshing every 5 seconds is 400 requests a second. Split the house into 40 sections, publish a compact JSON document per section, and cache each for 2 seconds. Each edge location then asks the origin for at most 40 / 2 = 20 documents a second, regardless of how many people are looking.

Keep the snapshot out of every decision. Charging a card because the map said a seat was free is how forty-four tickets get sold for twenty seats.

What a sold-out sale leaves behind

When the sale ends, check the invariants directly instead of trusting the code paths that were meant to preserve them. No seat should have two tickets, and a unique constraint on the seat in the tickets table makes that structurally true. No order should be partly sold. Every captured payment should match sold seats under its hold_id, and any authorization older than the hold window with no sold seats should be cancelled.

"Admit Through a Waiting Room" opens the Sell Out a Stadium series in the System Design Studio from the failure a shared checkout link causes, and a separate challenge covers the reservation that has to exist before any payment work is published. The EF Core exercises run your queries against real PostgreSQL and show the SQL they generate.

Run those invariant checks as a small reconciliation query on a schedule for as long as money can still move, because that is where a lost webhook surfaces.

Practice System Design

More like this: System Design Studio →

Get new katas and .NET tips in your inbox

A short note when fresh kata land, plus the C# and performance tricks behind the grading. No spam, unsubscribe anytime.