Skip to content

    System Design

    Case Study: Ticket Booking and Overselling

    Design a ticket booking system that never sells a seat twice: atomic seat claims, expiring holds, payment ordering, surge control and the failures to plan for.

    By Published 22 min read

    Share

    What you'll learn: By the end of this lesson you will be able to (1) explain exactly how two buyers get the same seat, (2) design a seat claim that the database itself makes impossible to duplicate, (3) design holds that expire, survive slow payments and release cleanly, (4) decide what Redis and caches may and may not do in the path, and (5) protect the system when hundreds of thousands of people arrive in the same minute.

    A box office has one paper seating chart on the counter. Two clerks, each with a pen, each look at seat F12, see it is empty, and each promise it to a customer. Neither did anything careless. Each read the chart, decided, then wrote, and the other clerk's write happened in between. The fix is not "be more careful". The fix is one chart, one pen, and a rule that you cross a seat off in the same motion as you check it is free.

    A ticket booking system is that box office with hundreds of thousands of customers at the counter at once. This lesson is the dedicated case study of the overselling problem. It builds on locking, optimistic and pessimistic, ACID and isolation levels and idempotency keys and safe retries, and it hands the money side to payments and double-entry ledgers; the planned Payment System case study applies that lesson as a whole.

    This is an educational reference design, not the verified internal architecture of any company. It names no ticketing company and describes none. Every number is an illustrative assumption. Verified on 2026-12-02 against the PostgreSQL 18 documentation, the Redis documentation, RFC 9110, RFC 6585 and the Stripe documentation (cited only as one example of a payment provider). The SQL on this page was checked to parse and to claim and refuse seats as described on a single connection in PGlite, a WebAssembly build of PostgreSQL; it was not run under concurrent sessions, and no output is shown.

    The core idea

    Overselling is a lost update on inventory, made worse by a crowd. The cure is to make the claim of a seat one atomic operation inside the database that owns the seat, with the invariant "a seat has at most one owner" enforced by the database itself, and to put everything else (queues, caches, Redis) in front of that operation, never in place of it.

    Three illustrations run through the lesson:

    • Minimal example: two buyers, one seat, and the check-then-write race that sells it twice, then the single UPDATE that cannot.
    • Realistic example: an on-sale for a 20,000-seat arena with a sudden crowd, holds that expire, and a payment that finishes late.
    • Failure example: a payment that succeeds after the hold has expired and the seat has gone to someone else.

    Requirements and scope

    Functional: browse an event and its seat map, pick specific seats or ask for "best available", hold seats while the buyer pays, confirm the booking after payment, release holds that are abandoned, show a ticket.

    Out of scope: pricing and fees, resale and transfer, ticket delivery and entry scanning, fraud scoring, the payment internals (see the ledger lesson), and any rule that depends on a country or a seller's contract.

    Non-functional (assumptions):

    • A seat is sold to at most one buyer. This is an invariant, not a goal: a violation is a defect.
    • A seat map that is a few seconds stale is acceptable, as long as a stale view never causes a sale.
    • A buyer who pays for a seat that is then unavailable is refunded automatically and told why.
    • The system stays responsive during a surge by refusing work early, not by slowing everyone down.

    Back-of-envelope estimate

    All figures are illustrative assumptions for one event.

    Quantity Assumption Result
    Seats 20,000, max 4 per hold At least 5,000 holds to sell out
    People trying at on-sale 400,000, 3 attempts each 1,200,000 hold attempts
    Attempt window First 10 minutes (600 s) 2,000 attempts per second average, about 6,000 at a 3x peak
    Attempts per seat 1,200,000 / 20,000 60 attempts for each seat
    Hold length 8 minutes, half of holds abandoned Roughly 10,000 successful holds in total (5,000 to sell out plus re-holds)
    Seat map snapshot 2 bits of status per seat 20,000 x 2 bits = 40,000 bits, about 5 KB per snapshot before compression

    Two conclusions follow, and neither depends on the exact figures. First, almost every attempt is a rejection: of 1,200,000 attempts only about 10,000 win. The design must make a losing attempt cheap. Second, the load is not spread evenly: the seats people want most take most of the attempts, so contention lives on a few hundred rows, not on 20,000. Whether one primary handles the peak is for a load test to confirm; this lesson makes no benchmark claim.

    API design

    GET    /v1/events/{eventId}/seats                  seat map snapshot (cacheable, may be a few seconds stale)
    POST   /v1/events/{eventId}/holds                  body: seatIds[] or {section, count}; header Idempotency-Key
             201 {holdId, seatIds[], expiresAt}
             409 problem+json {unavailableSeatIds[]}   some seat was not free
             429 or 503 with Retry-After               admission control is refusing work
    POST   /v1/holds/{holdId}/confirm                  after the payment is authorised; header Idempotency-Key
             200 {bookingId} | 409 hold expired or lost
    DELETE /v1/holds/{holdId}                          the buyer let go

    Three design points. The hold request carries an Idempotency-Key, so a retry after a lost response returns the same hold instead of grabbing a second set of seats (idempotency keys). A "not free" answer is 409: RFC 9110 defines 409 Conflict as a request that could not be completed due to a conflict with the current state of the target resource, and the body should say which seats lost, in the shape of Problem Details. Refusal under load is 429 or 503: RFC 6585 defines 429 Too Many Requests and says the response may include Retry-After, and RFC 9110 lets a 503 carry a Retry-After hint, so well-behaved clients wait instead of hammering.

    Data model

    Inventory is a table with one row per seat per event, in PostgreSQL. The row carries its own state, so one statement can check and change it together.

    CREATE TABLE seat (
      event_id        bigint      NOT NULL,
      seat_id         text        NOT NULL,
      section         text        NOT NULL,
      row_no          int         NOT NULL,
      seat_no         int         NOT NULL,
      status          text        NOT NULL DEFAULT 'available'
                      CHECK (status IN ('available', 'held', 'sold')),
      hold_id         uuid,
      hold_expires_at timestamptz,
      booking_id      uuid,
      PRIMARY KEY (event_id, seat_id),
      CHECK (status <> 'held' OR (hold_id IS NOT NULL AND hold_expires_at IS NOT NULL)),
      CHECK (status <> 'sold' OR booking_id IS NOT NULL)
    );
    
    CREATE TABLE booking_item (
      booking_id uuid   NOT NULL,
      event_id   bigint NOT NULL,
      seat_id    text   NOT NULL,
      status     text   NOT NULL CHECK (status IN ('confirmed', 'released')),
      FOREIGN KEY (event_id, seat_id) REFERENCES seat (event_id, seat_id)
    );
    
    -- a second, independent guard: no seat can have two confirmed bookings
    CREATE UNIQUE INDEX one_sale_per_seat ON booking_item (event_id, seat_id) WHERE status = 'confirmed';

    The CHECK constraints make impossible states unrepresentable: PostgreSQL raises an error when a row would violate one, so a code path that tries to mark a seat sold without a booking fails loudly. The partial unique index is a backstop. PostgreSQL's documentation describes a partial index as one built over a subset of the table, and a partial unique index as enforcing uniqueness among the rows that satisfy its predicate without constraining the rest. Here that means any number of released rows per seat, but one confirmed row.

    erDiagram accTitle: Ticket booking data model accDescr: An event has many seats. A seat has at most one active hold and at most one confirmed booking item. A booking has many booking items, one per seat, and one payment reference. EVENT ||--o{ SEAT : has SEAT ||--o{ BOOKING_ITEM : sold_as BOOKING ||--|{ BOOKING_ITEM : contains EVENT { bigint event_id PK string name } SEAT { bigint event_id PK string seat_id PK string status uuid hold_id timestamptz hold_expires_at uuid booking_id } BOOKING { uuid booking_id PK string payment_ref } BOOKING_ITEM { uuid booking_id FK string seat_id FK string status }

    Figure 1. The data model. How to read this: the seat row holds the live state (available, held, sold) and its hold, so a claim is one row update. BOOKING_ITEM is the permanent record and carries the partial unique index that backs up the seat row.

    For general admission with no seat numbers, the inventory is a counter instead of rows, ticket_tier(tier_id, remaining integer CHECK (remaining >= 0)), and the next sections apply to it with one change, covered in the second deep dive.

    High-level design

    Ticket booking reference designBuyers to Waiting room; Buyers to Redis (read map); Waiting room to Booking service (admitted); Booking service to PostgreSQL (claim); Booking service to Payment service; Payment service to Payment provider; Expiry sweeper to PostgreSQL (release expired); PostgreSQL to Notifications (outbox)BuyersBuyersWaiting room: admission controlWaiting roomadmission controlRedis: seat map snapshotRedisseat map snapshotBooking serviceBookingservicePostgreSQL: seats and bookingsPostgreSQLseats andbookingsPayment servicePaymentserviceExpiry sweeperExpiry sweeperPayment providerPaymentproviderNotificationsNotificationsread mapadmittedclaimrelease expiredoutbox

    Figure 2. Reference design. How to read this: only the booking service writes seat state, and only to PostgreSQL. Reads of the seat map go to a cached snapshot, so a crowd refreshing the map never reaches the database that decides sales.

    The booking service is stateless. All the truth about who owns a seat is in PostgreSQL. The waiting room decides how many buyers may attempt holds at once. The cached snapshot serves the picture and is allowed to be wrong for a few seconds because the claim step re-checks. The sweeper returns expired holds to the pool and clears the picture. Notifications are fed from an outbox written in the same transaction as the booking, as in the transactional outbox lesson.

    sequenceDiagram accTitle: Hold, pay and confirm accDescr: The buyer asks the booking service for seats. The service claims them in the database with a conditional update and returns a hold with an expiry. The buyer pays through the payment service, which authorises with the provider. The service then confirms the hold with a conditional update. If the update matches no rows the authorisation is cancelled, otherwise it is captured and the booking is final. participant B as Buyer participant S as Booking service participant D as PostgreSQL participant P as Payment service B->>S: POST holds (seats, key) S->>D: claim seats (conditional UPDATE) D-->>S: rows claimed S-->>B: 201 hold, expires in 8 min B->>P: pay for hold P-->>S: authorised S->>D: confirm hold (still held, not expired) alt hold still valid D-->>S: 1 row per seat S->>P: capture S-->>B: booking confirmed else hold expired or lost D-->>S: 0 rows S->>P: cancel authorisation S-->>B: 409 and no charge end

    Figure 3. The happy path and the late path. How to read this: the money is only captured after the confirm statement succeeds. The authorisation is a hold on the buyer's funds, so cancelling it is the cheap way out.

    Deep dive 1: how two buyers get one seat

    Seat F12 is available. Alice and Bob both click it. The naive handler does what a human would: read, decide, write.

    SELECT status FROM seat WHERE seat_id = 'F12';   -- both read 'available'
    -- application: if status == 'available' ...
    UPDATE seat SET status = 'held', hold_id = :mine WHERE seat_id = 'F12';   -- both write
    sequenceDiagram accTitle: The check then write race accDescr: Alice and Bob both read the seat as available. Alice writes her hold. Bob writes his hold over hers, because his update has no condition. Both are told success and the seat has one owner in the table but two promises outside it. participant A as Alice participant D as Seat row participant B as Bob A->>D: SELECT status D-->>A: available B->>D: SELECT status D-->>B: available A->>D: UPDATE to held by Alice D-->>A: 1 row updated B->>D: UPDATE to held by Bob D-->>B: 1 row updated Note over A,B: both were told success, one write silently replaced the other

    Figure 4. The check-then-write race, the minimal example. How to read this: nothing failed. Each UPDATE succeeded, and the later one replaced the earlier. The check lived in the application, and the application's view was stale the moment it was read.

    This is the lost update with a seat in place of a stock count. Three things make it worse than in a shop: the window between read and write includes a network round trip and often a human pause, the crowd reads the same few rows at once, and the damage is two real people each told they own seat F12.

    Deep dive 2: make the claim one atomic statement

    Move the check into the write, so there is no gap.

    UPDATE seat
    SET status = 'held',
        hold_id = :hold_id,
        hold_expires_at = now() + interval '8 minutes',
        booking_id = NULL
    WHERE event_id = :event_id
      AND seat_id = :seat_id
      AND (status = 'available' OR (status = 'held' AND hold_expires_at <= now()));

    The statement tells the caller whether it won through the number of rows it changed: one means the seat is yours, zero means someone else has it. There is no read for the application to act on. Under PostgreSQL's default Read Committed isolation, the documentation describes what happens when two such statements meet: the second one waits for the first to finish, and if the first commits, the second re-evaluates its WHERE clause against the updated version of the row (and ignores the row if it was deleted). Bob's statement therefore sees status = 'held' with a future expiry, no longer matches, and changes zero rows. The same sentence is why the condition has to be in the WHERE clause and not in a preceding SELECT.

    Expiry is part of the condition: a held seat whose hold_expires_at has passed is claimable again at once, without waiting for a sweeper. The database clock decides, so the application servers' clocks do not matter.

    Several seats, all or nothing. Buyers want pairs and groups. Take the locks in a fixed order, claim, and compare the count.

    BEGIN;
    SELECT seat_id FROM seat
    WHERE event_id = :event_id AND seat_id = ANY(:seat_ids)
    ORDER BY seat_id
    FOR UPDATE;
    
    UPDATE seat
    SET status = 'held', hold_id = :hold_id,
        hold_expires_at = now() + interval '8 minutes', booking_id = NULL
    WHERE event_id = :event_id AND seat_id = ANY(:seat_ids)
      AND (status = 'available' OR (status = 'held' AND hold_expires_at <= now()))
    RETURNING seat_id;
    -- if fewer rows came back than seats requested: ROLLBACK and answer 409 with the missing ones
    COMMIT;

    The fixed order is the same rule as in the locking lesson: two buyers who each want two of the same seats in opposite order are the classic recipe for a deadlock, and sorting the seat ids removes it. This lesson does not rely on a single multi-row UPDATE to lock in any particular order. Keep the transaction short, make no network call inside it, and retry a deadlock or serialization error a bounded number of times, as that lesson advises.

    "Best available". The buyer asks for any three seats in a section. Choosing them in the application and then claiming them invites constant collisions on the same top seats. PostgreSQL's SKIP LOCKED lets each request take rows that no other transaction holds.

    WITH pick AS (
      SELECT seat_id FROM seat
      WHERE event_id = :event_id AND section = :section
        AND (status = 'available' OR (status = 'held' AND hold_expires_at <= now()))
      ORDER BY row_no, seat_no
      LIMIT :n
      FOR UPDATE SKIP LOCKED
    )
    UPDATE seat s
    SET status = 'held', hold_id = :hold_id,
        hold_expires_at = now() + interval '8 minutes', booking_id = NULL
    FROM pick
    WHERE s.event_id = :event_id AND s.seat_id = pick.seat_id
    RETURNING s.seat_id;

    The documentation says that with SKIP LOCKED any rows that cannot be locked immediately are skipped, that this "provides an inconsistent view of the data", and that it is "not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table". A pool of interchangeable seats being handed out is queue-like. The price is that a request may get seats that are not next to each other because a neighbour was locked a moment earlier; if adjacency matters, ask for it as a rule and fall back to fewer or split seats, and tell the buyer. With LIMIT, the documentation says locking stops once enough rows have been returned.

    General admission. With no seat numbers the same idea applies to a counter.

    UPDATE ticket_tier
    SET remaining = remaining - :n
    WHERE tier_id = :tier_id AND remaining >= :n;

    Zero rows means sold out. The CHECK (remaining >= 0) makes a negative count an error even if a bug removes the remaining >= :n condition. The cost is a single hot row: every buyer of the tier queues on it. If one tier's row becomes the bottleneck, split its count into several bucket rows (for example 8 buckets of a few hundred each), pick a bucket at random and fall through to the next when one is empty. That raises the capacity of the counter at the price of a less exact "tickets left" figure and a small chance of reporting sold out while a bucket still has stock; decide whether that is acceptable.

    The backstop. The seat row prevents a second holder. The partial unique index on booking_item prevents a second confirmed booking even if a future code path forgets the condition: the insert fails instead of overselling. Two independent guards in the database are cheap and are the difference between a bug that is caught in staging and one that is found in a customer's inbox.

    Deep dive 3: holds, expiry and the payment that arrives late

    A hold turns a seat from "free" into "promised for a while". It exists because payment takes minutes, and no one wants to type card details for a seat that was sold during the typing.

    stateDiagram-v2 accTitle: Seat states accDescr: A seat starts available. A successful claim makes it held. A confirm while the hold is valid makes it sold. A release or an expired hold returns it to available. A sold seat can return to available only through a refund and cancellation process. [*] --> Available Available --> Held : claim succeeds Held --> Sold : confirm while hold valid Held --> Available : released or expired Sold --> Available : booking cancelled and refunded Sold --> [*]

    Figure 5. Seat states. How to read this: every transition is a conditional update that names the state it expects. There is no edge from Held to Sold that does not check the hold id and the expiry.

    The confirm step is the important one.

    UPDATE seat
    SET status = 'sold', booking_id = :booking_id, hold_id = NULL, hold_expires_at = NULL
    WHERE event_id = :event_id AND hold_id = :hold_id
      AND status = 'held' AND hold_expires_at > now();

    If it changes one row per seat in the hold, the seats are sold. If it changes fewer, the hold lapsed (and possibly the seat went to someone else), and the whole confirm is rolled back.

    Order the payment steps around that statement. The safe sequence is: hold the seats, authorise the payment (a hold on the buyer's funds, not a transfer), confirm the seats, then capture. The Stripe documentation describes the building blocks: a PaymentIntent that is authorised and waiting is in requires_capture, cancelling a PaymentIntent releases any held funds and cannot be undone, and a PaymentIntent in requires_capture is not refunded but cancelled. So when the confirm statement returns zero rows, cancelling the authorisation is the correct, cheap undo, and the buyer is never charged. If the order were capture first and confirm second, a lost race would force a refund, which is slower and visible on a statement. The payments lesson explains why a hold is not a ledger movement.

    The late payment. A card that needs a second authentication step, or a bank method that settles in days, can outlast an 8-minute hold. Stripe's documentation says asynchronous methods can sit in processing for up to a few days. A booking system has to choose, and each choice has a cost:

    Choice Behaviour Cost
    Fixed hold, then fail Payment outliving the hold is cancelled and the buyer retries Frustrating when a slow payment loses a seat the buyer thought was theirs
    Extend the hold when payment starts One bounded extension (for example 8 to 12 minutes) once the buyer submits payment Seats are locked longer; abuse needs limits
    Only offer fast methods for hot events Slow methods are removed during the on-sale Fewer ways to pay; simple behaviour
    Sell, then refund if the seat was lost Confirm after capture, with compensation Customer-visible refunds and support load

    The reference design uses the second row for cards, with one capped extension, and refuses slow-settling methods during the first minutes of an on-sale.

    Expiry has two jobs. The condition hold_expires_at <= now() in the claim makes an expired hold claimable immediately, which is what correctness needs. A sweeper that runs every few seconds and sets expired holds back to available is for everything else: the seat map, counters and the "seats left" figure. If the sweeper stops, correctness is unaffected, and only the picture lags. That is a deliberate split: a background job must not be on the path that prevents a double sale.

    Deep dive 4: where Redis fits, and where it must not

    Redis is fast, and the first idea in many designs is to hold seats there with SET seat:F12 holder NX PX 480000. The Redis documentation describes the pieces: NX sets the key only if it does not already exist, PX sets the expiry in milliseconds, and the command returns a null reply when the key exists and was not set. That is a fine primitive for a short-lived claim. The risks come from making it the authority.

    • Two sources of truth. The paid booking must be in the database for durability and refunds. If Redis also decides who holds a seat, the two can disagree, and every disagreement is a possible double sale or a lost seat.
    • Failover. The Redis distributed-locks page states the problem for replicated setups: replication is asynchronous, so if the master crashes before a lock key reaches the replica and the replica is promoted, a second client can acquire the same lock. For seats, that is two holders. The same page says that for correctness you should implement fencing tokens and that Redis does not use a monotonic clock for key expiry, so a wall-clock jump can let a lock be taken twice. The fencing tokens lesson explains the defence: the resource itself, here the database row, must reject a stale holder.
    • Safe release. The documentation recommends a random value per lock holder and a release that removes the key only if the value still matches, so a slow client cannot delete someone else's hold.

    The sensible roles are the ones that tolerate being wrong:

    Use of Redis Safe? Why
    Cache of the seat map snapshot Yes The claim step re-checks; a stale map costs a 409, not a double sale
    "Sold" markers to refuse hopeless attempts early Yes, if it is only a shortcut A missing marker just sends the attempt to the database
    Rate limits and admission counters Yes They shed load; see the rate limiter lesson
    Short pre-claim to reduce database contention With care The database claim still decides; Redis only orders who tries first
    Sole record of who holds a seat No Failover and clock behaviour can produce two holders

    Deep dive 5: surviving the crowd

    Seat map reads. The map is the most requested thing and the least important to get exactly right. Serve it as a snapshot from a cache or a CDN, refreshed every second or two, and push changes on the active event over a lightweight channel only if the product needs it. A buyer who clicks a seat that just went 409 sees a message and a refreshed map; that is the eventual consistency UX the design accepts in exchange for not sending thousands of reads per second to the primary.

    Admission control. A waiting room limits how many buyers may attempt holds at once. It turns a spike of 6,000 attempts per second into a rate the booking path was sized for, and it is fairer than letting whoever has the fastest connection win. The design is a rate limiter on the entry to the booking service, with a queue ahead of it; see the rate limiter lesson, load shedding and retry storms and backpressure. Refusals use 429 or 503 with Retry-After, and the client adds jitter so a million browsers do not retry in lockstep (timeouts, retries, backoff and jitter).

    Hold abuse. A script that holds every seat and never pays denies the event to real buyers. Limit seats per hold and live holds per account, keep holds short, and extend only once payment has started. The thresholds are product and fraud decisions for the event owner.

    Hot partitions. Shard by event id so different events do not share a bottleneck; one huge event still writes to one primary, which must be sized for it (hot partitions and resharding). Another design routes all writes for one event through a single-writer queue: ordering is trivial, at the price of a throughput ceiling and a failover story for the writer.

    Choosing a claim strategy and its trade-offs

    flowchart TD accTitle: Choosing how to claim inventory accDescr: Start by asking whether inventory is a count or named seats. A count uses a conditional decrement, possibly bucketed if one row is hot. Named seats use a conditional update per seat. If the buyer asks for any seats, use skip locked selection. If groups of named seats are claimed together, lock in a fixed order and claim in one transaction. In every case the database enforces the invariant and Redis is only a cache or limiter. start["Claim inventory"] --> kind{"Named seats?"} kind -- "No, a count" --> cnt["Conditional decrement, buckets if one row is hot"] kind -- "Yes" --> pick{"Buyer chooses exact seats?"} pick -- "No, any n" --> skip["Select with SKIP LOCKED, then update"] pick -- "Yes" --> multi{"More than one seat?"} multi -- "No" --> one["One conditional UPDATE"] multi -- "Yes" --> many["Lock in sorted order, claim, compare count, all or nothing"] cnt --> rule["The database enforces the invariant"] skip --> rule one --> rule many --> rule

    Figure 6. A decision for the claim step. How to read this: pick the shape of the inventory first. Every branch ends at the same rule, that the database enforces "at most one owner", and nothing in front of it is allowed to decide.

    Strategy Gain Cost Wrong when
    Conditional UPDATE (state in the row) One statement, no gap, cheap rejection Hot rows queue Claim logic needs data from several tables
    Pessimistic lock then update Simple to reason about Holds locks while the app decides Locks span a network call
    Optimistic version column No lock while the buyer thinks Retry storms on hot seats The seats everyone wants are the contended ones
    Serializable transactions The database detects anomalies Retries on serialization failure (40001) are mandatory Throughput is the limit and conflicts are common
    Single-writer queue per event Order is trivial Throughput ceiling, failover design One event needs more than one writer can do
    Redis lock as authority Fast Two truths, failover and clock risk Money or a promise depends on it

    On Serializable, the PostgreSQL documentation says the level emulates serial execution of all committed transactions and that applications must be prepared to retry transactions that fail with SQLSTATE 40001. It is a legitimate way to guard a multi-statement claim, but it moves the work into retries; for a hot seat that can mean most attempts retry. A conditional update avoids that by making the losers lose quickly.

    Failure modes

    Failure Effect Mitigation
    Two buyers claim one seat Oversell Conditional UPDATE, CHECK constraints, partial unique index
    Payment succeeds after hold expiry Charged for a seat that is gone Authorise first, confirm, then capture; cancel the authorisation on a failed confirm
    Booking service crashes after claim Seats held with no one paying Expiry returns them; the idempotent retry returns the same hold
    Sweeper stops Map and counts lag Correctness is in the claim condition, so only the picture is stale; alert on sweeper age
    Retry storm after errors Overload Jitter, Retry-After, admission control
    Hold hoarding Real buyers locked out Per-account limits, short holds, extension only after payment starts
    Deadlock on group claims Aborted transaction Sorted lock order, bounded retries
    Duplicate confirm Double booking record Idempotency key plus the partial unique index

    Build it

    There is no lab for this lesson. The SQL above is written for PostgreSQL 18 and was checked on a single connection only; races between sessions are not shown. The closest runnable material is the lab in locking, optimistic and pessimistic, which runs the two-buyers-one-row scenario and the opposite-order deadlock on H2, and the Spring filter in idempotency keys and safe retries.

    In practice: an arena on-sale

    This is a realistic scenario, not a case history.

    The situation

    A mid-sized venue operator, with no resemblance to any real company, sells a 20,000-seat arena through its own site. Today's system keeps seat state in the application: each server caches the seat map in memory and checks it before writing a booking row. During the last on-sale, 31 seats were each sold to two buyers, support spent days resolving them, and the site was unusable for the first four minutes. The numbers are illustrative.

    Starting architecture

    Starting architecture: availability checked in the applicationBuyers to App servers; App servers to Database (insert booking)BuyersBuyersApp servers: seat map in memoryApp serversseat map inmemoryDatabase: booking rows, no seat stateDatabasebooking rows, noseat stateinsert booking

    Figure 7. Starting point. How to read this: each server believes its own copy of the seat map, so two servers can both sell F12. The database stores bookings but does not know which seats are taken.

    Options considered

    Option Gain Cost Wrong when
    A. Sticky routing so one server owns each section No code change in the database A server failure or rebalance reopens the race; uneven load Servers restart during on-sale
    B. A Redis lock per seat Fast, familiar Second source of truth; failover and clock risks Money depends on it being exact
    C. Seat state in the database with conditional updates, plus partial unique index Race is impossible in the data layer; losers fail fast Hot rows; needs a waiting room for the crowd Inventory has no single owner database

    The decision

    Option C, with Redis used only for the cached map and the admission counters. The booking service claims seats with conditional updates, holds last 8 minutes with one extension once payment starts, payment is authorised before the confirm statement and captured after it, and a waiting room limits concurrent hold attempts to a rate the booking path was load tested for. The partial unique index goes in first, as a guard, before any application change. Business rules that depend on contracts, refunds policy or the law are decided by the venue operator and its advisers, not by this design.

    Rollout and verification

    1. Add the CHECK constraints and the partial unique index in a migration that is safe on a live table (zero-downtime migrations), and run the old code against it. Any violation is an existing bug, now visible.
    2. Ship the conditional claim behind a flag in shadow mode: perform the new claim, compare its answer with the old logic, and log disagreements.
    3. Switch the claim to authoritative for one low-demand event, then a larger one.
    4. Load test with a synthetic crowd that attempts the same 200 seats at the assumed peak rate, and check three counters: no seat with two confirmed bookings, no confirmed booking without a captured payment, no captured payment without a confirmed booking.
    5. Rehearse the late-payment path by delaying an authorisation past hold expiry and verifying the buyer is never charged.

    The 2 a.m. failure

    The page reads: "confirm failures at 40 percent for one event, refunds rising". The payment provider's authorisations began taking longer than the hold, so confirm statements match zero rows, the authorisations are cancelled and buyers lose seats they were paying for. First checks: confirm failure reasons, authorisation latency, hold expiry against the median payment time. Mitigation: extend the hold window for the affected method and pause slow methods for the rest of the on-sale. Lasting fix: alert on the ratio of confirm failures to holds, and make the extension rule data-driven. The invariant held throughout: no seat was sold twice, and no one was charged for a seat they did not get.

    Architect's notes

    • Name the invariant first. "A seat has at most one owner" is one sentence. Every design choice either enforces it or sits in front of it.
    • Count rejections, not just wins. The design is sized by the 1,190,000 refusals, not the 10,000 sales.
    • Make the correctness path independent of background jobs. If a sweeper outage can cause a double sale, the design is wrong.
    • Put two guards on the data. A conditional update and a unique index fail differently, which is the point.

    Common mistakes

    • Reading the seat in the application, then writing. The check and the write must be one statement.
    • Treating Redis as the source of truth. A failover can produce two holders. Use it for caching and limiting.
    • Capturing the payment before confirming the seat. A lost race then needs a refund.
    • No expiry condition in the claim. A crashed sweeper then strands seats.
    • Unordered group locks. Opposite orders deadlock; sort the seat ids.
    • Holding a lock across the payment call. Reserve, commit, then call.
    • Ignoring idempotency on the hold request. A retry grabs a second set of seats.

    Key takeaways

    • Overselling is a lost update on inventory, and a crowd makes the window large and the collision likely.
    • The claim is one conditional statement, and rows affected is the answer. Zero means someone else has it.
    • Holds are rows with an expiry the database checks; a sweeper is cleanup, never correctness.
    • Authorise, confirm the seats, then capture. Cancelling an authorisation is the cheap undo.
    • Redis and caches speed up reads and shed load; the database decides ownership, and a partial unique index backs it up.
    • A waiting room, Retry-After and jitter protect the claim path from the crowd.

    Practice exercises

    Exercise 1, Starter (30 min): Using the illustrative table, recompute attempts per second and attempts per seat for 600,000 people with 2 attempts each over 5 minutes. Which row of the design changes, and which does not?

    Exercise 2, Intermediate (2 hours): Write the claim for "any 3 adjacent seats in a section". Decide how adjacency is expressed in the data, what happens when SKIP LOCKED splits a group, and what the buyer is told.

    Exercise 4, Advanced (half day): Sketch the design if the arena sells through two regions and each wants to sell the same seats locally. Decide which region owns each seat and what a buyer in the other region sees (CAP theorem and PACELC).

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments