Skip to content

Case Study: Ticketing System (end-to-end 4-step walkthrough) ​

"Without it, the queue would order on a first-come basis, creating a race where the bots will always be faster than humans." — Ticketmaster, How A Ticketmaster Queue Works (vendor blog, on why the waiting room exists)

Summary: A ticketing system sells a fixed, numbered inventory to a crowd that arrives all at once; this chapter designs one from a blank page with the four-step method: scope, estimate, high-level design, then the deep dives that decide whether a seat is ever sold twice. Focus: Scope and the "no double-selling ever" invariant; on-sale arithmetic (QPS, hold rate, payments, seat-map bandwidth, storage, cache); API, seats-as-rows data model, services, CDN seat maps, virtual waiting room with signed admission tokens, realtime seat availability; single writer per seat (FOR UPDATE, SKIP LOCKED, version column, Redis Lua), hold expiry and the sweeper, fairness (randomised vs FIFO admission, bot defence, rate limiting), payment ambiguity (idempotency key, outbox, saga), hot events and partitioning, signed QR tickets with offline validation and revocation, transfer and resale, analytics, failure scenarios, capacity test, observability, cost and the interview version; Go and Laravel 13 code with concurrency tests. Learning goal: Given "design Ticketmaster for a 50,000-seat stadium on-sale", produce in under an hour a design whose every component is justified by a number, whose seat inventory cannot be double-sold under any interleaving or failure, and whose three riskiest decisions (hold mechanism, admission policy, payment ambiguity) each come with an alternative, a consequence and a metric.

This is the capstone of the System Design path: it applies The 4-Step Approach end to end to one problem, so read that chapter first. No company is described here. The design is a worked example, which makes every architecture claim on this page inference unless a source is named. Vendor pages are quoted only for what the vendor says about its own product: Ticketmaster's Smart Queue blog, Queue-it, Cloudflare Waiting Room. Mechanics owned by other chapters are linked rather than taught again: row locks in Locks & Concurrency, the strategy choice in Optimistic vs Pessimistic Locking, the outbox and saga in Transactional Outbox and Saga Pattern, payments in Payment Processing Architecture, push in Real-Time Communication, and limits in Rate Limiting.

Page map ​

If you are looking forGo to
The whole design on one screenEverything in one minute
Why ticketing is the classic hard caseWhy it exists
Which sources say whatWhere it comes from
Step 1: features, non-functional targets, the invariantFunctional scope, Non-functional
Step 2: QPS, holds, payments, storage, bandwidth, cacheEstimate
Step 3: API, data model, services, edge, realtimeAPI, Data model, Services, Edge, Realtime
Step 4: no double-sellingSingle writer per seat
Step 4: holds, TTL, sweeperSeat holds with expiry
Step 4: waiting room, fairness, botsFlash-sale fairness
Step 4: payment, idempotency, outbox, sagaPayment ambiguity
Step 4: hot events and partitioningHot events
Step 4: QR tickets, scanning, transfer, resaleTicket integrity, Transfer and resale
Step 4: analytics, failures, operationsAnalytics, Failure scenarios, Operations
The 45-minute interview versionInterview version
Knobs, error codes, arithmeticMechanics
CodeGo, Laravel
Classic incidents and their fixesSolving the classic problems
Which hold mechanism, which admission policyChoosing
Monolith to multi-regionIn architecture
Run the race tests and the estimatorLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four steps, applied. Each row is one step of the method and the answer this chapter gives for ticketing.

StepQuestionTicketing answerSection
1. ScopeWhat are we building, how well?Browse, seat map, hold, pay, issue, transfer/resale, scan. Invariant: a seat is sold at most once. On-sale for 50k seats with 100k concurrent buyers.Scope
2. EstimateWhere is it big?The crowd (100k at the edge, 5k polls/s) and the contention (50 holds/s on one partition), not throughputEstimate
3. High-level designSmallest design that fitsCDN + waiting room at the edge; one inventory service as the single writer; PostgreSQL partitioned by event; outbox to workers; SSE/WebSocket pushServices
4. DecisionsWhere does it break?Hold mechanism, hold expiry, admission policy, payment ambiguity, hot partition, ticket forgeryDouble-selling

Three ways to make one seat have one writer.

MechanismHowWins whenCosts
Row lock: SELECT ... FOR UPDATE (PostgreSQL)Lock the chosen seat rows in seat order, check, update, commitThe buyer picked exact seats on the seat mapWaiters queue on hot rows; needs lock_timeout
FOR UPDATE SKIP LOCKEDTake any N free rows, skip rows another transaction is locking"Best available" and the sweeperNot for exact seats: it skips, it does not wait
Optimistic: version columnUPDATE ... WHERE version = $readLow contention, single seatLost races become retries; bad on hot rows
Redis Lua atomic holdOne script checks and sets every seat key with PXVery high hold rate; holds in memorySecond source of truth; must be rebuilt from the DB after a Redis loss

The numbers that drive the design (back-of-the-envelope estimate, inputs in Step 2; output of go run ./estimate).

QuantityValueConsequence
Orders to sell out50,000 seats / 2.5 per order = 20,000Payments are small: about 17/s
Admission rate5,000 active shoppers / 5 min = 1,000 per minuteSells out in about 20 min; the waiting room sets this rate
Edge polls100,000 / 20 s = 5,000 req/sServed by the edge, never by the origin
Origin API5,000 shoppers x 2 req/s = 10,000 QPS19 instances at 1,000 QPS each, 60% target, N+2
Hold attemptsabout 50/s, 125 seat-row writes/sTrivial throughput, extreme contention on a few rows
Seat map250 KB gzipped from the CDN; 6.1 KB availability bitmap23.8 GB burst if everyone loaded it at once without a queue
Buyers100k at on-saleCDN: seat map, pagesVirtual waiting roomshuffle, FIFO, signed tokenAPI gatewaytoken check, rate limitCatalogueInventory / holdssingle writer per seatOrderPaymentPostgreSQLseats partitionedby event, outboxRedisholds, cacheOutbox relaySKIP LOCKEDBroker (Kafka or queue)ChargeRequested, IssueTicketsTicket issuanceNotificationAnalyticsPayment provider (Stripe...)Realtime gatewaySSE / WebSocketGate scannersoffline QR checkStrict consistency: inventory and orders (one PostgreSQL primary per event partition). Everything else is eventual.

Read the picture from left to right. The crowd never touches the origin until the waiting room admits it. The only strictly consistent part of the system is the inventory and order data in PostgreSQL, one primary per event partition. Everything to the right of the outbox (tickets, email, analytics, the seat-map push) is eventually consistent and may lag by seconds without breaking anything.

Why it exists ​

Most systems scale reads. A ticketing on-sale is the opposite: a small, fixed inventory (50,000 seats) meets a crowd much larger than the inventory, all arriving in the same minute, and every buyer wants the same few hundred best seats. The difficulty is not throughput. 125 row updates a second is nothing for PostgreSQL. It is three things at once: correctness under contention (two buyers, one seat), fairness under overload (who gets in first, and can a script cheat), and ambiguity under failure (the card was charged but the response was lost). This is why the problem is the standard capstone for system design.

Design pressureWeaker answerStronger answer
CorrectnessCheck "is it free?" then writeOne writer per seat: a lock, a conditional update or an atomic script
OverloadAutoscale the origin and hopeAdmission control at the edge: a virtual waiting room
FairnessFirst request wins (bots win)Randomised pre-queue, then FIFO, plus bot defence
Payment failureRetry the chargeIdempotency key at the provider, outbox, saga with compensation
Inventory after a crashIn-memory holdsHolds as rows with a deadline; Redis only as a rebuildable gate
Ticket forgerySequential ticket numbersSigned QR codes, offline validation, revocation

Everyday picture. A theatre box office on the morning of a sold-out premiere. A doorman lets ten people at a time into the lobby (the waiting room), handing each a numbered slip (the admission token). Inside, a clerk holds the seating chart and a pencil. Only the clerk writes on the chart (the single writer). When you point at seat 14, the clerk pencils your name in with a time ("held until 10:08"). If you pay at the cashier before 10:08, the pencil becomes ink. If not, the clerk rubs it out (hold expiry) the next time anyone asks about that seat, or on the half-hourly walk along the chart (the sweeper). The ticket you get has a stamp the usher at the door can check without phoning the box office (offline validation). We come back to the clerk, the pencil and the stamp throughout the page.

Three common misunderstandings, up front ​

  1. "It is a scale problem, so shard and cache." The write rate is tiny. The problem is contention on a few hot rows plus a crowd at the edge. Sharding the seats of one event across nodes makes multi-seat holds harder and helps nothing.
  2. "A distributed lock in Redis prevents double-selling." A lock with a TTL can expire while its holder is paused, and then two holders exist. The invariant has to be enforced where the sale is recorded: a conditional write in the database (and a unique constraint as the last line of defence). See Distributed Locking.
  3. "The waiting room is for fairness, so FIFO is fair." Ticketmaster's own explanation (quoted at the top) is the opposite: a pure first-come order rewards whoever is fastest, which is scripts. Fairness comes from randomising the early arrivals and from bot defence, and the queue's real engineering job is admission control.

Where it comes from ​

There is no single paper on ticketing. The design here combines primary documentation of the building blocks with vendor descriptions of waiting rooms. Each fact below was read on the page cited in References.

Building blockSource and what it saysUsed for
Row locksPostgreSQL docs, Explicit Locking: FOR UPDATE "prevents them from being locked, modified or deleted by other transactions until the current transaction ends"Single writer
SKIP LOCKEDPostgreSQL SELECT docs: "Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table."Best available, sweeper, outbox relay
Advisory locksPostgreSQL docs: locks "that have application-defined meanings", not enforced by the systemSweeper leadership (optional)
Atomic scriptsRedis docs, Scripting with Lua: "Redis guarantees the script's atomic execution."Redis Lua hold
Expiry timingRedis keyspace notifications: "there are no guarantees that the Redis server will be able to generate the expired event at the time the key time to live reaches the value of zero"Why the sweeper does not rely on expiry events
IdempotencyStripe API: keys "up to 255 characters long"; v1 keys can be removed "after they're at least 24 hours old"Payment
Waiting room (vendor)Ticketmaster: "Only a few hundred people can shop at once—fewer for smaller venues"Admission rate is a design input
Waiting room (vendor)Queue-it: early visitors "are randomized, just like a raffle"; later visitors proceed "in a first-in, first-out order"Randomised admission
Waiting room (product)Cloudflare Waiting Room: thresholds "total active users" and "new users per minute"; queueing methods FIFO, Random, Passthrough, RejectKnobs in Mechanics
Waiting room (reference)AWS "Virtual Waiting Room on AWS": the page now carries a "Notice of discontinuation"Build-or-buy: a reference implementation can disappear
OverloadGoogle SRE Book, Handling Overload: "redirect when possible, serve degraded results when necessary, and handle resource errors transparently when all else fails"Failure scenarios
Sagamicroservices.io: "A saga is a reliably coordinated sequence of local transactions" undone "by compensating transactions"Payment

The concept catalogue ​

The catalogue follows the four steps. Steps 1 to 3 are short, because the method chapter teaches them; step 4 is the bulk, one block per deep dive. Each deep-dive block follows the site's order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.

Step 1: functional scope Must-know ​

In plain words: write down the exact user journeys before drawing anything, because each one is a path through the system with its own consistency need.

Common misunderstanding: "Ticketing is just e-commerce with seats." E-commerce stock is fungible (any of 40 identical mugs). Reserved seating is not: seat S112-R07-14 exists once, a buyer chose that one, and "sold out" happens in minutes. General admission (standing tickets) is the fungible case and is easier: a counter with a conditional decrement.

FeatureIn scopeConsistency needNotes
Browse events, search, event pageYesEventual (cache, CDN)Catalogue changes rarely
View seat map with availabilityYesEventual, seconds of lag acceptableGeometry static (CDN); availability pushed
Hold seats (pick exact, or best available)YesStrictThe single writer
Pay (card via a provider)YesStrict per order, idempotentProvider is external
Issue tickets (QR), emailYesEventual, at-least-onceAsync from the outbox
Transfer to a friend, resale marketplaceYesStrict on ownershipGeneration bump revokes old QR
Check-in scanning at the gateYesOffline-capableNetwork at stadiums is unreliable
Dynamic pricing, recommendations, ads, seat-view photosNo (out of scope)Written as non-goals
Organiser back office (create events, price tiers)MinimalStrict, low volumeAdmin path, not on the hot path

Assumptions written down: reserved seating only; a maximum of 6 tickets per order; accounts required to enter the queue; one payment provider (Stripe-like) with idempotency keys; one primary region, a warm standby region.

Step 1: non-functional requirements and the invariant Must-know ​

In plain words: some targets are percentages you can miss a little (latency, availability); one is an invariant you can never miss (no double-selling). Keep them in separate lists.

Common misunderstanding: "99.99% availability includes not double-selling." An SLO allows a budget of failures; an invariant allows none. Double-selling is a correctness bug, not an availability incident, and you design it out instead of budgeting for it. See SLAs, SLOs, SLIs & Error Budgets.

RequirementTargetWhy this number
No double-selling, everInvariant: at most one valid ticket per (event, seat)Refunds, angry fans at the gate, press
Fairness under flash saleEarly arrivals have an equal chance; no advantage from refresh or many tabsTicketmaster and Queue-it both describe this as the goal
Concurrent buyers100,000 in the waiting room for a 50,000-seat eventGiven by the prompt; real hot events can be far larger
Hold latencyp99 under 300 ms at the originThe buyer is staring at the seat map
Availability update lagp99 under 2 s from hold to other buyers' mapsFewer clicks on seats that are already gone
Payment confirmp99 under 5 s, provider-boundCard networks set the floor
On-sale availability99.95% of hold and checkout requests during on-sale windowsError budget spent in minutes, so failure modes matter more than the number
Scan latencyUnder 200 ms per scan, offlineA gate processes a fan every few seconds
DurabilityNo confirmed sale lost (RPO 0 for orders)Synchronous replication for the inventory database

Latency targets are p99, not averages, because the slowest 1% of holds belong to the buyers fighting over the best seats. See Latency Budgets & Tail Latency.

Step 2: the estimate Must-know ​

In plain words: turn the crowd into numbers and see which number is scary. For ticketing the scary numbers are at the edge and on a few rows, not in the database's throughput.

Common misunderstanding: "100,000 concurrent users means 100,000 QPS at the database." The waiting room converts the crowd into a controlled admission rate; the database sees the active shoppers' holds, about 50 a second. The estimate's job is to show that, so nobody shards the inventory for no reason. Method: Back-of-the-Envelope Capacity Estimation.

text
Inputs (assumptions from step 1)
1  seats = 50,000; tickets per order = 2.5          -> orders = 20,000
2  active shoppers cap = 5,000; session = 5 min     -> admissions = 1,000 / min
3  orders / admissions                             -> sell-out in 20 min
4  waiting room: 100,000 visitors poll every 20 s   -> 5,000 req/s at the EDGE
5  origin API: 5,000 shoppers x 2 req/s             -> 10,000 QPS
6  holds: 5,000 x 3 attempts / 300 s                -> 50 holds/s, x 2.5 seats = 125 row writes/s
7  payments: 20,000 orders / 1,200 s                -> 16.7/s average (plan 3x: 50/s)
8  seat map: 250 KB gz x 1,000 admits/min           -> 4.1 MB/s from the CDN
9  no waiting room: 100,000 x 250 KB at T0          -> 23.8 GB burst
10 servers: ceil(10,000 / (1,000 x 0.6)) + 2         -> 19 API instances
QuantityFormulaValueWhere it lands
Seat rows per event50,000 x 150 B (row, tuple header, index share)7.5 MBFits in memory many times over
Tickets + orders per year20 M tickets x 300 B + 8 M orders x 500 B10 GBOne PostgreSQL cluster for years
Availability bitmap50,000 bits6.1 KBSnapshot from the CDN every few seconds
Hold cache (Redis option)50,000 keys x about 100 B5 MB per eventTrivial
Catalogue cache5,000 live events x 50 KB250 MBOne Redis node or the CDN
Realtime fan-out5,000 open maps x 1 batched delta/s x 200 B1 MB/sOne or two Reverb or SSE nodes
Analytics events100,000 visitors x 50 events x 200 B1 GB per hot on-saleStream, not the OLTP database

Where it is big: the edge (5,000 polls a second and a 24 GB burst you avoid by queueing) and the contention (the first 1,000 admitted buyers all click the front rows). Where it is small: storage, payments, row writes. That result drives step 3: spend the design on the edge and on the single writer, keep the data layer one ordinary PostgreSQL cluster.

Step 3: API design Must-know ​

In plain words: design the endpoints first; the hold and the order are separate resources, so a hold can expire without an order and an order can be retried without a second hold.

Common misunderstanding: "One POST /buy endpoint is simpler." It merges a fast, contended step (hold) with a slow, external one (payment), so a slow card network keeps seat locks open for seconds. Splitting them keeps the critical section in milliseconds. Resource design: REST API Design.

Method and pathPurposeIdempotencyErrors
GET /events/{id}Event pageSafe, CDN-cached 60 s404
GET /events/{id}/seatmapStatic geometry (sections, rows, coordinates)Safe, CDN, versioned URL404
GET /events/{id}/availabilityBitmap snapshot plus sequence numberSafe, cached 1-2 s503 under load shedding
GET /events/{id}/availability/streamSSE deltas (or a WebSocket channel)SafeReconnect with Last-Event-ID
POST /waiting-room/{event}/joinEnter the queue, get a positionIdempotent per account429
POST /events/{id}/holdsHold exact seats or best availableHold id returned; retry gets 409 if already yours409 seat taken, 429 rate limit, 401 no admission token
DELETE /events/{id}/holds/{hold}ReleaseIdempotent, 204 twice
POST /events/{id}/ordersCheckout with Idempotency-KeySame key returns the same order410 hold expired, 422 key reused
GET /orders/{id}Status for pollingSafe
POST /tickets/{id}/transferTransfer to another accountIdempotency-Key409 already scanned
POST /tickets/{id}/listingsList on resaleIdempotency-Key422 above price cap
POST /scans (batch upload)Gate devices upload scans when onlineIdempotent by scan id

Data model: seats as rows Must-know ​

In plain words: every seat of every event is one row with a state, and every state change is an UPDATE with a condition. The row is the clerk's pencil mark.

Common misunderstanding: "Store availability as a counter per section, or as a JSON blob per event." A counter cannot tell which seat; a blob turns 50,000 independent seats into one hot row that every buyer must lock. Rows give the database the lock granularity of one seat.

text
seats (event_id, seat_id) PK            partitioned by HASH(event_id)
  section, row_no, seat_no, price_cents
  state            available | held | sold      CHECK constraint
  hold_id, hold_expires_at                     set together (CHECK)
  order_id                                     set iff sold (CHECK)
  version                                      optimistic locking
orders (order_id) -> idempotency_keys (user_id, key) -> outbox (id, topic, aggregate_id)
tickets (ticket_id, event_id, seat_id, generation, owner_id, status)
  UNIQUE (event_id, seat_id) WHERE status IN (valid, scanned)   last line of defence
resale_listings (... CHECK (price_cents <= face_cents * 110 / 100))   price cap

The full schema, with partial indexes for "best available" and for the sweeper, is below. The CHECK constraints make illegal states unrepresentable: a held seat without a deadline, or a sold seat without an order, cannot be stored.

sql
-- Ticketing schema (PostgreSQL 16+). Seats are rows; the seats table is
-- partitioned by event so a hot on-sale touches one partition only.
CREATE TABLE events (
    event_id      text PRIMARY KEY,
    venue_id      text NOT NULL,
    starts_at     timestamptz NOT NULL,
    on_sale_at    timestamptz NOT NULL,
    max_per_order int NOT NULL DEFAULT 6,
    status        text NOT NULL DEFAULT 'scheduled'   -- scheduled | on_sale | sold_out | ended
);

CREATE TABLE seats (
    event_id        text NOT NULL,
    seat_id         text NOT NULL,                    -- e.g. 'S112-R07-14'
    section         text NOT NULL,
    row_no          int  NOT NULL,
    seat_no         int  NOT NULL,
    price_cents     int  NOT NULL,
    state           text NOT NULL DEFAULT 'available'
                    CHECK (state IN ('available', 'held', 'sold')),
    hold_id         text,
    hold_expires_at timestamptz,
    order_id        text,
    version         bigint NOT NULL DEFAULT 0,        -- optimistic locking
    PRIMARY KEY (event_id, seat_id),
    CHECK ((state = 'held') = (hold_id IS NOT NULL AND hold_expires_at IS NOT NULL)),
    CHECK ((state = 'sold') = (order_id IS NOT NULL))
) PARTITION BY HASH (event_id);

CREATE TABLE seats_p0 PARTITION OF seats FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE seats_p1 PARTITION OF seats FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE seats_p2 PARTITION OF seats FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE seats_p3 PARTITION OF seats FOR VALUES WITH (MODULUS 4, REMAINDER 3);

-- best-available search and the sweeper each get a small partial index
CREATE INDEX seats_available ON seats (event_id, section, row_no, seat_no)
    WHERE state = 'available';
CREATE INDEX seats_hold_expiry ON seats (event_id, hold_expires_at)
    WHERE state = 'held';
CREATE INDEX seats_by_hold ON seats (event_id, hold_id) WHERE hold_id IS NOT NULL;

CREATE TABLE orders (
    order_id     text PRIMARY KEY,
    user_id      text NOT NULL,
    event_id     text NOT NULL REFERENCES events,
    hold_id      text NOT NULL,
    amount_cents bigint NOT NULL,
    status       text NOT NULL DEFAULT 'pending_payment',
    -- pending_payment | paid | payment_failed | refund_required | refunded
    created_at   timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE idempotency_keys (
    user_id     text NOT NULL,
    key         text NOT NULL,
    fingerprint text NOT NULL,                        -- sha256 of the request body
    order_id    text NOT NULL REFERENCES orders,
    created_at  timestamptz NOT NULL DEFAULT now(),   -- prune after 24 h
    PRIMARY KEY (user_id, key)
);

CREATE TABLE outbox (
    id           bigserial PRIMARY KEY,
    topic        text NOT NULL,       -- ChargeRequested | IssueTickets | SeatsReleased | RefundPayment
    aggregate_id text NOT NULL,       -- order id: the relay keeps per-order order
    payload      jsonb NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now(),
    sent_at      timestamptz
);
CREATE INDEX outbox_unsent ON outbox (id) WHERE sent_at IS NULL;

CREATE TABLE tickets (
    ticket_id   text PRIMARY KEY,
    order_id    text NOT NULL REFERENCES orders,
    event_id    text NOT NULL,
    seat_id     text NOT NULL,
    owner_id    text NOT NULL,
    generation  int  NOT NULL DEFAULT 1,              -- bumped on transfer/resale
    status      text NOT NULL DEFAULT 'valid',        -- valid | revoked | scanned
    UNIQUE (event_id, seat_id, generation)
);
-- second line of defence: at most one valid ticket per seat, ever
CREATE UNIQUE INDEX one_valid_ticket_per_seat ON tickets (event_id, seat_id)
    WHERE status IN ('valid', 'scanned');

CREATE TABLE resale_listings (
    listing_id  text PRIMARY KEY,
    ticket_id   text NOT NULL REFERENCES tickets,
    seller_id   text NOT NULL,
    price_cents bigint NOT NULL,
    face_cents  bigint NOT NULL,
    status      text NOT NULL DEFAULT 'listed',       -- listed | in_escrow | sold | withdrawn
    CHECK (price_cents <= face_cents * 110 / 100)     -- price cap rule: face + 10%
);

Services and data flow Important ​

In plain words: one service owns writes to seats; everyone else asks it, or listens to what it published.

Common misunderstanding: "Microservices means each service gets its own copy of seat state." Two writers to seat state is exactly the double-selling bug. The inventory service is the single writer; the order service owns orders; they can share one PostgreSQL cluster (different schemas) at this scale. See Data Ownership in Microservices.

ServiceOwnsTalks toConsistency
CatalogueEvents, venues, price tiers, seat-map geometryCDN (publishes static files)Eventual
Inventory / allocationSeat state, holds, the sweeperPostgreSQL (seats partition), Redis (optional gate)Strict, single writer
OrderOrders, idempotency keys, outboxInventory (confirm/release), outbox relayStrict per order
PaymentCharges, refunds, provider callsProvider API with its own idempotency keyStrict per charge, async to order
Ticket issuanceTickets, QR signing, generationsConsumes IssueTicketsAt-least-once, idempotent
NotificationEmail, push, wallet passesConsumes TicketsIssuedAt-least-once
Check-inGate device sync, revocation lists, scan uploadsTicket service, devicesOffline-first
Realtime gatewaySSE/WebSocket connectionsConsumes seat-change eventsBest-effort, snapshot on gap
Waiting room (edge)Queue positions, admission tokensOrigin capacity signalIts own store at the edge
text
write path (numbered)                                   read path
1 waiting room admits visitor -> admission token        a GET seatmap from CDN (static)
2 POST /holds -> inventory: FOR UPDATE, UPDATE held     b GET availability snapshot (1-2 s cache)
3 inventory publishes SeatsChanged -> realtime push     c SSE deltas apply to the bitmap
4 POST /orders (Idempotency-Key) -> order + outbox      d GET /orders/{id} polls status
5 relay -> ChargeRequested -> payment -> provider
6 PaymentSucceeded -> inventory confirm (sold) + outbox IssueTickets
7 ticket issuance -> QR -> notification -> email/wallet

Edge: CDN seat maps and waiting room placement Important ​

In plain words: everything that is the same for every buyer is a file on the CDN; the only thing that differs, which seats are free, is a tiny bitmap.

Common misunderstanding: "The seat map is dynamic, so it cannot be cached." The geometry (50,000 seat shapes and labels) never changes during a sale; only availability does. Split them: geometry at a versioned URL with a long cache lifetime, availability as a 6 KB bitmap with a 1-2 s lifetime, plus pushed deltas. See CDNs and Caching.

AssetSizeCacheProduct
Seat-map geometry (SVG or JSON)about 250 KB gzippedCache-Control: public, max-age=31536000, immutable, versioned pathCloudflare, Fastly, Amazon CloudFront
Availability bitmap6.1 KBmax-age=1 with stale-while-revalidate at the CDNSame CDN, short TTL
Event page50 KB60 s, purge on changeCDN plus Redis
Waiting room page and statusSmallServed by the waiting-room productCloudflare Waiting Room, Queue-it, a custom edge worker

Pre-warm before the on-sale: push the seat map to the CDN and request it from several regions so the first 100,000 requests are cache hits; load the event's seat rows into memory (pg_prewarm or a warm-up query) and the catalogue into Redis; scale the API to the step-2 instance count 30 minutes before the start, because autoscaling reacts in minutes and the spike lasts seconds.

Realtime seat availability Important ​

In plain words: when a seat is held, everyone looking at that section should see it turn grey within a second or two, so they stop clicking it.

Common misunderstanding: "Realtime availability must be exact." It is a hint. The hold endpoint is the truth; if a buyer clicks a seat that was taken 300 ms ago, the answer is a 409 and the map updates. Push reduces wasted clicks; it does not prevent double-selling.

text
T0      buyer A holds S112-R07-14 (inventory commits)
T0+5ms  inventory publishes SeatsChanged{seq: 8812, seats: [S112-R07-14], state: held}
T0+40ms realtime gateway batches deltas for 250 ms per event channel
T0+300ms 5,000 open maps receive one SSE message with the batch
T0+310ms buyer B's map greys the seat; B had not clicked yet: saved a 409
gap     client sees seq 8815 after 8812 -> refetches the bitmap snapshot
OptionDirectionFits ticketing becauseProduct
Short polling of the bitmapPullSimple, CDN-cacheable, 1-2 s stalenessAny CDN
SSEServer to clientOne-way deltas, auto-reconnect with Last-Event-IDNGINX, Envoy in front of a Go SSE server
WebSocketBoth waysNeeded only if the client also sends over the same channelLaravel Reverb, Socket.IO, AWS API Gateway WebSockets

Mechanics of each option, connection limits and presence live in Real-Time Communication.

Preventing double-selling: single writer per seat Must-know ​

In plain words: at any moment only one transaction may be deciding what happens to a given seat. Whoever gets that right first wins the seat; everyone else is told "taken" quickly.

Common misunderstanding: "Check if it is available, then insert the sale." Two requests both read "available", both write "sold". The read and the write must be one atomic step, or the read must take a lock that the second reader waits on. Isolation alone does not save you: at PostgreSQL's default Read Committed a plain SELECT takes no lock. See Isolation Levels.

Definition: a seat has a single writer when every state change goes through an operation that is atomic with respect to the seat: a row lock held across check and write, a conditional UPDATE whose WHERE re-checks the state, a compare-and-set on a version column, or a Redis script that runs alone. The invariant "at most one valid ticket per seat" is then backed by a unique index, so even a bug upstream fails loudly instead of selling twice.

text
     Buyer A (tx 1)                                Buyer B (tx 2)
1    BEGIN
2    SELECT ... seat_id IN (13,14) ORDER BY seat_id FOR UPDATE   -> locks 13, 14
3                                                  BEGIN
4                                                  SELECT ... seat_id IN (14,15) ... FOR UPDATE
5                                                  -> waits on 14 (lock_timeout 200 ms)
6    UPDATE seats SET state='held', hold_id='hA' ... COMMIT  (locks released)
7                                                  -> gets 14, re-reads: state='held', not free
8                                                  -> row filtered out, 1 of 2 rows: ROLLBACK, 409
     without FOR UPDATE: both SELECTs see 'available' at step 2 and 4; both UPDATEs succeed

Real scenario: two friends on two phones pick the same pair of seats; a bot fires 50 hold requests for the front row in the same millisecond; a buyer double-clicks "hold"; a retry after a timeout arrives while the first attempt is still running; the sweeper frees an expired hold while its owner is confirming payment.

What provides it:

ProductPrimitiveBehaviour under contentionError when it gives up
PostgreSQLSELECT ... FOR UPDATEWaits; after the first commits, re-checks the rowlock_timeout -> SQLSTATE 55P03 lock_not_available
PostgreSQLFOR UPDATE NOWAITFails immediately if locked55P03
PostgreSQLFOR UPDATE SKIP LOCKEDSkips locked rowsNone (fewer rows returned)
PostgreSQLConditional UPDATE ... WHERE state='available'Second updater waits, re-evaluates WHERE, updates 0 rowsNone (UPDATE 0)
PostgreSQLUnique partial index on valid ticketsSecond insert fails23505 unique_violation
MySQL InnoDBSELECT ... FOR UPDATE [SKIP LOCKED / NOWAIT] (8.0+)Similar; next-key locks on ranges1205 lock wait timeout, 1213 deadlock
RedisEVAL Lua script; SET key val NX PX ttl for one seatRuns alone, no waitingScript returns "taken"
LaravelDB::transaction + lockForUpdate(); ->lock('for update skip locked')Same as PostgreSQLQueryException with the SQLSTATE

Fix / how to use it: the four hold queries (exact seats with FOR UPDATE, best available with SKIP LOCKED, the optimistic version column, and the checkout transaction) are in one SQL file; the Go and Laravel versions follow in Go and Laravel. The smallest correct form, a single conditional statement, already gives one writer, because a concurrent updater waits for the row and then re-evaluates the WHERE clause against the committed version:

sql
UPDATE seats
SET state = 'held', hold_id = 'h-7f3a', hold_expires_at = now() + interval '8 minutes'
WHERE event_id = 'ev1' AND seat_id = 'S112-R07-14' AND state = 'available';
-- UPDATE 1: you hold it.  UPDATE 0: somebody else does.
sql
-- 1. Hold chosen seats: lock in seat_id order, check, mark held.
BEGIN;
SET LOCAL lock_timeout = '200ms';                    -- hot row -> 55P03, answer 409
SELECT seat_id FROM seats
WHERE event_id = 'ev1' AND seat_id = ANY('{S112-R07-13,S112-R07-14}')
  AND (state = 'available' OR (state = 'held' AND hold_expires_at <= now()))
ORDER BY seat_id
FOR UPDATE;
-- application: if fewer rows than requested -> ROLLBACK, 409 seat_unavailable
UPDATE seats SET state = 'held', hold_id = 'h-7f3a',
       hold_expires_at = now() + interval '8 minutes', version = version + 1
WHERE event_id = 'ev1' AND seat_id = ANY('{S112-R07-13,S112-R07-14}');
COMMIT;

-- 2. Best available: n seats in a section, never wait behind another buyer.
WITH picked AS (
  SELECT seat_id FROM seats
  WHERE event_id = 'ev1' AND section = 'S112' AND state = 'available'
  ORDER BY row_no, seat_no
  LIMIT 2
  FOR UPDATE SKIP LOCKED
)
UPDATE seats s SET state = 'held', hold_id = 'h-91bc',
       hold_expires_at = now() + interval '8 minutes', version = s.version + 1
FROM picked WHERE s.event_id = 'ev1' AND s.seat_id = picked.seat_id
RETURNING s.seat_id;

-- 3. Optimistic alternative (one seat, version read earlier = 41).
UPDATE seats SET state = 'held', hold_id = 'h-22aa',
       hold_expires_at = now() + interval '8 minutes', version = version + 1
WHERE event_id = 'ev1' AND seat_id = 'S112-R07-14' AND version = 41
  AND state = 'available';
-- UPDATE 0 -> somebody else won; re-read and offer another seat

-- 4. Checkout: order + idempotency key + outbox row in ONE transaction.
BEGIN;
INSERT INTO orders (order_id, user_id, event_id, hold_id, amount_cents)
VALUES ('ord-1001', 'u-42', 'ev1', 'h-7f3a', 15000);
INSERT INTO idempotency_keys (user_id, key, fingerprint, order_id)
VALUES ('u-42', '5b0c2a6e-3c1d-4b8e-9a51-6f0c8e2d7a10', 'sha256:...', 'ord-1001');
-- duplicate key -> 23505 unique_violation: roll back and return the stored order
INSERT INTO outbox (topic, aggregate_id, payload)
VALUES ('ChargeRequested', 'ord-1001', '{"amount_cents":15000,"idempotency_key":"ord-1001-charge"}');
UPDATE seats SET hold_expires_at = now() + interval '15 minutes'   -- extend hold for payment
WHERE event_id = 'ev1' AND hold_id = 'h-7f3a' AND state = 'held' AND hold_expires_at > now();
COMMIT;

-- 5. Payment succeeded: confirm seats (only a live hold) and emit IssueTickets.
BEGIN;
UPDATE seats SET state = 'sold', order_id = 'ord-1001', hold_id = NULL,
       hold_expires_at = NULL, version = version + 1
WHERE event_id = 'ev1' AND hold_id = 'h-7f3a' AND state = 'held' AND hold_expires_at > now();
-- UPDATE 0 -> hold expired: status refund_required + outbox RefundPayment
UPDATE orders SET status = 'paid' WHERE order_id = 'ord-1001' AND status = 'pending_payment';
INSERT INTO outbox (topic, aggregate_id, payload) VALUES ('IssueTickets', 'ord-1001', '{}');
COMMIT;

-- 6. Sweeper: free expired holds in batches without blocking buyers.
WITH expired AS (
  SELECT seat_id FROM seats
  WHERE event_id = 'ev1' AND state = 'held' AND hold_expires_at <= now()
  LIMIT 500
  FOR UPDATE SKIP LOCKED
)
UPDATE seats s SET state = 'available', hold_id = NULL, hold_expires_at = NULL,
       version = s.version + 1
FROM expired WHERE s.event_id = 'ev1' AND s.seat_id = expired.seat_id;

-- 7. Outbox relay: several relay workers, no double publish of one row.
BEGIN;
SELECT id, topic, aggregate_id, payload FROM outbox
WHERE sent_at IS NULL ORDER BY id LIMIT 100
FOR UPDATE SKIP LOCKED;
-- publish each, then:
UPDATE outbox SET sent_at = now() WHERE id = ANY('{101,102,103}');
COMMIT;

-- 8. Rebuild Redis holds after a Redis loss (PostgreSQL is the record).
SELECT seat_id, hold_id, extract(epoch FROM hold_expires_at - now()) * 1000 AS ttl_ms
FROM seats WHERE event_id = 'ev1' AND state = 'held' AND hold_expires_at > now();
SELECT seat_id, order_id FROM seats WHERE event_id = 'ev1' AND state = 'sold';

-- 9. Watch contention during the on-sale.
SELECT pid, wait_event_type, wait_event, now() - query_start AS waiting, left(query, 60)
FROM pg_stat_activity WHERE wait_event_type = 'Lock';
SELECT state, count(*) FROM seats WHERE event_id = 'ev1' GROUP BY state;

Three rules make the row-lock version safe and fast. Lock in a fixed order (ORDER BY seat_id), so two buyers with overlapping selections cannot deadlock (40P01). Bound the wait with SET LOCAL lock_timeout = '200ms', so a hot row turns into a quick 409 instead of a pile of waiting connections. Keep the transaction short: no network calls (no payment, no email) inside it. Deadlock mechanics are in Deadlocks.

Strict consistency for inventory, eventual for everything else. The seat state needs a single primary and synchronous commits. The seat map, the event page, search results, emails and analytics may be seconds stale. That split is what lets the design stay small: only one component needs consensus-grade guarantees, and PostgreSQL's single primary per partition already provides them. See Consistency Models.

Seat holds with expiry Must-know ​

In plain words: a hold is a reservation with a deadline. If the buyer does not pay in time, the seat goes back on sale without anyone having to remember to free it.

Common misunderstanding: "A background job releases expired holds, so until it runs the seat is stuck." Correctness must not depend on the sweeper. The hold query itself treats a hold whose hold_expires_at has passed as free (lazy expiry). The sweeper only makes the seat visible again to "best available" queries and to the availability feed.

Definition: a seat hold (reservation) is the state held with an owner (hold_id) and a deadline (hold_expires_at, set by the database clock as now() + TTL). Transitions: hold (available or expired -> held), extend (only by the owner, only while live), confirm (owner, live -> sold), release (owner -> available, idempotent), expire (deadline passed -> available, lazily or by the sweeper).

availableheldhold_id, expires_atsoldorder_id, ticketshold (one winner)TTL 8 minrelease / payment failed /expired (lazy or sweeper)payment ok beforedeadline: confirmextend once at checkout (15 min)transfer / resale: generation+1old QR revoked, seat stays soldpayment after expiry: cannotconfirm, refund (compensation)
text
     Buyer                    Inventory (DB clock)                 Sweeper (every 1 s)
1    POST /holds  ->          held, expires 19:08:00
2    picks shipping...        (19:07:55) POST /orders -> extend to 19:22:55 (once)
3    card 3-D Secure prompt
4    abandons the tab
5                             19:22:55 deadline passes             19:22:56 batch: 500 rows,
6                                                                    SKIP LOCKED -> available
7    late webhook: paid       confirm: UPDATE ... hold_expires_at > now() -> 0 rows
8                             order -> refund_required, outbox RefundPayment

Real scenario: a buyer opens the card form and goes to find the card; a phone loses signal during 3-D Secure; a bot holds 6 seats in every section and never pays (hold limits per admission token stop this); a payment webhook arrives after the deadline; two sweeper instances run during a deploy.

Design choiceRecommendedWhy
TTL length8 min to pick and enter details; one extension to 15 min when checkout startsLong enough for 3-D Secure; short enough that abandoned seats return during the on-sale
ClockDatabase now() for both setting and checking the deadlineOne clock: app servers' clocks can drift; Redis TTLs use the Redis server clock
ExtensionServer-side, once, at checkout; never from a client heartbeatA heartbeat lets a bot hold seats forever
ExpiryLazy check in every hold query plus a sweeperRedis expired events are not on time ("no guarantees", Redis docs)
SweeperBatches of 500 with SKIP LOCKED, one per partition or under an advisory lockShort transactions; never blocks a buyer
ReleaseWHERE hold_id = $1 AND state = 'held'Idempotent; a late release cannot free someone else's new hold

Fix / how to use it: the Go MemStore.Hold treats expired holds as free, Release matches on owner, and Sweeper.RunOnce loops in batches; the tests freeze a fake clock to prove a confirm after expiry fails and a late release frees nothing that is not its own.

Flash-sale fairness: waiting room, admission tokens, bots Must-know ​

In plain words: let people into the shop at the rate the shop can serve, decide the order fairly, and make it expensive for scripts to cut the line.

Common misunderstanding: "Rate limiting is enough." A per-IP rate limit protects the origin from one client; it does not decide who among 100,000 humans goes first, and residential proxy networks give a bot thousands of IPs. The waiting room solves admission and order; rate limiting and bot defence solve abuse after admission.

Definition: a virtual waiting room is an edge component that holds visitors before the protected pages, admits them at a rate derived from the origin's capacity, and gives each admitted visitor an admission token. Queue-it describes the hand-off as visitors being "flowed back to the site with a unique Queue token". Cloudflare Waiting Room sizes the flow with two thresholds, "total active users" and "new users per minute", and gives each user a cookie.

Pre-queue (T-30 min)join early, any orderbot checks at joinone place per accountStart (T0): shuffle oncerandomised admissionrefresh does not helpposition shown to userLate arrivalsjoin the back: FIFOafter all early visitorsAdmission controllerslots = cap - active5,000 cap, 5 min sessionabout 1,000 per minuteOrigin (on-sale API)verifies HMAC tokenno lookup, exp 10 minrate limit per visitorStatus pollsserved at the edge100k / 20 s = 5k req/sToken: base64url(e, v, p, nbf, exp) + "." + HMAC-SHA256session ends: slot frees
text
T-30 min  waiting room opens; 100,000 visitors join the pre-queue (bot checks at join)
T0        pre-queue shuffled once: positions 1..100,000 at random (refresh does not help)
T0+1s     late visitors join behind position 100,000 in FIFO order
T0..      admission controller: slots = 5,000 cap - active shoppers -> admit that many
          each admitted visitor: token {e, v, p, nbf, exp=+10 min} + HMAC-SHA256
          origin middleware verifies the token: no database, no Redis, a few microseconds
T0+20min  last seat sold -> waiting room shows "sold out", stops admitting

Real scenario: a superstar tour on-sale; a sneaker drop; a limited conference registration; a presale code for fan-club members (a separate protected queue); a bot farm opening 10,000 tabs (one place per account, device fingerprinting, CAPTCHA at join, not at T0).

Admission policyWho goes firstFair toWeaknessProducts
Pure FIFO from T0Fastest requestScripts and people near the data centreRewards speed and refresh stormsCloudflare Waiting Room FIFO (the default method)
Randomised pre-queue, then FIFORandom among early arrivals, then arrival orderEveryone who came before T0Feels like a lottery; must explain itQueue-it (described in its own blog); Ticketmaster's waiting room (vendor blog)
Random throughoutRandom at every admissionEveryone, any timeNo reward for arriving earlyCloudflare Waiting Room Random (plan-dependent: "Only certain customers can use queue methods besides First In First Out")
Invite / lottery registrationDrawn days beforeVerified fansExtra product flowOrganiser-specific
Bot defence layerWhereExample
Account required to queueJoinOne position per account (Room.Join is idempotent per visitor)
Challenge at join, not at T0Join, before the rushCAPTCHA or managed challenge (Cloudflare Turnstile)
Token bound to the visitorEvery origin requestToken carries visitor id; compare with session
Rate limit after admissionOriginLaravel RateLimiter::for('onsale-holds'), 20 holds/min per visitor
Hold limitsInventoryMax 6 seats per order, max one live hold per token
Behaviour signalsEdge and originTicketmaster warns that refreshing "could get you flagged as a bot"

Fix / how to use it: the Go waitingroom package issues and verifies HMAC tokens and implements shuffle-then-FIFO; the Laravel middleware verifies the same token format. The admission rate is a capacity decision: Ticketmaster says "Only a few hundred people can shop at once", which is the same idea as the 5,000-shopper cap here (our number is an assumption sized for a 50,000-seat stadium). Limit algorithms: Rate Limiting; shedding the rest: Load Shedding.

Payment ambiguity: idempotency key, outbox, saga Must-know ​

In plain words: a payment call can end three ways: yes, no, and "I don't know" (timeout). The design must make retrying "I don't know" safe and must undo the seat hold when the answer is no.

Common misunderstanding: "Wrap the seat update and the charge in one transaction." The payment provider is not in your database; there is no transaction across them. Holding seat locks during a card authorisation also stretches a millisecond critical section to seconds. Instead: hold first (short transaction), charge outside, confirm after (short transaction), compensate on failure.

Definition: the purchase is a saga ("a reliably coordinated sequence of local transactions", microservices.io) with three local steps: checkout (order + idempotency key + ChargeRequested outbox row in one transaction), charge (payment service calls the provider with an idempotency key derived from the order id), and confirm (seats held -> sold only if the hold is live, plus IssueTickets outbox row). Compensations: payment failed -> release the seats; paid after the hold expired -> refund (or re-hold if the seats are still free).

1. Checkout (one transaction)order: pending_paymentidempotency key + fingerprintoutbox: ChargeRequestedhold extended to 15 min2. Relay and payment workerpublish ChargeRequestedprovider call with key"ord-1001-charge"timeout: retry same key3a. Paid before deadlineseats held to soldoutbox: IssueTicketstickets, QR, email (async)3b. Payment failedcompensate: release seatsoutbox: SeatsReleased3c. Paid after hold expiredconfirm updates 0 rowscompensate: RefundPaymentor re-hold if seats still freeInvariantsA seat is sold only by a live hold (WHERE hold_expires_at > now()).Every step is idempotent: webhook replays find the order already moved.Unique (event, seat) on valid tickets is the last line of defence.Unknown payment outcome: ask the provider, never guess.
text
     Browser                Order service               Payment service           Provider
1    POST /orders  Idempotency-Key: k1
2                           tx: order pending + key k1 + outbox ChargeRequested; extend hold
3    <- 201 ord-1001
4    (network drops, retries) POST /orders k1 -> 200 same ord-1001 (Idempotent-Replayed)
5                                                       relay -> ChargeRequested
6                                                       POST /charges key ord-1001-charge -> timeout
7                                                       retry same key ---------------> 200 (stored result)
8                           PaymentSucceeded -> tx: seats sold (live hold) + outbox IssueTickets
9    GET /orders/ord-1001 -> paid; tickets arrive by email (at-least-once, deduplicated)

Real scenario: the user double-clicks "Pay"; the mobile app retries after a 30 s timeout; the provider's webhook is delivered twice; the payment worker crashes after the provider charged; the provider is down for 10 minutes in the middle of the on-sale.

ProblemMechanismDetail
Duplicate checkoutIdempotency-Key, scoped by user, with a request fingerprintSame key + same body -> stored order; same key + different body -> 422
Duplicate chargeProvider idempotency key = order_id + "-charge"Stripe: keys up to 255 characters; v1 stores "the status code and body of the first request"
Lost publish after commitTransactional outboxRelay with SKIP LOCKED; consumers deduplicate (Inbox)
Payment declinedCompensation: release seatsRelease is idempotent
Paid after the hold expiredCompensation: refund, or re-hold if still freeConfirm updates 0 rows -> refund_required
Unknown outcomeQuery the provider by key; never guessKeep the hold extended while unknown
Duplicate webhookOrder state machineOnly pending_payment moves; repeats are no-ops

Fix / how to use it: the Go purchase package and the Laravel CheckoutController and PaymentWebhookController implement exactly the table above; the Go test fires 50 concurrent checkouts with one key and asserts one order and one outbox row. Deep material: API Idempotency, Transactional Outbox, Saga Pattern, Payment Processing Architecture.

Hot events, hot rows and partitioning Important ​

In plain words: one event can be a thousand times hotter than all others combined; give it its own lane so it cannot starve the rest, and keep each event's seats together so a hold never crosses machines.

Common misunderstanding: "Partition seats by seat id to spread the load." That spreads one event over every node, so a hold of seats 13 and 14 becomes a cross-shard transaction. Partition by event: all seats of one event live in one partition, every hold is a local transaction, and the hot event becomes a hot partition you can isolate.

text
normal day:  5,000 events, hash(event_id) % 4 partitions, one PostgreSQL cluster
on-sale:     event ev-tour-01 -> 50 holds/s on ~200 front-row rows (hot rows)
isolation:   ev-tour-01 seats on its own partition and, if needed, its own primary;
             its own API pool (bulkhead), its own Redis keys ({ev-tour-01} hash tag),
             its own waiting room; other events keep selling normally
after:       move it back with the rest (logical replication or pg_dump of one partition)
TechniqueWhat it isolatesProduct example
Partition by eventLocks and I/O of one eventPostgreSQL PARTITION BY HASH (event_id) or LIST for a hot event
Dedicated primary for a hot eventCPU, WAL, connectionsA separate PostgreSQL cluster for the stadium tour
Bulkhead: per-event connection pool and API poolThreads, connectionsSeparate Kubernetes Deployment, PgBouncer pool per tier
Redis hash tag per eventCluster slot for multi-key scriptsKeys seat:{ev1}:S112-R07-14
Pre-warm caches and seat rowsCold-start latencypg_prewarm, CDN warm requests, catalogue in Redis
Spread the demandHot rows within the event"Best available" picks from many rows; show alternatives on 409

Hot rows cannot be partitioned away: 1,000 buyers want row 1. The remedies are product and flow, not storage: admission caps how many fight at once, lock_timeout keeps losers fast, best-available spreads choice, and the map's realtime push steers buyers away from taken seats. Bulkheads: Bulkheads & Graceful Degradation; partitioning mechanics: Sharding at System Level and Partitioning & Sharding in PostgreSQL.

Ticket integrity: signed QR codes and offline validation Must-know ​

In plain words: the ticket carries its own proof. A gate scanner can check the stamp without asking the server, because only the box office can make that stamp.

Common misunderstanding: "Store a random ticket number and look it up at the gate." That needs a live connection from every gate to the database at the moment 50,000 people arrive, which stadium networks do not provide. Also, "a JWT signed with HMAC is fine": with HMAC every scanner holds the signing secret, so one stolen device can mint tickets.

Definition: a signed ticket is a payload (ticket id, event, seat, ownership generation, validity window) plus a signature. With an asymmetric scheme (Ed25519, or a JWT with alg: EdDSA or ES256), scanners hold only the public key. HMAC (RFC 2104) is right for tokens the same party issues and verifies (the admission token, signed download URLs) and wrong for codes verified by many untrusted devices. Offline validation checks the signature, the event, the time window, a revocation list downloaded before doors open, and a local "already scanned" set.

text
     Server                               Gate scanner (offline)
1    issue tk-1 gen 1, sign (Ed25519)
2    fan resells tk-1 -> generation 2, new QR; revocation list: tk-1 <= gen 1
3    18:00 scanners download revocation list + public key, go offline
4                                         scan old QR (gen 1)  -> REVOKED
5                                         scan new QR (gen 2)  -> OK, recorded locally
6                                         scan screenshot again -> ALREADY SCANNED
7                                         other gate, same code -> OK locally (!)
8    devices reconnect -> upload scans -> duplicate entry flagged for review

Step 7 is the honest limit of offline validation: two gates without a network cannot know about each other's scans. Mitigations are rotating codes (the app shows a code that changes every 30 s from a per-ticket secret, so a screenshot dies), gate-to-gate sync on the local network, and assigning tickets to gates by section.

FormatSize in a QRWho can verifyWho can forge
Random id + online lookupSmallOnly online devicesNobody (but needs the network)
HMAC-signed payloadSmallAnyone with the secretAnyone with the secret (every scanner)
JWT HS256MediumSame as HMACSame as HMAC
JWT ES256 / EdDSA, or a compact Ed25519 tokenMediumAnyone with the public keyOnly the issuer
Rotating code (TOTP-like)SmallDevice with the per-ticket seedScreenshot useless after 30 s

The Go ticketqr package signs with Ed25519 and implements generation revocation and first-scan-wins; the Laravel TicketSigner produces the same format with sodium_crypto_sign_detached. Token formats: JWT Deep Dive and Password Hashing & Signed Tokens; key management: Cryptography in Practice.

Transfer and resale marketplace Important ​

In plain words: a transfer is a change of owner that kills the old QR code; a resale is a transfer where money sits with the platform until the ticket has changed hands.

Common misunderstanding: "Resale is a second sale of the seat." The seat stays sold; only the ticket's owner and generation change. Treating resale as release-and-resell would put the seat back into the primary on-sale pool and invite exactly the race this design removed.

StepTransactionRule
ListInsert listing listed; ticket cannot be transferred meanwhilePrice cap as a rule: CHECK (price_cents <= face_cents * 110 / 100) or per-organiser policy
BuyBuyer pays into escrow; listing in_escrow (lock the listing row)One buyer per listing: conditional update on status
TransferTicket owner_id = buyer, generation + 1; revocation entry for the old generationSame transaction as listing sold
SettleRelease escrow to the seller after the transfer commits (or after the event)Refund the buyer if the transfer fails
GateOld QR rejected as revoked; new QR acceptedRevocation list refreshed before doors

Escrow means the platform holds the buyer's money until the ticket has been delivered; it is a small saga of its own (charge buyer, transfer ticket, pay seller; compensate by refunding the buyer). Price caps are business rules that vary by country and organiser, so they live in data (a rule per event) with a database CHECK or validation as the enforcement point, not in the UI.

Analytics and real-time dashboards Good to know ​

In plain words: organisers want a live dashboard of "sold per section per minute"; compute it from the event stream, never by running COUNT(*) on the hot seats partition.

Common misunderstanding: "A dashboard query every 5 s is harmless." 50 organiser dashboards x a GROUP BY over 50,000 rows every 5 s competes with the hold transactions for the same partition at the worst moment.

text
inventory/order outbox -> broker topic seat-events (key = event_id)
-> stream processor: tumbling 1-minute windows by (event, section, state)
-> results table / Redis hash -> dashboard (SSE) and fraud signals (holds per account)
NeedToolNote
Live sold/held countsStream processing (Kafka Streams, Apache Flink) or a consumer updating Redis countersWindows and watermarks: Stream Processing
Queue length, admission rateWaiting-room product analyticsCloudflare passthrough mode gathers "total active users, new users per minute and time on origin" without queueing
Funnel (queue -> hold -> pay)Columnar store (ClickHouse, BigQuery)OLTP vs OLAP
Bot signalsStream join of holds, accounts, devicesFeeds the bot-defence layer

Failure scenarios Must-know ​

In plain words: for each component, decide in advance what the system does when it is gone, and make sure every answer keeps the invariant.

Common misunderstanding: "If Redis holds the seats and Redis dies, we lose the sale." Only if Redis is the system of record. In this design PostgreSQL records every hold and sale; Redis is a gate that can be rebuilt from the database (query 8 in the SQL file) in seconds.

text
Redis loss during the on-sale
1  Redis primary fails; failover promotes a replica that lacks the last ~1 s of holds
2  inventory switches to "DB-only" mode (FOR UPDATE path), latency up, correctness same
3  rebuild: SELECT held seats with remaining TTL, SET ... PX ttl_ms; SELECT sold seats
4  switch back to the Redis gate; holds made during the gap already live in PostgreSQL
FailureEffectResponseInvariant kept by
Payment provider outageCheckouts cannot completePause admissions (waiting room holds the crowd), extend live holds once, show "payment delayed"; optional second providerHolds expire normally; no sale without confirm
Payment timeout (unknown)Did it charge?Retry with the same provider key; query by key; keep hold extendedProvider idempotency
Redis lossHold gate goneDB-only mode, rebuild from PostgreSQLPostgreSQL rows and constraints
PostgreSQL primary failureHolds and checkouts failSynchronous standby promoted (Patroni); waiting room pauses admissionsSynchronous replication: no committed sale lost
Region failureOrigin unreachableWarm standby region with a synchronous or near-synchronous replica; DNS failover; the on-sale may be paused and rescheduledOne writer at a time: fence the old primary before promoting
Waiting room failureCrowd hits the originFail closed for on-sale paths (static "please wait" page from the CDN); never fail openOrigin load shedding: 503 with Retry-After
Overload despite admissionLatency risesLower the admission rate (feedback from p99), shed non-critical traffic (search, recommendations)SRE: "serve degraded results when necessary"
Email provider outageTickets not emailedOutbox keeps TicketsIssued; tickets visible in the appAt-least-once delivery
Gate network outageNo online checksOffline validation with revocation listSignatures and first-scan-wins

Failure-mode thinking in general: Cascading Failures, Timeouts, Retries & Jitter, Capacity Planning, Failure Scenarios & Disaster Recovery.

Capacity test plan, observability and cost Important ​

In plain words: rehearse the on-sale with synthetic buyers before the real one, watch the few numbers that predict trouble, and know what the peak costs.

Common misunderstanding: "A load test at 10,000 QPS of random reads proves it." The dangerous load is contention: thousands of virtual buyers fighting over the same 200 seats, plus payment latency injected at the provider stub. A read-only test passes and the real on-sale deadlocks.

TestShapePass criterion
Contention test5,000 virtual buyers, 80% of them aim at the first 5 rowsp99 hold under 300 ms; zero double-sold seats (unique index never fires)
Spike test100,000 joins in 60 s at the waiting roomOrigin QPS stays at the admission rate
Payment chaosProvider stub with 10% timeouts, 2 s p99, duplicate webhooksZero duplicate charges; every order reaches a terminal state
Failover drillKill the PostgreSQL primary and Redis mid-testNo lost sale; recovery under 60 s (Chaos Engineering)
SoakNormal traffic for 24 h with sweeper and relay runningNo growing outbox backlog, no stuck holds
SignalAlert whenWhy
Hold p99 latency (by event)Above 300 ms for 2 minContention or lock waits
Lock waits (pg_stat_activity wait_event_type = 'Lock')Above 50 waiting backendsHot rows; lower admission rate
55P03 / 40P01 rate40P01 above zeroLock ordering bug
Held seats past deadlineAny older than 2 sweeper intervalsSweeper stalled
Outbox backlog (unsent rows, oldest age)Oldest above 60 sRelay or broker down: tickets delayed
Orders in pending_payment older than 15 minAnyPayment saga stuck
refund_required rateAbove 0.5% of ordersHolds too short for payment latency
Unique-violation on ticketsAnyA double-sell attempt reached the last line of defence
Admission rate vs active shoppersActive above capWaiting room misconfigured

Alerting on these is covered in Alerting That Actually Works and instrumentation in Observability. Cost (back-of-the-envelope, inference): the on-sale peak is 20 minutes, so the expensive parts are per-request edge products (waiting room, CDN, bot management) and the over-provisioned origin during the window; the database is one modest cluster. Scale the API to 19 instances for the window and back down; buy the waiting room rather than build it unless on-sales are your core business (the AWS reference solution being discontinued is a reminder that maintenance is the real cost).

How the interview version differs Good to know ​

In plain words: in 45 minutes you show the method and two deep dives; you do not design resale escrow and gate sync.

Common misunderstanding: "Interviewers want Kafka and microservices." They want the invariant named in minute 3, the estimate that shows contention not throughput, and a defended choice between row locks and Redis holds.

MinuteInterviewReal design doc
0-5Features, "no double-selling", 50k seats, 100k buyersSame, plus organiser requirements, legal (price caps), accessibility
5-10Three numbers: admission rate, hold rate, edge pollsFull estimate table, cost
10-25API, seats-as-rows, services box diagram, waiting roomSame plus ADRs per decision
25-40Deep dive 1: hold with FOR UPDATE vs Redis Lua and TTL. Deep dive 2: payment idempotency and compensationAll step-4 blocks on this page
40-45Failure modes (Redis loss, payment outage), metricsCapacity test plan, runbooks, game day

Mechanics ​

Lock and hold knobs ​

KnobProductValue hereEffect
lock_timeoutPostgreSQLSET LOCAL lock_timeout = '200ms' in hold transactionsLock waits fail with 55P03 instead of piling up
statement_timeoutPostgreSQL2 s for the on-sale roleUpper bound on any statement
idle_in_transaction_session_timeoutPostgreSQL5 sA crashed client cannot keep seat locks
NOWAIT / SKIP LOCKEDPostgreSQL SELECT locking clauseSKIP LOCKED for best available, sweeper, relayNo waiting at all
synchronous_commit + synchronous_standby_namesPostgreSQLOn for the inventory clusterRPO 0 for sales
SET key value NX PX msRedisSingle-seat hold"Only set the key if it does not already exist", TTL in ms
EVAL / EVALSHARedisMulti-seat hold scriptAtomic; all keys in one slot (hash tag)
Hold TTLApplication8 min, one extension to 15 minBalance abandonment against payment latency
Sweeper interval and batchApplication1 s and 500 rows during on-saleShort transactions
total active users, new users per minute, session durationCloudflare Waiting Room5,000 active; session 5 minAdmission thresholds
queueing_methodCloudflare Waiting Roomfifo or random (plan-dependent), passthrough to measure, reject to closeOrder of admission
Admission token TTLApplication10 min, key rotated per on-saleToken reuse window
Idempotency-Key retentionStripeKeys removable after 24 hRetries within a day are safe
after_commit / ->afterCommit()Laravel queuesOnJobs dispatched only after the transaction commits
REVERB_SCALING_ENABLEDLaravel Reverbtrue with several Reverb serversRedis pub/sub between Reverb nodes

Error codes and messages ​

Code / messageSourceMeaning hereResponse
SQLSTATE 55P03 lock_not_availablePostgreSQLlock_timeout hit on a hot seat, or NOWAIT409 seat unavailable, suggest alternatives
SQLSTATE 40P01 deadlock_detectedPostgreSQLLocks taken in different ordersBug: fix the ORDER BY seat_id; retry once
SQLSTATE 40001 serialization_failurePostgreSQLOnly if you run holds at Repeatable Read / SerializableRetry
SQLSTATE 23505 unique_violationPostgreSQLDuplicate idempotency key insert, or a second valid ticket for a seatReplay the stored order; for tickets, page someone
UPDATE 0PostgreSQLConditional update lost (taken, expired, version moved)409 or refund_required
CROSSSLOT Keys in request don't hash to the same slotRedis ClusterSeat keys of one hold in different slotsUse a hash tag {event_id}
HTTP 409 ConflictAPISeat takenRefresh availability
HTTP 410 GoneAPIHold expired before checkoutStart again
HTTP 422APIIdempotency key reused with a different body; price above capClient bug or rule violation
HTTP 429 with Retry-AfterAPI, Laravel throttleRate limit after admissionBack off
HTTP 503 with Retry-AfterOriginLoad sheddingWaiting room lowers the admission rate

The arithmetic ​

The estimator prints every step-2 number from its inputs; change an assumption and rerun. Its output is shown in the lab.

go
// Command estimate prints the step-2 numbers of the ticketing design. Every
// input is an assumption from step 1; change one and rerun.
package main

import (
	"fmt"
	"math"
)

func main() {
	const (
		seats             = 50_000  // stadium event
		concurrentBuyers  = 100_000 // in the waiting room at the start
		ticketsPerOrder   = 2.5
		activeShoppers    = 5_000 // cap on people past the waiting room
		sessionMinutes    = 5.0   // seat pick + pay
		reqPerShopperSec  = 2.0   // API calls per active shopper (map, holds, polls)
		holdsPerSession   = 3.0   // attempts incl. "someone else took it"
		pollSeconds       = 20.0  // waiting-room status refresh
		seatMapGzipKB     = 250.0 // static geometry for 50k seats
		seatRowBytes      = 150.0 // incl. tuple header and index share
		ticketRowBytes    = 300.0
		orderRowBytes     = 500.0
		ticketsPerYear    = 20_000_000.0
		perInstanceQPS    = 1_000.0
		targetUtilisation = 0.6
	)
	orders := seats / ticketsPerOrder
	admitsPerMin := activeShoppers / sessionMinutes
	sellOutMin := orders / admitsPerMin
	apiQPS := activeShoppers * reqPerShopperSec
	holdQPS := activeShoppers * holdsPerSession / (sessionMinutes * 60)
	seatWrites := holdQPS * ticketsPerOrder
	payQPS := orders / (sellOutMin * 60)
	pollQPS := concurrentBuyers / pollSeconds
	mapMBps := admitsPerMin / 60 * seatMapGzipKB / 1024
	burstGB := concurrentBuyers * seatMapGzipKB / 1024 / 1024
	bitmapKB := float64(seats) / 8 / 1024
	instances := math.Ceil(apiQPS/(perInstanceQPS*targetUtilisation)) + 2

	fmt.Printf("orders to sell out          %8.0f\n", orders)
	fmt.Printf("admissions per minute       %8.0f\n", admitsPerMin)
	fmt.Printf("minutes to sell out         %8.1f\n", sellOutMin)
	fmt.Printf("waiting-room polls/s (edge) %8.0f\n", pollQPS)
	fmt.Printf("origin API QPS              %8.0f\n", apiQPS)
	fmt.Printf("hold attempts/s             %8.0f\n", holdQPS)
	fmt.Printf("seat row writes/s           %8.0f\n", seatWrites)
	fmt.Printf("payments/s (average)        %8.1f\n", payQPS)
	fmt.Printf("seat map egress MB/s (CDN)  %8.1f\n", mapMBps)
	fmt.Printf("no-queue burst GB (CDN)     %8.1f\n", burstGB)
	fmt.Printf("availability bitmap KB      %8.1f\n", bitmapKB)
	fmt.Printf("seat rows MB per event      %8.1f\n", seats*seatRowBytes/1e6)
	fmt.Printf("ticket+order GB per year    %8.1f\n", (ticketsPerYear*ticketRowBytes+ticketsPerYear/ticketsPerOrder*orderRowBytes)/1e9)
	fmt.Printf("API instances (N+2)         %8.0f\n", instances)
}

Go ​

The Go module academy/case-study-ticketing has one package per deep dive. It uses github.com/jackc/pgx/v5 for PostgreSQL and github.com/redis/go-redis/v9 for Redis; tests run against an in-memory fake and miniredis, so no server is needed.

Example ​

The inventory core: the Store interface, an in-memory implementation with one mutex per event (the stand-in for row locks), lazy expiry, idempotent release.

go
// Package inventory is the seat-allocation core of the ticketing design:
// every seat has exactly one writer at a time, holds carry a deadline,
// release is idempotent and a sweeper returns expired holds to sale.
package inventory

import (
	"context"
	"errors"
	"sort"
	"sync"
	"time"
)

// State is the lifecycle of one seat for one event.
type State int

const (
	Available State = iota
	Held
	Sold
)

func (s State) String() string {
	return [...]string{"available", "held", "sold"}[s]
}

// Seat is one row of the seats table: (event_id, seat_id) is the key.
type Seat struct {
	ID          string
	State       State
	HoldID      string
	HoldExpires time.Time
	OrderID     string
	Version     int64 // optimistic-locking column, bumped on every change
}

var (
	ErrSeatUnavailable = errors.New("inventory: seat unavailable")
	ErrUnknownSeat     = errors.New("inventory: unknown seat")
	ErrHoldNotFound    = errors.New("inventory: hold not found or expired")
)

// Store is what the hold, order and sweeper services need. MemStore and
// PGStore implement it; the tests run against MemStore.
type Store interface {
	Hold(ctx context.Context, eventID, holdID string, seatIDs []string, ttl time.Duration) (time.Time, error)
	Extend(ctx context.Context, eventID, holdID string, ttl time.Duration) (time.Time, error)
	Confirm(ctx context.Context, eventID, holdID, orderID string) error
	Release(ctx context.Context, eventID, holdID string) (int, error)
	ReleaseExpired(ctx context.Context, eventID string, limit int) (int, error)
}

// MemStore is an in-memory fake with the same semantics as the SQL version:
// one mutex per event plays the role of the row locks of one partition.
type MemStore struct {
	Now    func() time.Time
	mu     sync.Mutex
	events map[string]*eventShard
}

type eventShard struct {
	mu    sync.Mutex
	seats map[string]*Seat
}

// NewMemStore creates an event with the given seat ids, all available.
func NewMemStore(now func() time.Time) *MemStore {
	if now == nil {
		now = time.Now
	}
	return &MemStore{Now: now, events: map[string]*eventShard{}}
}

// AddEvent loads the seat map of one event (the on-sale "pre-warm").
func (m *MemStore) AddEvent(eventID string, seatIDs []string) {
	sh := &eventShard{seats: make(map[string]*Seat, len(seatIDs))}
	for _, id := range seatIDs {
		sh.seats[id] = &Seat{ID: id}
	}
	m.mu.Lock()
	m.events[eventID] = sh
	m.mu.Unlock()
}

func (m *MemStore) shard(eventID string) (*eventShard, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	sh, ok := m.events[eventID]
	if !ok {
		return nil, ErrUnknownSeat
	}
	return sh, nil
}

// free reports whether a seat may be taken now: available, or held by a hold
// whose deadline has passed (lazy expiry: correctness never waits for the sweeper).
func free(s *Seat, now time.Time) bool {
	return s.State == Available || (s.State == Held && !now.Before(s.HoldExpires))
}

// Hold takes all seats or none.
func (m *MemStore) Hold(ctx context.Context, eventID, holdID string, seatIDs []string, ttl time.Duration) (time.Time, error) {
	if err := ctx.Err(); err != nil {
		return time.Time{}, err
	}
	sh, err := m.shard(eventID)
	if err != nil {
		return time.Time{}, err
	}
	ids := append([]string(nil), seatIDs...)
	sort.Strings(ids) // same order the SQL version locks rows in
	sh.mu.Lock()
	defer sh.mu.Unlock()
	now := m.Now()
	for _, id := range ids {
		s, ok := sh.seats[id]
		if !ok {
			return time.Time{}, ErrUnknownSeat
		}
		if !free(s, now) {
			return time.Time{}, ErrSeatUnavailable
		}
	}
	exp := now.Add(ttl)
	for _, id := range ids {
		s := sh.seats[id]
		s.State, s.HoldID, s.HoldExpires = Held, holdID, exp
		s.Version++
	}
	return exp, nil
}

// Extend pushes the deadline of a live hold (used when payment starts).
func (m *MemStore) Extend(_ context.Context, eventID, holdID string, ttl time.Duration) (time.Time, error) {
	sh, err := m.shard(eventID)
	if err != nil {
		return time.Time{}, err
	}
	sh.mu.Lock()
	defer sh.mu.Unlock()
	now := m.Now()
	exp := now.Add(ttl)
	n := 0
	for _, s := range sh.seats {
		if s.State == Held && s.HoldID == holdID && now.Before(s.HoldExpires) {
			s.HoldExpires = exp
			s.Version++
			n++
		}
	}
	if n == 0 {
		return time.Time{}, ErrHoldNotFound
	}
	return exp, nil
}

// Confirm turns a live hold into a sale. An expired hold cannot be confirmed:
// the caller must refund or re-hold (the saga's compensation branch).
func (m *MemStore) Confirm(_ context.Context, eventID, holdID, orderID string) error {
	sh, err := m.shard(eventID)
	if err != nil {
		return err
	}
	sh.mu.Lock()
	defer sh.mu.Unlock()
	now := m.Now()
	var mine []*Seat
	for _, s := range sh.seats {
		if s.State == Sold && s.OrderID == orderID {
			return nil // idempotent: already confirmed for this order
		}
		if s.State == Held && s.HoldID == holdID {
			if !now.Before(s.HoldExpires) {
				return ErrHoldNotFound
			}
			mine = append(mine, s)
		}
	}
	if len(mine) == 0 {
		return ErrHoldNotFound
	}
	for _, s := range mine {
		s.State, s.OrderID, s.HoldID = Sold, orderID, ""
		s.Version++
	}
	return nil
}

// Release is idempotent: a second call, or a call after expiry and re-sale,
// touches nothing because it only matches seats still held by this hold.
func (m *MemStore) Release(_ context.Context, eventID, holdID string) (int, error) {
	sh, err := m.shard(eventID)
	if err != nil {
		return 0, err
	}
	sh.mu.Lock()
	defer sh.mu.Unlock()
	n := 0
	for _, s := range sh.seats {
		if s.State == Held && s.HoldID == holdID {
			s.State, s.HoldID, s.HoldExpires = Available, "", time.Time{}
			s.Version++
			n++
		}
	}
	return n, nil
}

// ReleaseExpired is the sweeper's statement: free at most limit expired holds.
func (m *MemStore) ReleaseExpired(_ context.Context, eventID string, limit int) (int, error) {
	sh, err := m.shard(eventID)
	if err != nil {
		return 0, err
	}
	sh.mu.Lock()
	defer sh.mu.Unlock()
	now := m.Now()
	n := 0
	for _, s := range sh.seats {
		if n == limit {
			break
		}
		if s.State == Held && !now.Before(s.HoldExpires) {
			s.State, s.HoldID, s.HoldExpires = Available, "", time.Time{}
			s.Version++
			n++
		}
	}
	return n, nil
}

// Snapshot returns a copy of one seat (tests and the availability feed).
func (m *MemStore) Snapshot(eventID, seatID string) (Seat, bool) {
	sh, err := m.shard(eventID)
	if err != nil {
		return Seat{}, false
	}
	sh.mu.Lock()
	defer sh.mu.Unlock()
	s, ok := sh.seats[seatID]
	if !ok {
		return Seat{}, false
	}
	return *s, true
}

The PostgreSQL implementation with pgx: FOR UPDATE in seat order with lock_timeout, SKIP LOCKED for best available and the sweeper, a version-column alternative, and SQLSTATE mapping.

go
package inventory

import (
	"context"
	"errors"
	"fmt"
	"sort"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

// PGStore is the PostgreSQL implementation. The seats table is partitioned by
// event_id (see sql/schema.sql); every statement filters on event_id so it
// touches one partition only.
type PGStore struct {
	Pool *pgxpool.Pool
}

var _ Store = (*PGStore)(nil)

func (p *PGStore) inTx(ctx context.Context, fn func(pgx.Tx) error) error {
	// READ COMMITTED is enough: every decision is taken on rows we hold locks on.
	return pgx.BeginTxFunc(ctx, p.Pool, pgx.TxOptions{IsoLevel: pgx.ReadCommitted}, fn)
}

// Hold locks the chosen seats in seat_id order (no deadlocks between two
// buyers whose selections overlap), checks them, then marks them held.
func (p *PGStore) Hold(ctx context.Context, eventID, holdID string, seatIDs []string, ttl time.Duration) (time.Time, error) {
	ids := append([]string(nil), seatIDs...)
	sort.Strings(ids)
	var exp time.Time
	err := p.inTx(ctx, func(tx pgx.Tx) error {
		// lock_timeout turns a long wait on a hot row into SQLSTATE 55P03.
		if _, err := tx.Exec(ctx, `SET LOCAL lock_timeout = '200ms'`); err != nil {
			return err
		}
		rows, err := tx.Query(ctx, `
			SELECT seat_id
			FROM seats
			WHERE event_id = $1 AND seat_id = ANY($2)
			  AND (state = 'available' OR (state = 'held' AND hold_expires_at <= now()))
			ORDER BY seat_id
			FOR UPDATE`, eventID, ids)
		if err != nil {
			return err
		}
		got, err := pgx.CollectRows(rows, pgx.RowTo[string])
		if err != nil {
			return err
		}
		if len(got) != len(ids) {
			return ErrSeatUnavailable
		}
		return tx.QueryRow(ctx, `
			UPDATE seats
			SET state = 'held', hold_id = $3,
			    hold_expires_at = now() + make_interval(secs => $4),
			    version = version + 1
			WHERE event_id = $1 AND seat_id = ANY($2)
			RETURNING hold_expires_at`, eventID, ids, holdID, ttl.Seconds()).Scan(&exp)
	})
	return exp, mapPG(err)
}

// HoldBestAvailable picks n seats in a section without making buyers queue
// behind each other's row locks: SKIP LOCKED ignores rows another hold is
// taking right now.
func (p *PGStore) HoldBestAvailable(ctx context.Context, eventID, section, holdID string, n int, ttl time.Duration) ([]string, error) {
	var seats []string
	err := p.inTx(ctx, func(tx pgx.Tx) error {
		rows, err := tx.Query(ctx, `
			WITH picked AS (
			  SELECT seat_id
			  FROM seats
			  WHERE event_id = $1 AND section = $2 AND state = 'available'
			  ORDER BY row_no, seat_no
			  LIMIT $3
			  FOR UPDATE SKIP LOCKED
			)
			UPDATE seats s
			SET state = 'held', hold_id = $4,
			    hold_expires_at = now() + make_interval(secs => $5),
			    version = s.version + 1
			FROM picked
			WHERE s.event_id = $1 AND s.seat_id = picked.seat_id
			RETURNING s.seat_id`, eventID, section, n, holdID, ttl.Seconds())
		if err != nil {
			return err
		}
		seats, err = pgx.CollectRows(rows, pgx.RowTo[string])
		if err != nil {
			return err
		}
		if len(seats) < n {
			return ErrSeatUnavailable // roll back a partial pick
		}
		return nil
	})
	return seats, mapPG(err)
}

// HoldOptimistic is the version-column alternative for a single seat: no lock
// is held between read and write; a lost race shows up as zero rows.
func (p *PGStore) HoldOptimistic(ctx context.Context, eventID, seatID, holdID string, readVersion int64, ttl time.Duration) error {
	tag, err := p.Pool.Exec(ctx, `
		UPDATE seats
		SET state = 'held', hold_id = $3,
		    hold_expires_at = now() + make_interval(secs => $5),
		    version = version + 1
		WHERE event_id = $1 AND seat_id = $2 AND version = $4
		  AND (state = 'available' OR (state = 'held' AND hold_expires_at <= now()))`,
		eventID, seatID, holdID, readVersion, ttl.Seconds())
	if err != nil {
		return mapPG(err)
	}
	if tag.RowsAffected() == 0 {
		return ErrSeatUnavailable
	}
	return nil
}

func (p *PGStore) Extend(ctx context.Context, eventID, holdID string, ttl time.Duration) (time.Time, error) {
	var exp time.Time
	err := p.Pool.QueryRow(ctx, `
		UPDATE seats
		SET hold_expires_at = now() + make_interval(secs => $3), version = version + 1
		WHERE event_id = $1 AND hold_id = $2 AND state = 'held' AND hold_expires_at > now()
		RETURNING hold_expires_at`, eventID, holdID, ttl.Seconds()).Scan(&exp)
	if errors.Is(err, pgx.ErrNoRows) {
		return time.Time{}, ErrHoldNotFound
	}
	return exp, mapPG(err)
}

func (p *PGStore) Confirm(ctx context.Context, eventID, holdID, orderID string) error {
	return mapPG(p.inTx(ctx, func(tx pgx.Tx) error {
		var already int
		if err := tx.QueryRow(ctx, `SELECT count(*) FROM seats WHERE event_id = $1 AND order_id = $2`,
			eventID, orderID).Scan(&already); err != nil {
			return err
		}
		if already > 0 {
			return nil // idempotent replay of the payment callback
		}
		tag, err := tx.Exec(ctx, `
			UPDATE seats
			SET state = 'sold', order_id = $3, hold_id = NULL, hold_expires_at = NULL,
			    version = version + 1
			WHERE event_id = $1 AND hold_id = $2 AND state = 'held' AND hold_expires_at > now()`,
			eventID, holdID, orderID)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			return ErrHoldNotFound
		}
		return nil
	}))
}

func (p *PGStore) Release(ctx context.Context, eventID, holdID string) (int, error) {
	tag, err := p.Pool.Exec(ctx, `
		UPDATE seats
		SET state = 'available', hold_id = NULL, hold_expires_at = NULL, version = version + 1
		WHERE event_id = $1 AND hold_id = $2 AND state = 'held'`, eventID, holdID)
	if err != nil {
		return 0, mapPG(err)
	}
	return int(tag.RowsAffected()), nil
}

func (p *PGStore) ReleaseExpired(ctx context.Context, eventID string, limit int) (int, error) {
	tag, err := p.Pool.Exec(ctx, `
		WITH expired AS (
		  SELECT seat_id FROM seats
		  WHERE event_id = $1 AND state = 'held' AND hold_expires_at <= now()
		  LIMIT $2
		  FOR UPDATE SKIP LOCKED
		)
		UPDATE seats s
		SET state = 'available', hold_id = NULL, hold_expires_at = NULL, version = s.version + 1
		FROM expired
		WHERE s.event_id = $1 AND s.seat_id = expired.seat_id`, eventID, limit)
	if err != nil {
		return 0, mapPG(err)
	}
	return int(tag.RowsAffected()), nil
}

// mapPG turns lock errors into the domain error the API maps to 409.
func mapPG(err error) error {
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) {
		switch pgErr.Code {
		case "55P03", "40P01", "40001": // lock_not_available, deadlock_detected, serialization_failure
			return fmt.Errorf("%w: %s", ErrSeatUnavailable, pgErr.Code)
		}
	}
	return err
}

The hold-expiry sweeper:

go
package inventory

import (
	"context"
	"time"
)

// Sweeper returns expired holds to sale in small batches. Correctness does not
// depend on it (Hold treats an expired hold as free); it exists so that the
// availability feed and the "best available" query see the seats again.
type Sweeper struct {
	Store    Store
	Events   func() []string // events currently on sale
	Interval time.Duration   // e.g. 1s during an on-sale, 30s otherwise
	Batch    int             // rows per statement, keeps transactions short
	OnFreed  func(eventID string, n int)
}

// RunOnce sweeps every event until a batch comes back short.
func (s Sweeper) RunOnce(ctx context.Context) (int, error) {
	total := 0
	for _, ev := range s.Events() {
		for {
			n, err := s.Store.ReleaseExpired(ctx, ev, s.Batch)
			if err != nil {
				return total, err
			}
			total += n
			if n > 0 && s.OnFreed != nil {
				s.OnFreed(ev, n)
			}
			if n < s.Batch {
				break
			}
		}
	}
	return total, nil
}

// Run sweeps on a ticker until ctx is cancelled. Run one sweeper per event
// partition (or take a lease) so two sweepers do not fight over the same rows.
func (s Sweeper) Run(ctx context.Context) error {
	t := time.NewTicker(s.Interval)
	defer t.Stop()
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-t.C:
			if _, err := s.RunOnce(ctx); err != nil && ctx.Err() == nil {
				continue // log and retry on the next tick
			}
		}
	}
}

Double-sell tests under concurrency (go test -race): 1,000 goroutines on one seat produce exactly one winner; 500 goroutines on overlapping pairs never share a seat; a fake clock proves expiry, late release and confirm-after-expiry behaviour.

go
package inventory

import (
	"context"
	"errors"
	"fmt"
	"math/rand/v2"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

type fakeClock struct {
	mu sync.Mutex
	t  time.Time
}

func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t }
func (c *fakeClock) Add(d time.Duration) {
	c.mu.Lock()
	c.t = c.t.Add(d)
	c.mu.Unlock()
}

func seats(n int) []string {
	out := make([]string, n)
	for i := range out {
		out[i] = fmt.Sprintf("A-%03d", i)
	}
	return out
}

// 1,000 buyers press "hold" on the same seat at the same moment: one wins.
func TestOneSeatOneWinner(t *testing.T) {
	st := NewMemStore(nil)
	st.AddEvent("ev1", seats(1))
	var wins, losses atomic.Int64
	var wg sync.WaitGroup
	for i := range 1000 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			_, err := st.Hold(context.Background(), "ev1", fmt.Sprintf("h%d", i), []string{"A-000"}, time.Minute)
			switch {
			case err == nil:
				wins.Add(1)
			case errors.Is(err, ErrSeatUnavailable):
				losses.Add(1)
			default:
				t.Error(err)
			}
		}()
	}
	wg.Wait()
	if wins.Load() != 1 || losses.Load() != 999 {
		t.Fatalf("wins=%d losses=%d, want 1 and 999", wins.Load(), losses.Load())
	}
}

// Buyers grab overlapping pairs of 50 seats; no seat may end up in two holds.
func TestOverlappingHoldsNeverDoubleSell(t *testing.T) {
	st := NewMemStore(nil)
	ids := seats(50)
	st.AddEvent("ev1", ids)
	var mu sync.Mutex
	owner := map[string]string{}
	var wg sync.WaitGroup
	for i := range 500 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			r := rand.New(rand.NewPCG(uint64(i), 7))
			a, b := ids[r.IntN(50)], ids[r.IntN(50)]
			if a == b {
				return
			}
			h := fmt.Sprintf("h%d", i)
			if _, err := st.Hold(context.Background(), "ev1", h, []string{a, b}, time.Minute); err != nil {
				return
			}
			mu.Lock()
			defer mu.Unlock()
			for _, s := range []string{a, b} {
				if prev, ok := owner[s]; ok {
					t.Errorf("seat %s held by %s and %s", s, prev, h)
				}
				owner[s] = h
			}
		}()
	}
	wg.Wait()
	for s, h := range owner {
		snap, _ := st.Snapshot("ev1", s)
		if snap.HoldID != h {
			t.Errorf("seat %s: store says %q, winner was %q", s, snap.HoldID, h)
		}
	}
}

func TestExpiryReleaseAndConfirm(t *testing.T) {
	clk := &fakeClock{t: time.Date(2026, 11, 26, 19, 0, 0, 0, time.UTC)}
	st := NewMemStore(clk.Now)
	st.AddEvent("ev1", seats(2))
	ctx := context.Background()
	if _, err := st.Hold(ctx, "ev1", "h1", []string{"A-000", "A-001"}, 8*time.Minute); err != nil {
		t.Fatal(err)
	}
	clk.Add(9 * time.Minute) // buyer walked away; the sweeper has not run yet
	if err := st.Confirm(ctx, "ev1", "h1", "o1"); !errors.Is(err, ErrHoldNotFound) {
		t.Fatalf("confirm after expiry: %v", err)
	}
	if _, err := st.Hold(ctx, "ev1", "h2", []string{"A-000"}, 8*time.Minute); err != nil {
		t.Fatalf("expired seat must be holdable before the sweep: %v", err)
	}
	// late release of h1 must not free h2's seat
	if n, _ := st.Release(ctx, "ev1", "h1"); n != 1 {
		t.Fatalf("release h1 freed %d seats, want 1 (A-001 only)", n)
	}
	if n, _ := st.Release(ctx, "ev1", "h1"); n != 0 {
		t.Fatalf("second release freed %d, want 0", n)
	}
	if err := st.Confirm(ctx, "ev1", "h2", "o2"); err != nil {
		t.Fatal(err)
	}
	if err := st.Confirm(ctx, "ev1", "h2", "o2"); err != nil {
		t.Fatalf("confirm replay: %v", err)
	}
	if s, _ := st.Snapshot("ev1", "A-000"); s.State != Sold || s.OrderID != "o2" {
		t.Fatalf("A-000 = %+v", s)
	}
}

func TestExtendAndSweeper(t *testing.T) {
	clk := &fakeClock{t: time.Date(2026, 11, 26, 19, 0, 0, 0, time.UTC)}
	st := NewMemStore(clk.Now)
	st.AddEvent("ev1", seats(10))
	ctx := context.Background()
	for i := range 10 {
		if _, err := st.Hold(ctx, "ev1", fmt.Sprintf("h%d", i), []string{fmt.Sprintf("A-%03d", i)}, 5*time.Minute); err != nil {
			t.Fatal(err)
		}
	}
	clk.Add(4 * time.Minute)
	if _, err := st.Extend(ctx, "ev1", "h0", 10*time.Minute); err != nil { // h0 started paying
		t.Fatal(err)
	}
	clk.Add(2 * time.Minute)
	freed := 0
	sw := Sweeper{Store: st, Events: func() []string { return []string{"ev1"} }, Batch: 4,
		OnFreed: func(_ string, n int) { freed += n }}
	n, err := sw.RunOnce(ctx)
	if err != nil || n != 9 || freed != 9 {
		t.Fatalf("swept %d (callback %d) err=%v, want 9", n, freed, err)
	}
	if s, _ := st.Snapshot("ev1", "A-000"); s.State != Held {
		t.Fatalf("extended hold was swept: %+v", s)
	}
}

The Redis Lua alternative: one script for all seats of a hold, a hash tag per event for Redis Cluster, owner-checked release and extend, and a permanent sold marker.

go
// Package redishold is the Redis alternative to the row-lock hold: one Lua
// script checks and sets every seat key atomically, with a TTL as the hold
// deadline. PostgreSQL stays the system of record; Redis is the fast gate.
package redishold

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/redis/go-redis/v9"
)

var (
	ErrSeatTaken = errors.New("redishold: seat taken")
	ErrNotOwner  = errors.New("redishold: hold not owned or expired")
)

// holdScript: KEYS = seat keys (same hash tag so they share a cluster slot),
// ARGV[1] = hold id, ARGV[2] = ttl in ms. All or nothing.
var holdScript = redis.NewScript(`
for i = 1, #KEYS do
  if redis.call('EXISTS', KEYS[i]) == 1 then
    return {0, KEYS[i]}
  end
end
for i = 1, #KEYS do
  redis.call('SET', KEYS[i], ARGV[1], 'PX', ARGV[2])
end
return {1, ''}
`)

// releaseScript deletes only keys still owned by this hold: idempotent, and a
// late release can never free a seat somebody else holds now.
var releaseScript = redis.NewScript(`
local n = 0
for i = 1, #KEYS do
  if redis.call('GET', KEYS[i]) == ARGV[1] then
    redis.call('DEL', KEYS[i])
    n = n + 1
  end
end
return n
`)

// extendScript pushes the TTL of every key, only if all are still owned.
var extendScript = redis.NewScript(`
for i = 1, #KEYS do
  if redis.call('GET', KEYS[i]) ~= ARGV[1] then return 0 end
end
for i = 1, #KEYS do redis.call('PEXPIRE', KEYS[i], ARGV[2]) end
return 1
`)

// soldScript replaces the hold with a permanent "sold:<order>" marker.
var soldScript = redis.NewScript(`
for i = 1, #KEYS do
  local v = redis.call('GET', KEYS[i])
  if v ~= ARGV[1] and v ~= ARGV[2] then return 0 end
end
for i = 1, #KEYS do redis.call('SET', KEYS[i], ARGV[2]) end
return 1
`)

type Holds struct {
	RDB redis.Scripter
}

// Key puts the event id in a hash tag: Redis Cluster refuses a script whose
// keys live in different slots (CROSSSLOT), so one event = one slot.
func Key(eventID, seatID string) string {
	return fmt.Sprintf("seat:{%s}:%s", eventID, seatID)
}

func keys(eventID string, seatIDs []string) []string {
	ks := make([]string, len(seatIDs))
	for i, s := range seatIDs {
		ks[i] = Key(eventID, s)
	}
	return ks
}

func (h Holds) Hold(ctx context.Context, eventID, holdID string, seatIDs []string, ttl time.Duration) error {
	res, err := holdScript.Run(ctx, h.RDB, keys(eventID, seatIDs), holdID, ttl.Milliseconds()).Slice()
	if err != nil {
		return err
	}
	if ok, _ := res[0].(int64); ok != 1 {
		return fmt.Errorf("%w: %v", ErrSeatTaken, res[1])
	}
	return nil
}

func (h Holds) Release(ctx context.Context, eventID, holdID string, seatIDs []string) (int64, error) {
	return releaseScript.Run(ctx, h.RDB, keys(eventID, seatIDs), holdID).Int64()
}

func (h Holds) Extend(ctx context.Context, eventID, holdID string, seatIDs []string, ttl time.Duration) error {
	ok, err := extendScript.Run(ctx, h.RDB, keys(eventID, seatIDs), holdID, ttl.Milliseconds()).Int64()
	if err != nil {
		return err
	}
	if ok != 1 {
		return ErrNotOwner
	}
	return nil
}

func (h Holds) MarkSold(ctx context.Context, eventID, holdID, orderID string, seatIDs []string) error {
	ok, err := soldScript.Run(ctx, h.RDB, keys(eventID, seatIDs), holdID, "sold:"+orderID).Int64()
	if err != nil {
		return err
	}
	if ok != 1 {
		return ErrNotOwner
	}
	return nil
}
go
package redishold

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"
)

func setup(t *testing.T) (*miniredis.Miniredis, Holds) {
	t.Helper()
	mr := miniredis.RunT(t)
	rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
	t.Cleanup(func() { _ = rdb.Close() })
	return mr, Holds{RDB: rdb}
}

func TestConcurrentHoldOneWinner(t *testing.T) {
	_, h := setup(t)
	var wins atomic.Int64
	var wg sync.WaitGroup
	for i := range 200 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			err := h.Hold(context.Background(), "ev1", fmt.Sprintf("h%d", i), []string{"A-1", "A-2"}, time.Minute)
			if err == nil {
				wins.Add(1)
			} else if !errors.Is(err, ErrSeatTaken) {
				t.Error(err)
			}
		}()
	}
	wg.Wait()
	if wins.Load() != 1 {
		t.Fatalf("wins = %d, want 1", wins.Load())
	}
}

func TestTTLReleaseExtendSold(t *testing.T) {
	mr, h := setup(t)
	ctx := context.Background()
	if err := h.Hold(ctx, "ev1", "h1", []string{"A-1"}, 8*time.Minute); err != nil {
		t.Fatal(err)
	}
	mr.FastForward(9 * time.Minute) // TTL elapsed: Redis expires the key
	if err := h.Hold(ctx, "ev1", "h2", []string{"A-1"}, 8*time.Minute); err != nil {
		t.Fatalf("expired seat should be free: %v", err)
	}
	if n, _ := h.Release(ctx, "ev1", "h1", []string{"A-1"}); n != 0 {
		t.Fatalf("stale release freed %d keys", n)
	}
	if err := h.Extend(ctx, "ev1", "h2", []string{"A-1"}, 15*time.Minute); err != nil {
		t.Fatal(err)
	}
	if err := h.MarkSold(ctx, "ev1", "h2", "o9", []string{"A-1"}); err != nil {
		t.Fatal(err)
	}
	if err := h.MarkSold(ctx, "ev1", "h2", "o9", []string{"A-1"}); err != nil {
		t.Fatalf("replay: %v", err)
	}
	if ttl := mr.TTL(Key("ev1", "A-1")); ttl != 0 {
		t.Fatalf("sold marker must not expire, ttl=%v", ttl)
	}
}

Idempotent purchase with an outbox and saga transitions:

go
// Package purchase is the order side of the design: an idempotent checkout
// that writes the order and an outbox row together, and a payment-result
// handler that confirms seats or runs the compensation (release or refund).
package purchase

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"sync"

	"academy/case-study-ticketing/inventory"
)

type Status string

const (
	PendingPayment Status = "pending_payment"
	Paid           Status = "paid"
	PaymentFailed  Status = "payment_failed"
	RefundRequired Status = "refund_required"
)

type Order struct {
	ID, UserID, EventID, HoldID string
	AmountCents                 int64
	Status                      Status
}

// OutboxMsg is a row of the outbox table; a relay publishes and marks it.
type OutboxMsg struct {
	ID      int64
	Topic   string // ChargeRequested, IssueTickets, SeatsReleased, RefundPayment
	OrderID string
	Sent    bool
}

type CheckoutRequest struct {
	IdempotencyKey string
	UserID         string
	EventID        string
	HoldID         string
	AmountCents    int64
}

func (r CheckoutRequest) fingerprint() string {
	h := sha256.Sum256(fmt.Appendf(nil, "%s|%s|%s|%d", r.UserID, r.EventID, r.HoldID, r.AmountCents))
	return hex.EncodeToString(h[:])
}

var (
	ErrKeyReused    = errors.New("purchase: idempotency key reused with a different request")
	ErrMissingKey   = errors.New("purchase: Idempotency-Key header required")
	ErrUnknownOrder = errors.New("purchase: unknown order")
)

type idemRecord struct {
	fingerprint string
	orderID     string
}

// Service keeps orders, idempotency keys and the outbox behind one mutex: the
// in-memory stand-in for one PostgreSQL transaction (see sql/queries.sql).
type Service struct {
	Inv inventory.Store

	mu     sync.Mutex
	keys   map[string]idemRecord // key scoped by user: user|key
	orders map[string]*Order
	outbox []OutboxMsg
	seq    int64
}

func New(inv inventory.Store) *Service {
	return &Service{Inv: inv, keys: map[string]idemRecord{}, orders: map[string]*Order{}}
}

func (s *Service) emit(topic, orderID string) {
	s.seq++
	s.outbox = append(s.outbox, OutboxMsg{ID: s.seq, Topic: topic, OrderID: orderID})
}

// Checkout returns the same order for every retry with the same key.
func (s *Service) Checkout(_ context.Context, r CheckoutRequest) (Order, bool, error) {
	if r.IdempotencyKey == "" {
		return Order{}, false, ErrMissingKey
	}
	scoped := r.UserID + "|" + r.IdempotencyKey
	fp := r.fingerprint()
	s.mu.Lock()
	defer s.mu.Unlock()
	if rec, ok := s.keys[scoped]; ok {
		if rec.fingerprint != fp {
			return Order{}, false, ErrKeyReused
		}
		return *s.orders[rec.orderID], true, nil
	}
	s.seq++
	o := &Order{ID: fmt.Sprintf("ord-%d", s.seq), UserID: r.UserID, EventID: r.EventID,
		HoldID: r.HoldID, AmountCents: r.AmountCents, Status: PendingPayment}
	s.orders[o.ID] = o
	s.keys[scoped] = idemRecord{fingerprint: fp, orderID: o.ID}
	s.emit("ChargeRequested", o.ID) // same transaction as the order row
	return *o, false, nil
}

// OnPaymentResult is called by the payment webhook/consumer, possibly twice.
func (s *Service) OnPaymentResult(ctx context.Context, orderID string, succeeded bool) (Order, error) {
	s.mu.Lock()
	o, ok := s.orders[orderID]
	if !ok {
		s.mu.Unlock()
		return Order{}, ErrUnknownOrder
	}
	if o.Status != PendingPayment { // duplicate delivery: state machine already moved
		cp := *o
		s.mu.Unlock()
		return cp, nil
	}
	cp := *o
	s.mu.Unlock()

	// In one database these run in the same transaction as the status change.
	next, topic := Paid, "IssueTickets"
	if succeeded {
		if err := s.Inv.Confirm(ctx, cp.EventID, cp.HoldID, cp.ID); err != nil {
			if !errors.Is(err, inventory.ErrHoldNotFound) {
				return Order{}, err
			}
			next, topic = RefundRequired, "RefundPayment" // paid too late: compensate
		}
	} else {
		if _, err := s.Inv.Release(ctx, cp.EventID, cp.HoldID); err != nil {
			return Order{}, err
		}
		next, topic = PaymentFailed, "SeatsReleased"
	}

	s.mu.Lock()
	defer s.mu.Unlock()
	if o.Status == PendingPayment {
		o.Status = next
		s.emit(topic, o.ID)
	}
	return *o, nil
}

// Pending is what the relay polls (SELECT ... FOR UPDATE SKIP LOCKED in SQL).
func (s *Service) Pending(limit int) []OutboxMsg {
	s.mu.Lock()
	defer s.mu.Unlock()
	var out []OutboxMsg
	for _, m := range s.outbox {
		if !m.Sent && len(out) < limit {
			out = append(out, m)
		}
	}
	return out
}

func (s *Service) MarkSent(id int64) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for i := range s.outbox {
		if s.outbox[i].ID == id {
			s.outbox[i].Sent = true
		}
	}
}
go
package purchase

import (
	"context"
	"errors"
	"sync"
	"testing"
	"time"

	"academy/case-study-ticketing/inventory"
)

type clock struct{ t time.Time }

func (c *clock) now() time.Time { return c.t }

func setup(t *testing.T) (*Service, *inventory.MemStore, *clock) {
	t.Helper()
	c := &clock{t: time.Date(2026, 11, 26, 19, 0, 0, 0, time.UTC)}
	inv := inventory.NewMemStore(c.now)
	inv.AddEvent("ev1", []string{"A-1", "A-2"})
	if _, err := inv.Hold(context.Background(), "ev1", "h1", []string{"A-1", "A-2"}, 8*time.Minute); err != nil {
		t.Fatal(err)
	}
	return New(inv), inv, c
}

func req() CheckoutRequest {
	return CheckoutRequest{IdempotencyKey: "k-1", UserID: "u1", EventID: "ev1", HoldID: "h1", AmountCents: 15000}
}

// A double-clicked "Pay" button plus client retries: 50 concurrent requests.
func TestConcurrentRetriesCreateOneOrder(t *testing.T) {
	s, _, _ := setup(t)
	ids := make(chan string, 50)
	var wg sync.WaitGroup
	for range 50 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			o, _, err := s.Checkout(context.Background(), req())
			if err != nil {
				t.Error(err)
				return
			}
			ids <- o.ID
		}()
	}
	wg.Wait()
	close(ids)
	first := ""
	for id := range ids {
		if first == "" {
			first = id
		} else if id != first {
			t.Fatalf("two orders: %s and %s", first, id)
		}
	}
	if p := s.Pending(10); len(p) != 1 || p[0].Topic != "ChargeRequested" {
		t.Fatalf("outbox = %+v, want one ChargeRequested", p)
	}
}

func TestKeyReuseRejected(t *testing.T) {
	s, _, _ := setup(t)
	if _, _, err := s.Checkout(context.Background(), req()); err != nil {
		t.Fatal(err)
	}
	r := req()
	r.AmountCents = 1
	if _, _, err := s.Checkout(context.Background(), r); !errors.Is(err, ErrKeyReused) {
		t.Fatalf("err = %v, want ErrKeyReused", err)
	}
}

func TestPaymentOutcomes(t *testing.T) {
	ctx := context.Background()

	s, inv, _ := setup(t)
	o, _, _ := s.Checkout(ctx, req())
	got, err := s.OnPaymentResult(ctx, o.ID, true)
	if err != nil || got.Status != Paid {
		t.Fatalf("success: %+v %v", got, err)
	}
	if again, _ := s.OnPaymentResult(ctx, o.ID, true); again.Status != Paid { // webhook replay
		t.Fatalf("replay changed status: %+v", again)
	}
	if seat, _ := inv.Snapshot("ev1", "A-1"); seat.State != inventory.Sold {
		t.Fatalf("seat not sold: %+v", seat)
	}

	s, inv, _ = setup(t)
	o, _, _ = s.Checkout(ctx, req())
	if got, _ := s.OnPaymentResult(ctx, o.ID, false); got.Status != PaymentFailed {
		t.Fatalf("failure: %+v", got)
	}
	if seat, _ := inv.Snapshot("ev1", "A-1"); seat.State != inventory.Available {
		t.Fatalf("seat not released: %+v", seat)
	}

	s, _, c := setup(t)
	o, _, _ = s.Checkout(ctx, req())
	c.t = c.t.Add(10 * time.Minute) // provider answered after the hold expired
	if got, _ := s.OnPaymentResult(ctx, o.ID, true); got.Status != RefundRequired {
		t.Fatalf("late payment: %+v", got)
	}
	topics := []string{}
	for _, m := range s.Pending(10) {
		topics = append(topics, m.Topic)
	}
	if len(topics) != 2 || topics[1] != "RefundPayment" {
		t.Fatalf("outbox topics = %v", topics)
	}
}

Waiting-room token issuer and verifier with shuffle-then-FIFO admission:

go
// Package waitingroom is the edge queue in front of the on-sale: visitors
// who arrive before the start are shuffled (randomised admission), later
// arrivals join the back (FIFO), and admitted visitors get a signed,
// short-lived admission token that the origin verifies without a lookup.
package waitingroom

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"math/rand/v2"
	"strings"
	"sync"
	"time"
)

var (
	ErrBadToken     = errors.New("waitingroom: malformed or forged token")
	ErrExpiredToken = errors.New("waitingroom: token expired or not yet valid")
	ErrWrongEvent   = errors.New("waitingroom: token is for another event")
)

// Claims travel in the token; keep them small (it rides on every request).
type Claims struct {
	Event     string `json:"e"`
	Visitor   string `json:"v"`
	Position  int    `json:"p"`
	NotBefore int64  `json:"nbf"`
	Expires   int64  `json:"exp"`
}

// Issuer signs with HMAC-SHA256. Edge and origin share the key (rotate it
// per on-sale; accept the previous key for one token lifetime).
type Issuer struct {
	Key []byte
	TTL time.Duration // e.g. 10 minutes: long enough to pick seats and pay
	Now func() time.Time
}

var b64 = base64.RawURLEncoding

func (is Issuer) mac(payload string) []byte {
	m := hmac.New(sha256.New, is.Key)
	m.Write([]byte(payload))
	return m.Sum(nil)
}

func (is Issuer) Issue(event, visitor string, position int) (string, error) {
	now := is.Now()
	c := Claims{Event: event, Visitor: visitor, Position: position,
		NotBefore: now.Unix(), Expires: now.Add(is.TTL).Unix()}
	raw, err := json.Marshal(c)
	if err != nil {
		return "", err
	}
	p := b64.EncodeToString(raw)
	return p + "." + b64.EncodeToString(is.mac(p)), nil
}

// Verify checks signature first (constant time), then time and audience.
func (is Issuer) Verify(token, event string) (Claims, error) {
	p, sig, ok := strings.Cut(token, ".")
	if !ok {
		return Claims{}, ErrBadToken
	}
	got, err := b64.DecodeString(sig)
	if err != nil || !hmac.Equal(got, is.mac(p)) {
		return Claims{}, ErrBadToken
	}
	raw, err := b64.DecodeString(p)
	if err != nil {
		return Claims{}, ErrBadToken
	}
	var c Claims
	if err := json.Unmarshal(raw, &c); err != nil {
		return Claims{}, ErrBadToken
	}
	now := is.Now().Unix()
	if now < c.NotBefore || now >= c.Expires {
		return c, ErrExpiredToken
	}
	if c.Event != event {
		return c, ErrWrongEvent
	}
	return c, nil
}

// Room orders visitors. Before Start: a pre-queue (arrival time does not
// matter). Start shuffles it once. After Start: plain FIFO.
type Room struct {
	mu      sync.Mutex
	started bool
	queue   []string
	seen    map[string]bool // one place per visitor (device/account dedup)
	rng     *rand.Rand
}

func NewRoom(seed1, seed2 uint64) *Room {
	return &Room{seen: map[string]bool{}, rng: rand.New(rand.NewPCG(seed1, seed2))}
}

// Join is idempotent per visitor: refreshing does not buy a second ticket in the raffle.
func (r *Room) Join(visitor string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.seen[visitor] {
		return
	}
	r.seen[visitor] = true
	r.queue = append(r.queue, visitor)
}

// Start randomises everyone who arrived early.
func (r *Room) Start() {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.started {
		return
	}
	r.rng.Shuffle(len(r.queue), func(i, j int) { r.queue[i], r.queue[j] = r.queue[j], r.queue[i] })
	r.started = true
}

// Admit releases up to n visitors; the caller sizes n from free shopping slots
// (active-shopper cap minus current shoppers), not from a fixed rate alone.
func (r *Room) Admit(n int) []string {
	r.mu.Lock()
	defer r.mu.Unlock()
	if !r.started {
		return nil
	}
	if n > len(r.queue) {
		n = len(r.queue)
	}
	out := append([]string(nil), r.queue[:n]...)
	r.queue = r.queue[n:]
	return out
}

func (r *Room) Len() int {
	r.mu.Lock()
	defer r.mu.Unlock()
	return len(r.queue)
}
go
package waitingroom

import (
	"errors"
	"fmt"
	"strings"
	"testing"
	"time"
)

func TestTokenRoundTripAndTamper(t *testing.T) {
	now := time.Date(2026, 11, 26, 19, 0, 0, 0, time.UTC)
	is := Issuer{Key: []byte("test-key-rotate-per-onsale"), TTL: 10 * time.Minute, Now: func() time.Time { return now }}
	tok, err := is.Issue("ev1", "visitor-42", 1234)
	if err != nil {
		t.Fatal(err)
	}
	c, err := is.Verify(tok, "ev1")
	if err != nil || c.Position != 1234 || c.Visitor != "visitor-42" {
		t.Fatalf("verify: %+v %v", c, err)
	}
	if _, err := is.Verify(tok, "ev2"); !errors.Is(err, ErrWrongEvent) {
		t.Fatalf("wrong event: %v", err)
	}
	p, sig, _ := strings.Cut(tok, ".")
	forged := strings.ToUpper(p[:1]) + p[1:] + "." + sig
	if forged != tok {
		if _, err := is.Verify(forged, "ev1"); !errors.Is(err, ErrBadToken) {
			t.Fatalf("forged: %v", err)
		}
	}
	other := Issuer{Key: []byte("other"), TTL: time.Minute, Now: is.Now}
	if _, err := other.Verify(tok, "ev1"); !errors.Is(err, ErrBadToken) {
		t.Fatalf("other key: %v", err)
	}
	later := is
	later.Now = func() time.Time { return now.Add(11 * time.Minute) }
	if _, err := later.Verify(tok, "ev1"); !errors.Is(err, ErrExpiredToken) {
		t.Fatalf("expired: %v", err)
	}
}

func TestRandomisedThenFIFO(t *testing.T) {
	r := NewRoom(1, 2)
	for i := range 1000 {
		r.Join(fmt.Sprintf("early-%04d", i))
	}
	r.Join("early-0000") // refresh: no second place
	if got := r.Admit(10); got != nil {
		t.Fatalf("admitted before start: %v", got)
	}
	r.Start()
	r.Join("late-1")
	r.Join("late-2")
	if r.Len() != 1002 {
		t.Fatalf("len = %d", r.Len())
	}
	first := r.Admit(1000)
	inOrder := 0
	for i, v := range first {
		if !strings.HasPrefix(v, "early-") {
			t.Fatalf("late visitor %s admitted before an early one", v)
		}
		if v == fmt.Sprintf("early-%04d", i) {
			inOrder++
		}
	}
	if inOrder > 50 {
		t.Fatalf("pre-queue not shuffled: %d of 1000 kept their arrival slot", inOrder)
	}
	if rest := r.Admit(5); len(rest) != 2 || rest[0] != "late-1" || rest[1] != "late-2" {
		t.Fatalf("late arrivals not FIFO: %v", rest)
	}
}

QR signer and offline scanner with generations and first-scan-wins:

go
// Package ticketqr signs tickets for QR codes and validates them offline at
// the gate: Ed25519 so scanners hold only the public key, an ownership
// generation so a transfer revokes the old code, a revocation list synced
// before doors open, and a local first-scan-wins set against screenshots.
package ticketqr

import (
	"crypto/ed25519"
	"encoding/base64"
	"encoding/json"
	"errors"
	"strings"
	"sync"
	"time"
)

var (
	ErrForged      = errors.New("ticketqr: bad signature or format")
	ErrWrongEvent  = errors.New("ticketqr: ticket for another event")
	ErrOutsideTime = errors.New("ticketqr: outside the validity window")
	ErrRevoked     = errors.New("ticketqr: revoked (transferred, refunded or resold)")
	ErrAlreadyIn   = errors.New("ticketqr: already scanned")
)

type Claims struct {
	TicketID   string `json:"tid"`
	Event      string `json:"eid"`
	Seat       string `json:"seat"`
	Generation int    `json:"gen"` // bumped on every transfer or resale
	NotBefore  int64  `json:"nbf"` // doors open
	Expires    int64  `json:"exp"` // event end
}

var b64 = base64.RawURLEncoding

// Sign produces "T1.<payload>.<signature>", short enough for a QR code.
func Sign(priv ed25519.PrivateKey, c Claims) (string, error) {
	raw, err := json.Marshal(c)
	if err != nil {
		return "", err
	}
	p := "T1." + b64.EncodeToString(raw)
	return p + "." + b64.EncodeToString(ed25519.Sign(priv, []byte(p))), nil
}

// Scanner runs on a gate device with no network. Revoked maps ticket id to
// the highest revoked generation; it is downloaded before doors open and
// refreshed whenever the device is online.
type Scanner struct {
	Pub     ed25519.PublicKey
	Event   string
	Now     func() time.Time
	mu      sync.Mutex
	revoked map[string]int
	scanned map[string]time.Time
}

func NewScanner(pub ed25519.PublicKey, event string, now func() time.Time) *Scanner {
	return &Scanner{Pub: pub, Event: event, Now: now, revoked: map[string]int{}, scanned: map[string]time.Time{}}
}

// Revoke records that every generation <= gen of a ticket is dead.
func (s *Scanner) Revoke(ticketID string, gen int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if gen > s.revoked[ticketID] {
		s.revoked[ticketID] = gen
	}
}

func (s *Scanner) Scan(code string) (Claims, error) {
	i := strings.LastIndexByte(code, '.')
	if i < 0 || !strings.HasPrefix(code, "T1.") {
		return Claims{}, ErrForged
	}
	signed, sigPart := code[:i], code[i+1:]
	sig, err := b64.DecodeString(sigPart)
	if err != nil || !ed25519.Verify(s.Pub, []byte(signed), sig) {
		return Claims{}, ErrForged
	}
	raw, err := b64.DecodeString(strings.TrimPrefix(signed, "T1."))
	if err != nil {
		return Claims{}, ErrForged
	}
	var c Claims
	if err := json.Unmarshal(raw, &c); err != nil {
		return Claims{}, ErrForged
	}
	if c.Event != s.Event {
		return c, ErrWrongEvent
	}
	now := s.Now()
	if now.Unix() < c.NotBefore || now.Unix() >= c.Expires {
		return c, ErrOutsideTime
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if g, ok := s.revoked[c.TicketID]; ok && c.Generation <= g {
		return c, ErrRevoked
	}
	if _, ok := s.scanned[c.TicketID]; ok {
		return c, ErrAlreadyIn
	}
	s.scanned[c.TicketID] = now
	return c, nil
}

// Transfer is the server side: new owner, new generation, old code revoked.
func Transfer(priv ed25519.PrivateKey, old Claims) (Claims, string, error) {
	next := old
	next.Generation++
	code, err := Sign(priv, next)
	return next, code, err
}
go
package ticketqr

import (
	"crypto/ed25519"
	"errors"
	"testing"
	"time"
)

func TestOfflineScanTransferRevocation(t *testing.T) {
	pub, priv, err := ed25519.GenerateKey(nil)
	if err != nil {
		t.Fatal(err)
	}
	doors := time.Date(2026, 12, 5, 18, 0, 0, 0, time.UTC)
	c := Claims{TicketID: "tk-1", Event: "ev1", Seat: "A-12-7", Generation: 1,
		NotBefore: doors.Unix(), Expires: doors.Add(6 * time.Hour).Unix()}
	oldCode, err := Sign(priv, c)
	if err != nil {
		t.Fatal(err)
	}
	// fan sells the ticket on the resale marketplace: new generation
	_, newCode, err := Transfer(priv, c)
	if err != nil {
		t.Fatal(err)
	}

	now := doors.Add(30 * time.Minute)
	gate := NewScanner(pub, "ev1", func() time.Time { return now })
	gate.Revoke("tk-1", 1) // from the revocation list synced before doors

	if _, err := gate.Scan(oldCode); !errors.Is(err, ErrRevoked) {
		t.Fatalf("old code after transfer: %v", err)
	}
	if got, err := gate.Scan(newCode); err != nil || got.Generation != 2 {
		t.Fatalf("new code: %+v %v", got, err)
	}
	if _, err := gate.Scan(newCode); !errors.Is(err, ErrAlreadyIn) {
		t.Fatalf("screenshot reuse: %v", err)
	}
	if _, err := gate.Scan(newCode[:len(newCode)-2] + "AA"); !errors.Is(err, ErrForged) {
		t.Fatalf("tampered: %v", err)
	}
	other := NewScanner(pub, "ev2", gate.Now)
	if _, err := other.Scan(newCode); !errors.Is(err, ErrWrongEvent) {
		t.Fatalf("wrong event: %v", err)
	}
	early := NewScanner(pub, "ev1", func() time.Time { return doors.Add(-time.Hour) })
	if _, err := early.Scan(newCode); !errors.Is(err, ErrOutsideTime) {
		t.Fatalf("before doors: %v", err)
	}
}

The Go angle ​

Go featureUse hereNote
pgx.BeginTxFuncHold, confirm and checkout transactionsCommits on nil, rolls back on error
pgx.CollectRows + pgx.RowTo[string]Read locked seat idsGeneric row collection in pgx v5
pgconn.PgError.CodeMap 55P03/40P01/40001 to a domain errorerrors.As
pgxpool.PoolOne pool per partition tier (bulkhead)Size it below max_connections
redis.NewScript (go-redis v9)Lua hold, release, extendUses EVALSHA, falls back to EVAL
sync.Mutex per eventThe in-memory single writerSame semantics as one partition's row locks
go test -raceProves no data race in the fakeRun it in CI for every concurrency change
crypto/hmac, hmac.EqualAdmission tokensConstant-time compare
crypto/ed25519Ticket QR signaturesScanners need only the public key
math/rand/v2 with NewPCGDeterministic shuffle in testsUse a crypto seed in production
time.Ticker + contextSweeper loopStops cleanly on shutdown

Laravel ​

Example ​

Schema (unpartitioned for tests; partitioning by event in raw SQL):

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // Partitioning by event is done in raw SQL (sql/schema.sql); Laravel's
        // schema builder creates the unpartitioned shape used in tests.
        Schema::create('seats', function (Blueprint $table) {
            $table->string('event_id');
            $table->string('seat_id');
            $table->string('section');
            $table->integer('row_no');
            $table->integer('seat_no');
            $table->integer('price_cents');
            $table->string('state')->default('available');
            $table->string('hold_id')->nullable();
            $table->timestampTz('hold_expires_at')->nullable();
            $table->string('order_id')->nullable();
            $table->unsignedBigInteger('version')->default(0);
            $table->primary(['event_id', 'seat_id']);
            $table->index(['event_id', 'state', 'hold_expires_at']);
            $table->index(['event_id', 'hold_id']);
        });

        Schema::create('orders', function (Blueprint $table) {
            $table->string('order_id')->primary();
            $table->string('user_id');
            $table->string('event_id');
            $table->string('hold_id');
            $table->bigInteger('amount_cents');
            $table->string('status')->default('pending_payment');
            $table->timestampsTz();
        });

        Schema::create('idempotency_keys', function (Blueprint $table) {
            $table->string('user_id');
            $table->string('key');
            $table->string('fingerprint', 64);
            $table->string('order_id');
            $table->timestampTz('created_at')->useCurrent();
            $table->primary(['user_id', 'key']);
        });

        Schema::create('outbox', function (Blueprint $table) {
            $table->id();
            $table->string('topic');
            $table->string('aggregate_id');
            $table->jsonb('payload');
            $table->timestampTz('created_at')->useCurrent();
            $table->timestampTz('sent_at')->nullable()->index();
        });

        Schema::create('tickets', function (Blueprint $table) {
            $table->string('ticket_id')->primary();
            $table->string('order_id');
            $table->string('event_id');
            $table->string('seat_id');
            $table->string('owner_id');
            $table->integer('generation')->default(1);
            $table->string('status')->default('valid');
            $table->unique(['event_id', 'seat_id', 'generation']);
        });
    }

    public function down(): void
    {
        foreach (['tickets', 'outbox', 'idempotency_keys', 'orders', 'seats'] as $t) {
            Schema::dropIfExists($t);
        }
    }
};

Seat hold with lockForUpdate inside DB::transaction, plus best available with ->lock('for update skip locked'). The query builder's lock() accepts a raw string, and the PostgreSQL grammar's compileLock returns it unchanged (read in the 13.x source):

php
<?php

namespace App\Services;

use App\Events\SeatsChanged;
use App\Exceptions\SeatUnavailable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class SeatHoldService
{
    public const HOLD_MINUTES = 8;

    /**
     * Hold the seats the buyer clicked on the seat map: all or nothing.
     *
     * @param  list<string>  $seatIds
     */
    public function hold(string $eventId, array $seatIds, string $userId): string
    {
        sort($seatIds); // same lock order for every buyer: no deadlocks
        $holdId = (string) Str::uuid();

        DB::transaction(function () use ($eventId, $seatIds, $holdId) {
            DB::statement("SET LOCAL lock_timeout = '200ms'");

            $free = DB::table('seats')
                ->where('event_id', $eventId)
                ->whereIn('seat_id', $seatIds)
                ->where(fn ($q) => $q->where('state', 'available')
                    ->orWhere(fn ($q) => $q->where('state', 'held')
                        ->where('hold_expires_at', '<=', now())))
                ->orderBy('seat_id')
                ->lockForUpdate()            // SELECT ... FOR UPDATE
                ->pluck('seat_id');

            if ($free->count() !== count($seatIds)) {
                throw new SeatUnavailable($eventId, $seatIds);
            }

            DB::table('seats')
                ->where('event_id', $eventId)
                ->whereIn('seat_id', $seatIds)
                ->update([
                    'state' => 'held',
                    'hold_id' => $holdId,
                    'hold_expires_at' => now()->addMinutes(self::HOLD_MINUTES),
                    'version' => DB::raw('version + 1'),
                ]);
        }, attempts: 1);

        SeatsChanged::dispatch($eventId, $seatIds, 'held');

        return $holdId;
    }

    /**
     * "Best available": the query builder's lock() takes a raw lock clause,
     * which the PostgreSQL grammar passes through unchanged.
     *
     * @return list<string>
     */
    public function holdBestAvailable(string $eventId, string $section, int $count): array
    {
        $holdId = (string) Str::uuid();

        $seats = DB::transaction(function () use ($eventId, $section, $count, $holdId) {
            $ids = DB::table('seats')
                ->where('event_id', $eventId)
                ->where('section', $section)
                ->where('state', 'available')
                ->orderBy('row_no')->orderBy('seat_no')
                ->limit($count)
                ->lock('for update skip locked')
                ->pluck('seat_id')
                ->all();

            if (count($ids) < $count) {
                throw new SeatUnavailable($eventId, $ids);
            }

            DB::table('seats')
                ->where('event_id', $eventId)
                ->whereIn('seat_id', $ids)
                ->update([
                    'state' => 'held',
                    'hold_id' => $holdId,
                    'hold_expires_at' => now()->addMinutes(self::HOLD_MINUTES),
                    'version' => DB::raw('version + 1'),
                ]);

            return $ids;
        });

        SeatsChanged::dispatch($eventId, $seats, 'held');

        return $seats;
    }

    /** Idempotent: only seats still held by this hold are touched. */
    public function release(string $eventId, string $holdId): int
    {
        $seatIds = DB::table('seats')
            ->where('event_id', $eventId)->where('hold_id', $holdId)
            ->pluck('seat_id')->all();

        $n = DB::table('seats')
            ->where('event_id', $eventId)
            ->where('hold_id', $holdId)
            ->where('state', 'held')
            ->update([
                'state' => 'available',
                'hold_id' => null,
                'hold_expires_at' => null,
                'version' => DB::raw('version + 1'),
            ]);

        if ($n > 0) {
            SeatsChanged::dispatch($eventId, $seatIds, 'available');
        }

        return $n;
    }
}
php
<?php

namespace App\Exceptions;

use Illuminate\Http\JsonResponse;
use RuntimeException;

class SeatUnavailable extends RuntimeException
{
    /** @param list<string> $seatIds */
    public function __construct(public string $eventId, public array $seatIds)
    {
        parent::__construct('seat_unavailable');
    }

    public function render(): JsonResponse
    {
        return response()->json([
            'type' => 'https://tickets.example.com/problems/seat-unavailable',
            'title' => 'One or more seats were just taken',
            'status' => 409,
            'seats' => $this->seatIds,
        ], 409, ['Content-Type' => 'application/problem+json']);
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Services\SeatHoldService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class HoldController extends Controller
{
    public function __construct(private SeatHoldService $holds) {}

    /** POST /events/{event}/holds {"seats": [...]} or {"section": "S112", "count": 2} */
    public function store(Request $request, string $event): JsonResponse
    {
        $data = $request->validate([
            'seats' => ['required_without:section', 'array', 'min:1', 'max:6'],
            'seats.*' => ['string', 'max:32'],
            'section' => ['required_without:seats', 'string', 'max:16'],
            'count' => ['required_with:section', 'integer', 'between:1,6'],
        ]);

        if (isset($data['seats'])) {
            $holdId = $this->holds->hold($event, array_values(array_unique($data['seats'])), (string) $request->user()->getAuthIdentifier());

            return response()->json(['hold_id' => $holdId, 'seats' => $data['seats'],
                'expires_in' => SeatHoldService::HOLD_MINUTES * 60], 201);
        }

        $seats = $this->holds->holdBestAvailable($event, $data['section'], (int) $data['count']);

        return response()->json(['seats' => $seats, 'expires_in' => SeatHoldService::HOLD_MINUTES * 60], 201);
    }

    /** DELETE /events/{event}/holds/{hold}: idempotent, 204 even the second time. */
    public function destroy(string $event, string $hold): JsonResponse
    {
        $this->holds->release($event, $hold);

        return response()->json(null, 204);
    }
}

Cache::lock holds. The cache docs describe passing the lock's "owner token" to a queued job so it can "re-instantiate the lock" with Cache::restoreLock. That is what the release does here. Several locks taken one by one are not one atomic step, so this variant is a gate in front of the database, not a replacement for it:

php
<?php

namespace App\Services;

use Illuminate\Contracts\Cache\Lock;
use Illuminate\Support\Facades\Cache;

/**
 * Seat holds as Laravel atomic locks (redis store). One lock per seat, taken
 * in sorted order and rolled back on the first failure. Simpler than the Lua
 * script but not one atomic step: a crash between two get() calls leaves a
 * partial hold that only the TTL cleans up. PostgreSQL still confirms the sale.
 */
class CacheSeatHold
{
    public function __construct(private int $seconds = 480) {}

    private function key(string $eventId, string $seatId): string
    {
        return "seat:{$eventId}:{$seatId}";
    }

    /**
     * @param  list<string>  $seatIds
     * @return array<string, string>|null seat id => owner token, or null if taken
     */
    public function hold(string $eventId, array $seatIds): ?array
    {
        sort($seatIds);
        /** @var array<string, Lock> $taken */
        $taken = [];

        foreach ($seatIds as $seatId) {
            $lock = Cache::store('redis')->lock($this->key($eventId, $seatId), $this->seconds);
            if (! $lock->get()) {
                foreach ($taken as $held) {
                    $held->release();
                }

                return null;
            }
            $taken[$seatId] = $lock;
        }

        // the owner token lets the payment job release the lock later
        return array_map(fn (Lock $l) => $l->owner(), $taken);
    }

    /** @param array<string, string> $owners */
    public function release(string $eventId, array $owners): void
    {
        foreach ($owners as $seatId => $owner) {
            // restoreLock + release only deletes the key if the owner still matches
            Cache::store('redis')->restoreLock($this->key($eventId, $seatId), $owner)->release();
        }
    }
}

Idempotent checkout with an outbox row and the payment webhook as the saga step:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    /** POST /events/{event}/orders with an Idempotency-Key header. */
    public function store(Request $request, string $event): JsonResponse
    {
        $key = $request->header('Idempotency-Key');
        abort_if(! is_string($key) || strlen($key) < 16 || strlen($key) > 255, 400, 'Idempotency-Key required');

        $data = $request->validate([
            'hold_id' => ['required', 'uuid'],
        ]);
        $userId = (string) $request->user()->getAuthIdentifier();
        $fingerprint = hash('sha256', $event.'|'.$data['hold_id']);

        if ($replay = $this->replay($userId, $key, $fingerprint)) {
            return $replay;
        }

        try {
            $order = DB::transaction(function () use ($event, $data, $userId, $key, $fingerprint) {
                $amount = (int) DB::table('seats')
                    ->where('event_id', $event)
                    ->where('hold_id', $data['hold_id'])
                    ->where('state', 'held')
                    ->where('hold_expires_at', '>', now())
                    ->lockForUpdate()
                    ->sum('price_cents');
                abort_if($amount === 0, 410, 'Hold expired');

                $orderId = 'ord-'.Str::ulid();
                DB::table('orders')->insert([
                    'order_id' => $orderId, 'user_id' => $userId, 'event_id' => $event,
                    'hold_id' => $data['hold_id'], 'amount_cents' => $amount,
                    'created_at' => now(), 'updated_at' => now(),
                ]);
                DB::table('idempotency_keys')->insert([
                    'user_id' => $userId, 'key' => $key,
                    'fingerprint' => $fingerprint, 'order_id' => $orderId,
                ]);
                // the outbox row commits with the order: no lost or phantom charge
                DB::table('outbox')->insert([
                    'topic' => 'ChargeRequested',
                    'aggregate_id' => $orderId,
                    'payload' => json_encode([
                        'amount_cents' => $amount,
                        'provider_idempotency_key' => $orderId.'-charge',
                    ]),
                ]);
                // payment can take minutes: extend the hold once, server side
                DB::table('seats')
                    ->where('event_id', $event)->where('hold_id', $data['hold_id'])
                    ->update(['hold_expires_at' => now()->addMinutes(15)]);

                return ['order_id' => $orderId, 'amount_cents' => $amount, 'status' => 'pending_payment'];
            });
        } catch (UniqueConstraintViolationException) {
            // a concurrent retry with the same key won the insert
            return $this->replay($userId, $key, $fingerprint) ?? abort(409);
        }

        return response()->json($order, 201);
    }

    private function replay(string $userId, string $key, string $fingerprint): ?JsonResponse
    {
        $row = DB::table('idempotency_keys')->where(['user_id' => $userId, 'key' => $key])->first();
        if ($row === null) {
            return null;
        }
        abort_if($row->fingerprint !== $fingerprint, 422, 'Idempotency-Key reused with a different request');
        $order = DB::table('orders')->where('order_id', $row->order_id)->first();

        return response()->json([
            'order_id' => $order->order_id,
            'amount_cents' => $order->amount_cents,
            'status' => $order->status,
        ], 200, ['Idempotent-Replayed' => 'true']);
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Services\SeatHoldService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

/**
 * The saga step after the payment provider answers. Signature verification of
 * the webhook is provider-specific and omitted; see the payment chapter.
 */
class PaymentWebhookController extends Controller
{
    public function __invoke(Request $request, SeatHoldService $holds): Response
    {
        $orderId = (string) $request->input('order_id');
        $succeeded = $request->input('status') === 'succeeded';

        DB::transaction(function () use ($orderId, $succeeded, $holds) {
            $order = DB::table('orders')->where('order_id', $orderId)->lockForUpdate()->first();
            if ($order === null || $order->status !== 'pending_payment') {
                return; // duplicate webhook: the state machine already moved
            }

            if (! $succeeded) {
                $holds->release($order->event_id, $order->hold_id);   // compensation
                $this->move($orderId, 'payment_failed', 'SeatsReleased');

                return;
            }

            $sold = DB::table('seats')
                ->where('event_id', $order->event_id)
                ->where('hold_id', $order->hold_id)
                ->where('state', 'held')
                ->where('hold_expires_at', '>', now())
                ->update(['state' => 'sold', 'order_id' => $orderId, 'hold_id' => null,
                    'hold_expires_at' => null, 'version' => DB::raw('version + 1')]);

            $sold > 0
                ? $this->move($orderId, 'paid', 'IssueTickets')
                : $this->move($orderId, 'refund_required', 'RefundPayment'); // paid too late
        });

        return response()->noContent();
    }

    private function move(string $orderId, string $status, string $topic): void
    {
        DB::table('orders')->where('order_id', $orderId)->update(['status' => $status, 'updated_at' => now()]);
        DB::table('outbox')->insert(['topic' => $topic, 'aggregate_id' => $orderId, 'payload' => '{}']);
    }
}

Outbox relay and hold sweeper as Artisan commands (#[Signature] attributes, Laravel 13):

php
<?php

namespace App\Console\Commands;

use App\Jobs\IssueTickets;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('outbox:relay {--batch=100}')]
#[Description('Publish unsent outbox rows; several relays may run (SKIP LOCKED).')]
class RelayOutbox extends Command
{
    public function handle(): int
    {
        DB::transaction(function () {
            $rows = DB::table('outbox')
                ->whereNull('sent_at')
                ->orderBy('id')
                ->limit((int) $this->option('batch'))
                ->lock('for update skip locked')
                ->get();

            foreach ($rows as $row) {
                match ($row->topic) {
                    'IssueTickets' => IssueTickets::dispatch($row->aggregate_id)->afterCommit(),
                    default => null, // ChargeRequested, RefundPayment... go to the payment worker
                };
            }

            DB::table('outbox')->whereIn('id', $rows->pluck('id'))->update(['sent_at' => now()]);
        });

        return self::SUCCESS;
    }
}
php
<?php

namespace App\Console\Commands;

use App\Events\SeatsChanged;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

#[Signature('holds:sweep {event} {--batch=500}')]
#[Description('Return expired seat holds to sale in small batches.')]
class SweepExpiredHolds extends Command
{
    public function handle(): int
    {
        $event = (string) $this->argument('event');

        do {
            $freed = DB::transaction(function () use ($event) {
                $ids = DB::table('seats')
                    ->where('event_id', $event)
                    ->where('state', 'held')
                    ->where('hold_expires_at', '<=', now())
                    ->limit((int) $this->option('batch'))
                    ->lock('for update skip locked')
                    ->pluck('seat_id')
                    ->all();

                DB::table('seats')->where('event_id', $event)->whereIn('seat_id', $ids)
                    ->update(['state' => 'available', 'hold_id' => null,
                        'hold_expires_at' => null, 'version' => DB::raw('version + 1')]);

                return $ids;
            });

            if ($freed !== []) {
                SeatsChanged::dispatch($event, $freed, 'available');
            }
        } while (count($freed) === (int) $this->option('batch'));

        return self::SUCCESS;
    }
}

Queued ticket issuance, idempotent on redelivery. ShouldBeUnique only stops duplicate queueing, so the handler checks for existing tickets inside the transaction:

php
<?php

namespace App\Jobs;

use App\Support\TicketSigner;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

#[Tries(10)]
#[Backoff([5, 30, 120])]
class IssueTickets implements ShouldQueue, ShouldBeUnique
{
    use Queueable;

    public function __construct(public string $orderId) {}

    /** One pending job per order; uniqueness is a dispatch-time lock only. */
    public function uniqueId(): string
    {
        return $this->orderId;
    }

    public function handle(TicketSigner $signer): void
    {
        DB::transaction(function () use ($signer) {
            $order = DB::table('orders')->where('order_id', $this->orderId)->lockForUpdate()->first();
            if ($order === null || $order->status !== 'paid') {
                return;
            }
            if (DB::table('tickets')->where('order_id', $this->orderId)->exists()) {
                return; // redelivery after a crash: tickets already issued
            }

            $seats = DB::table('seats')
                ->where('event_id', $order->event_id)
                ->where('order_id', $this->orderId)
                ->get(['seat_id']);

            foreach ($seats as $seat) {
                $ticketId = 'tk-'.Str::ulid();
                // unique (event_id, seat_id, generation) is the last line of defence
                DB::table('tickets')->insert([
                    'ticket_id' => $ticketId, 'order_id' => $this->orderId,
                    'event_id' => $order->event_id, 'seat_id' => $seat->seat_id,
                    'owner_id' => $order->user_id, 'generation' => 1,
                ]);
            }

            DB::table('outbox')->insert([
                'topic' => 'TicketsIssued',
                'aggregate_id' => $this->orderId,
                'payload' => json_encode(['download' => $signer->downloadUrl($this->orderId)]),
            ]);
        });
    }
}

Signed QR payloads and signed download URLs:

php
<?php

namespace App\Support;

use Illuminate\Support\Facades\URL;

/**
 * Same wire format as the Go ticketqr package: "T1.<payload>.<signature>",
 * Ed25519 via ext-sodium so gate scanners only need the public key.
 */
class TicketSigner
{
    public function __construct(private string $secretKey) {} // 64-byte sodium sign secret key

    private static function b64(string $bin): string
    {
        return rtrim(strtr(base64_encode($bin), '+/', '-_'), '=');
    }

    /** @param array{tid:string,eid:string,seat:string,gen:int,nbf:int,exp:int} $claims */
    public function qrPayload(array $claims): string
    {
        $signed = 'T1.'.self::b64(json_encode($claims, JSON_THROW_ON_ERROR));

        return $signed.'.'.self::b64(sodium_crypto_sign_detached($signed, $this->secretKey));
    }

    /** A wallet/PDF link that expires and cannot be edited (HMAC with APP_KEY). */
    public function downloadUrl(string $orderId): string
    {
        return URL::temporarySignedRoute('tickets.download', now()->addDays(7), ['order' => $orderId]);
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Support\TicketSigner;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class TicketDownloadController extends Controller
{
    /** Reached only through URL::temporarySignedRoute (the 'signed' middleware). */
    public function __invoke(string $order, TicketSigner $signer): JsonResponse
    {
        $tickets = DB::table('tickets')
            ->join('events', 'events.event_id', '=', 'tickets.event_id')
            ->where('tickets.order_id', $order)
            ->where('tickets.status', 'valid')
            ->get(['tickets.ticket_id', 'tickets.event_id', 'tickets.seat_id', 'tickets.generation', 'events.starts_at']);

        return response()->json($tickets->map(fn ($t) => [
            'ticket_id' => $t->ticket_id,
            'seat' => $t->seat_id,
            'qr' => $signer->qrPayload([
                'tid' => $t->ticket_id, 'eid' => $t->event_id, 'seat' => $t->seat_id,
                'gen' => (int) $t->generation,
                'nbf' => strtotime($t->starts_at) - 4 * 3600,   // doors open
                'exp' => strtotime($t->starts_at) + 6 * 3600,
            ]),
        ]));
    }
}

Waiting-room token middleware, rate-limited on-sale routes:

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Verifies the waiting-room token (HMAC-SHA256, same format as the Go
 * waitingroom package) without a database or cache lookup.
 */
class RequireAdmissionToken
{
    public function handle(Request $request, Closure $next): Response
    {
        $token = (string) $request->cookie('admission', $request->header('X-Admission-Token', ''));
        [$payload, $sig] = array_pad(explode('.', $token, 2), 2, '');

        $expected = rtrim(strtr(base64_encode(
            hash_hmac('sha256', $payload, (string) config('services.waiting_room.key'), true)
        ), '+/', '-_'), '=');

        if ($payload === '' || ! hash_equals($expected, $sig)) {
            return redirect()->away((string) config('services.waiting_room.url'));
        }

        $claims = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
        $now = time();
        if (! is_array($claims)
            || ($claims['e'] ?? null) !== $request->route('event')
            || $now < ($claims['nbf'] ?? PHP_INT_MAX)
            || $now >= ($claims['exp'] ?? 0)) {
            return redirect()->away((string) config('services.waiting_room.url'));
        }

        $request->attributes->set('admission_visitor', $claims['v']);

        return $next($request);
    }
}
php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Per admitted visitor and per IP: humans click a few seats a minute,
        // scripts click hundreds. The waiting room already capped the crowd.
        RateLimiter::for('onsale-holds', function (Request $request) {
            return [
                Limit::perMinute(20)->by('v:'.$request->attributes->get('admission_visitor', $request->ip())),
                Limit::perMinute(120)->by('ip:'.$request->ip()),
            ];
        });

        RateLimiter::for('onsale-checkout', fn (Request $request) => Limit::perMinute(5)->by('u:'.$request->user()?->id));
    }
}
php
<?php

use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\HoldController;
use App\Http\Controllers\PaymentWebhookController;
use App\Http\Controllers\TicketDownloadController;
use App\Http\Middleware\RequireAdmissionToken;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth', RequireAdmissionToken::class])->prefix('events/{event}')->group(function () {
    Route::post('/holds', [HoldController::class, 'store'])->middleware('throttle:onsale-holds');
    Route::delete('/holds/{hold}', [HoldController::class, 'destroy']);
    Route::post('/orders', [CheckoutController::class, 'store'])->middleware('throttle:onsale-checkout');
});

Route::post('/webhooks/payments', PaymentWebhookController::class);

Route::get('/orders/{order}/tickets', TicketDownloadController::class)
    ->name('tickets.download')
    ->middleware('signed');

Reverb seat updates, a broadcast event on a public per-event channel:

php
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;

/**
 * Pushed through Reverb to every open seat map of the event. Public channel:
 * availability is not personal data. Clients apply deltas to the bitmap they
 * fetched from the CDN and re-fetch the snapshot if they miss a sequence.
 */
class SeatsChanged implements ShouldBroadcast
{
    use Dispatchable;

    /** @param list<string> $seatIds */
    public function __construct(
        public string $eventId,
        public array $seatIds,
        public string $state,
    ) {}

    public function broadcastOn(): Channel
    {
        return new Channel('event.'.$this->eventId.'.seats');
    }

    public function broadcastAs(): string
    {
        return 'seats.changed';
    }

    /** @return array<string, mixed> */
    public function broadcastWith(): array
    {
        return ['seats' => $this->seatIds, 'state' => $this->state];
    }
}

The Laravel angle ​

Laravel 13 featureUse hereNote
DB::transaction(fn, attempts: 1)Hold, checkout, webhookDo not auto-retry holds: a retry should re-read availability
lockForUpdate() / sharedLock()SELECT ... FOR UPDATE / FOR SHAREDocs recommend wrapping pessimistic locks in a transaction
->lock('for update skip locked')Best available, sweeper, relayRaw lock clause, passed through by the PostgreSQL grammar
UniqueConstraintViolationExceptionConcurrent idempotency-key insertReplay the stored order
Cache::lock($key, $seconds), owner(), restoreLock()Redis seat locks released by another processNeeds a lock-capable store
ShouldQueue, ShouldBeUnique, #[Tries], #[Backoff]Ticket issuance jobUniqueness is dispatch-time only
->afterCommit() / after_commitDispatch only after the transaction commitsNot an outbox: a crash after commit loses the dispatch
RateLimiter::for + throttle: middlewareHolds per visitor and per IPMultiple Limit objects per limiter
URL::temporarySignedRoute + signed middlewareTicket download linksHMAC with the app key; expires
ShouldBroadcast, broadcastOn, broadcastAs, broadcastWithSeat changes to ReverbShouldBroadcastNow skips the queue
Laravel Reverb reverb:start, REVERB_SCALING_ENABLEDWebSocket server, horizontal scaling over Redis pub/subDocs example: about 28,231 connections per server before raising the port range
#[Signature], #[Description]Artisan commandsLaravel 13 attribute style

Solving the classic problems ​

Two buyers, one seat ​

SolutionHowAdvantageCost / limitation
FOR UPDATE in seat orderLock, check, update in one short transactionExact seats, simplest correct answerWaits on hot rows: add lock_timeout
Conditional UPDATE ... WHERE state = 'available'One statement, check RowsAffectedNo explicit lock statementMulti-seat needs all-or-nothing handling
Version columnWHERE version = $readNo locks held between read and writeMany retries on hot rows
Redis Lua holdScript checks then sets all keysFastest, no DB loadTwo sources of truth; rebuild after loss
Unique index on valid ticketsLast line of defenceCatches bugs anywhere upstreamFails late (after payment)

Ghost holds: seats stuck as "held" ​

Cause: a hold without a deadline, or correctness that waits for a cleanup job. Fix: deadline set by the database clock, lazy expiry in every hold query, a sweeper with SKIP LOCKED, alert on holds older than two sweeper intervals.

The thundering herd at T0 ​

Cause: 100,000 browsers request the seat map and the hold endpoint in the same second. Fix: waiting room with a pre-queue that opens 15-60 minutes before (Queue-it's documented range), static seat map from a pre-warmed CDN, admission at the measured rate, origin load shedding with Retry-After.

Charged but no ticket ​

Cause: the process crashed between the charge and the ticket write, or the event was published before the commit. Fix: confirm and IssueTickets outbox row in one transaction; idempotent issuance; reconciliation job comparing provider charges with orders every few minutes.

Paid after the hold expired ​

Cause: payment latency longer than the hold. Fix: extend the hold once at checkout; on confirm failure, re-hold if free, else refund; alert on the refund_required rate and tune the TTL.

Redis lost the holds ​

Cause: Redis as the record. Fix: PostgreSQL as the record, Redis rebuilt from the database, DB-only fallback mode tested in the failover drill.

Scalpers and bots ​

Fix: account-bound queue positions, challenges at join time, randomised pre-queue, per-visitor rate limits, hold limits, price caps and identity checks on resale, generation-based revocation so resold tickets outside the platform fail at the gate.

Forged or copied tickets ​

Fix: asymmetric signatures (Ed25519) so scanners cannot mint; revocation lists for transfers; first-scan-wins per device; rotating codes against screenshots; reconcile scans when devices reconnect.

Choosing ​

Which hold mechanism ​

SituationRecommendationExtra techniqueReason
Reserved seating, under a few hundred holds/s per eventPostgreSQL FOR UPDATE in seat orderlock_timeout, short transactionsOne source of truth, simplest correct design
"Best available" / any N seatsFOR UPDATE SKIP LOCKED with LIMIT nPartial index on available seatsBuyers never wait behind each other
General admission (fungible)UPDATE ... SET remaining = remaining - n WHERE remaining >= nSharded counters for extreme rates (Write Buffering & Sharded Counters)No seat identity needed
Very high hold rate, many events at onceRedis Lua atomic hold as the gate, PostgreSQL confirmsHash tag per event, rebuild procedureKeeps contention off the database
Low contention admin editsVersion columnRetry once, then show conflictNo locks held across user think time
Multi-region active-active inventoryAvoid; give each event one home regionRoute by event to its homeTwo writers per seat is the bug

Which admission policy ​

SituationPolicyReason
Hot on-sale with a known start timeRandomised pre-queue, then FIFORewards arriving before the start, not speed
Steady demand, no start timeFIFOArrival order is intuitive and nobody gains from scripts' speed
Extreme demand vs supply (10x or more)Registration plus lottery days beforeAvoids 20 minutes of false hope for 90% of the queue
Testing thresholds before the real salePassthrough mode (Cloudflare)Measures traffic without queueing anyone
Event cancelled mid-saleReject modeStatic page, no origin load

Which ticket token ​

SituationChoiceReason
Stadium, unreliable networkEd25519-signed QR + revocation listOffline validation, scanners cannot forge
High-value, anti-screenshotRotating code in the appCopies expire in seconds
Small venue, always onlineRandom id + online lookupSimplest, instant revocation
Same party signs and verifies (admission token, links)HMACSymmetric is fine when there is one verifier

In architecture: from a single process to a distributed system ​

The same invariant (one writer per seat) appears at every scale; what changes is where the writer lives.

Monolith: one process, one database ​

A Laravel or Go monolith with one PostgreSQL database is the right first version for a ticketing start-up and handles the 50,000-seat estimate. Holds use lockForUpdate in DB::transaction; checkout writes the order and an outbox row in the same transaction; a queue worker issues tickets; Reverb pushes seat changes. The waiting room is bought (Cloudflare Waiting Room or Queue-it) and put in front of the on-sale routes. The single writer is simply "the seats table", and the whole design fits in this chapter's snippets.

Modular monolith: boundaries without the network ​

Split the code into modules with owned tables: Catalogue, Inventory, Orders, Payments, Tickets, Check-in. Only Inventory's module writes seats; Orders calls Inventory::confirm() in-process, still inside one database transaction. This keeps the strict path local while making the later split obvious. See Modular Monolith.

Microservices: every arrow is a decision ​

Inventory becomes its own service with its own database; Orders, Payments and Tickets are separate. The checkout now crosses a network: Orders asks Inventory to extend a hold (sync, with a deadline), writes its order and outbox locally, and the confirm step becomes an InventoryConfirm command consumed by Inventory, which replies SeatsSold or HoldExpired. That is the saga of the payment block, now with messages between services instead of function calls. What does not survive the split: one transaction covering order and seats. What must replace it: idempotent commands, an outbox in every service, and the inventory service's own conditional updates as the single writer.

text
Orders: tx(order pending, outbox ChargeRequested) -> Payments -> PaymentSucceeded
Orders: outbox ConfirmSeats{order, hold} -> Inventory: UPDATE ... WHERE hold live
Inventory: outbox SeatsSold | HoldExpired -> Orders: paid | refund_required

Distributed data: replicas, caches, regions ​

Read replicas serve the catalogue and order history, never hold decisions (replica lag would show a held seat as free). The availability bitmap is a cache with 1-2 s staleness and a sequence number. Redis holds are a cache of PostgreSQL state with a rebuild procedure. Multi-region: give each event a home region whose primary is the only writer for its seats; other regions serve browse traffic and forward holds to the home region; failover is a fenced promotion, not active-active writes. See Replication Topologies and CAP and PACELC.

Scaling path: 1x, 10x, 100x ​

LoadChangeWhat stays
1x (50k seats, 100k buyers)Monolith, one PostgreSQL, bought waiting room, CDN seat mapRow locks, outbox, signed QR
10x (several stadium on-sales at once, 1 M buyers)Partition seats by event; per-event API pools (bulkheads); Redis Lua gate; dedicated primary for the hottest eventPostgreSQL is still the record
100x (global platform, 10 M buyers for one tour)Home region per event, inventory service per region, stream-processed analytics, registration lotteries instead of a 10 M-person queueOne writer per seat

Lab: race the seats, then run the estimate ​

The Go tests and the estimator are single-process and were run; the PostgreSQL two-terminal experiments are expected, not run.

1. Run the concurrency tests with the race detector.

bash
cd docs/snippets/system-design/case-study-ticketing/go
go test -race ./...
# ok  academy/case-study-ticketing/inventory
# ok  academy/case-study-ticketing/purchase
# ok  academy/case-study-ticketing/redishold
# ok  academy/case-study-ticketing/ticketqr
# ok  academy/case-study-ticketing/waitingroom

2. Run the estimator (output as run):

bash
go run ./estimate
# orders to sell out             20000
# admissions per minute           1000
# minutes to sell out             20.0
# waiting-room polls/s (edge)     5000
# origin API QPS                 10000
# hold attempts/s                   50
# seat row writes/s                125
# payments/s (average)            16.7
# seat map egress MB/s (CDN)       4.1
# no-queue burst GB (CDN)         23.8
# availability bitmap KB           6.1
# seat rows MB per event           7.5
# ticket+order GB per year        10.0
# API instances (N+2)               19

Change activeShoppers to 500 (the "few hundred" Ticketmaster describes) and rerun: the sell-out time becomes 200 minutes, which shows why the admission cap is a business decision, not only a capacity one.

3. Break the invariant on purpose (expected, not run). Load sql/schema.sql into a scratch PostgreSQL, insert one event and seat, then in two psql sessions:

text
     psql A                                        psql B
1    BEGIN;
2    SELECT state FROM seats WHERE event_id='ev1' AND seat_id='A-1';  -- available
3                                                  BEGIN;
4                                                  SELECT state FROM seats WHERE ... ;  -- available
5    UPDATE seats SET state='sold', order_id='o1' WHERE event_id='ev1' AND seat_id='A-1';
6    COMMIT;
7                                                  UPDATE seats SET state='sold', order_id='o2' WHERE ...;
8                                                  COMMIT;   -- UPDATE 1: o1 overwritten, seat sold twice

4. Fix it with FOR UPDATE (expected, not run). Repeat with SELECT ... FOR UPDATE at steps 2 and 4: session B blocks at step 4 until A commits, then sees sold and its application code rolls back. Add SET LOCAL lock_timeout = '200ms' in B and keep A open for one second: B fails with ERROR: canceling statement due to lock timeout (SQLSTATE 55P03).

5. Skip instead of wait (expected, not run). With A holding a lock on seat A-1, run the best-available query from queries.sql in B with LIMIT 1: it returns A-2 immediately, because SKIP LOCKED ignores A-1.

6. Last line of defence (expected, not run). Insert two tickets rows with status valid for the same (event_id, seat_id): the second fails with duplicate key value violates unique constraint "one_valid_ticket_per_seat" (23505).

Common misconceptions ​

BeliefReality
Ticketing is a throughput problemIt is contention on a few rows plus a crowd at the edge; 125 row writes/s is small
A Redis lock with a TTL prevents double-sellingA TTL lock can expire under a paused holder; enforce in the database with conditional writes and a unique index
FIFO is the fair queuePure FIFO rewards the fastest client; randomise early arrivals
The sweeper is what frees expired seatsHolds expire lazily in the hold query; the sweeper only tidies up and feeds the map
Redis keyspace expired events fire at the TTLRedis docs: no guarantee of timing; events fire when the key is deleted
Pay and seat update can share a transactionThe provider is external; use a saga with compensation
Retrying a timed-out charge is unsafeIt is safe with the same provider idempotency key
ShouldBeUnique makes a job exactly-onceIt only stops duplicate dispatch; the handler must be idempotent
Realtime availability must be exactIt is a hint; the hold endpoint is the truth
Partition seats by seat id for scalePartition by event so a hold stays local
JWT HS256 is fine for QR ticketsEvery scanner would hold the signing secret; use an asymmetric signature
Resale puts the seat back on saleThe seat stays sold; the ticket changes owner and generation
The waiting room can fail openFailing open sends the crowd to the origin; fail closed with a static page

Cheat sheet ​

TopicRemember
InvariantAt most one valid ticket per (event, seat); unique index as last defence
Hold (exact seats)FOR UPDATE in seat_id order, lock_timeout 200 ms, short transaction
Hold (best available)FOR UPDATE SKIP LOCKED LIMIT n
Hold (Redis)One Lua script, PX TTL, {event} hash tag, rebuild from PostgreSQL
ExpiryDatabase clock; lazy check; sweeper in batches; one extension at checkout
ReleaseWHERE hold_id = $1 AND state = 'held': idempotent
AdmissionRandomised pre-queue, then FIFO; rate = free shopper slots
Admission tokenHMAC-SHA256 over event, visitor, position, nbf, exp; 10 min
BotsAccount per position, challenge at join, rate limit and hold limits after admission
CheckoutIdempotency-Key + fingerprint; order + outbox in one transaction
PaymentProvider key = order id + "-charge"; unknown -> query, not guess
CompensationFailed -> release seats; late -> refund or re-hold
PartitioningBy event; bulkhead the hot event; pre-warm
TicketsEd25519-signed QR, generation for transfer, revocation list, first-scan-wins
Numbers20k orders, 1,000 admits/min, 5k edge polls/s, 10k origin QPS, 50 holds/s, 17 payments/s

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is the estimate for this problem mostly about the edge and contention rather than database throughput? Must-know ​

Answer

Answer: The waiting room converts 100,000 visitors into about 1,000 admissions a minute, so the database sees about 50 holds and 125 row writes a second, which is small. The large numbers are the 5,000 polls a second and the 24 GB seat-map burst at the edge, and the hundreds of buyers aiming at the same few rows. See Estimate.

2 — Two buyers select overlapping pairs of seats. What two rules stop a deadlock and a long pile-up? Must-know ​

Answer

Answer: Lock rows in a fixed order (ORDER BY seat_id ... FOR UPDATE) so the lock graph has no cycle, and bound the wait with SET LOCAL lock_timeout so a hot row fails fast with 55P03 and becomes a 409. See Single writer.

3 — When is SKIP LOCKED the right tool and when is it wrong? Must-know ​

Answer

Answer: Right for "any N seats", the sweeper and the outbox relay, where any free row is as good as another. Wrong for exact seats the buyer chose: skipping a locked seat would silently return fewer seats instead of waiting to learn whether it became free. PostgreSQL itself says it is "not suitable for general purpose work".

4 — The sweeper has been down for ten minutes. Are expired seats unsellable? Important ​

Answer

Answer: No. Every hold query treats state = 'held' AND hold_expires_at <= now() as free (lazy expiry). Only "best available" (which filters on state = 'available') and the availability feed miss them until the sweeper runs. See Holds.

5 — Why does the design not rely on Redis keyspace notifications to release holds? Important ​

Answer

Answer: Redis generates the expired event when it deletes the key, and its docs say there are "no guarantees" the event fires when the TTL reaches zero; with many keys the delay can be significant. Notifications are also fire-and-forget pub/sub. A database deadline plus a sweeper is deterministic.

6 — A payment succeeds 20 minutes after checkout, after the hold expired and the seats were sold to someone else. What happens? Must-know ​

Answer

Answer: The confirm UPDATE ... WHERE hold_id = $1 AND hold_expires_at > now() updates 0 rows; the order moves to refund_required and a RefundPayment outbox row starts the compensation. If the seats were still free, the system could re-hold them instead. See Payment.

7 — What does the idempotency fingerprint protect against that the key alone does not? Must-know ​

Answer

Answer: A client bug that reuses a key for a different request (another hold, another amount). Without the fingerprint the server would return the old order for a new purchase. With it, the server answers 422.

8 — Why randomise the pre-queue instead of ordering by arrival? Important ​

Answer

Answer: Arrival order inside the pre-queue measures who refreshed fastest or ran a script, not who wanted tickets more. Shuffling once at the start gives everyone who arrived before the start an equal chance, and later arrivals queue FIFO behind them (Queue-it describes this; Ticketmaster explains the bot race).

9 — Why sign QR tickets with Ed25519 rather than HMAC? Important ​

Answer

Answer: Scanners verify offline. With HMAC every scanner would hold the secret that creates tickets; with Ed25519 they hold only the public key, so a stolen scanner cannot forge tickets.

10 — A ticket is resold. How does the gate reject the seller's old screenshot while offline? Important ​

Answer

Answer: The transfer bumps the ticket's generation and adds "ticket id, generations up to the old one" to the revocation list; scanners download that list before doors open and reject the old generation. See Ticket integrity.

11 — Redis is lost mid-sale in the Redis-gate variant. What breaks? Important ​

Answer

Answer: Nothing about correctness: PostgreSQL recorded every hold and sale. The inventory switches to the database path (slower), rebuilds Redis from held and sold rows with their remaining TTLs, then switches back. See Failure scenarios.

12 — Why partition seats by event rather than by seat? Must-know ​

Answer

Answer: A hold covers several seats of one event; by-event partitioning keeps it a local transaction and makes a hot event a single partition that can be isolated with its own primary, pool and waiting room (bulkhead). See Hot events.

Glossary ​

TermMeaning
TicketingSelling a fixed, numbered inventory (seats) for a dated event
Seat mapStatic geometry of a venue plus a dynamic availability layer
Seat availabilityWhich seats are free now; a bitmap snapshot plus pushed deltas
Seat hold (reservation)A seat in state held with an owner and a deadline
Hold expiryThe deadline passing; the seat becomes free lazily or via the sweeper
TTLTime to live; the hold length, or a Redis key's PX expiry
SweeperBackground job that returns expired holds to available in batches
Release seatOwner-checked, idempotent transition from held to available
Double-selling / double bookingThe same seat sold to two buyers; the invariant this design forbids
Single writerOnly one transaction decides a seat's state at a time
Row lockA lock on one table row held until the transaction ends (PostgreSQL, InnoDB)
FOR UPDATELocking clause: locks the selected rows against other writers and lockers
SKIP LOCKEDLocking option: skip rows that cannot be locked immediately
NOWAITLocking option: fail at once instead of waiting
lock_timeoutPostgreSQL setting that aborts a lock wait (SQLSTATE 55P03)
Advisory lockPostgreSQL lock with an application-defined meaning, not tied to rows
Optimistic lockingWrite only if a version column still has the value you read
Version columnInteger bumped on every change, used for compare-and-set
Redis Lua (atomic hold)A script run with EVAL that checks and sets all seat keys atomically
Hash tagThe {...} part of a Redis key that picks the cluster slot
Inventory / allocationThe service and data that decide which buyer gets which seat
Best availableAllocation of any N seats in a section, chosen by the system
General admissionUnnumbered tickets; a counter instead of seat rows
OrderA purchase attempt with a state machine (pending, paid, failed, refund)
PaymentThe external charge; may succeed, fail or be unknown
Idempotency keyClient-generated key that makes a retried request return the first result
OutboxTable written in the business transaction and published later by a relay
SagaA sequence of local transactions with compensations on failure
CompensationThe undo step of a saga: release seats, refund
Ticket issuanceCreating ticket rows and QR codes after a confirmed sale
QR code / signed ticketA ticket payload plus a signature, encoded as a QR image
HMACKeyed hash (RFC 2104); symmetric signing for one-verifier tokens
JWTJSON Web Token (RFC 7519); a signed claims format
Ed25519Asymmetric signature scheme; scanners need only the public key
Offline validationChecking a ticket at the gate without a network
RevocationMarking old ticket generations invalid after transfer, refund or resale
TransferChange of ticket owner with a generation bump
ResaleA transfer paid through the platform
EscrowThe platform holds the buyer's money until the transfer completes
Price capA rule limiting resale price, enforced in data
Check-in / scanningValidating tickets at the gate and recording entry
Virtual waiting roomEdge queue that admits visitors at the origin's capacity
QueueOrdered list of waiting visitors (pre-queue, then FIFO)
Admission tokenSigned, short-lived token proving a visitor was admitted
Flash saleVery large demand at a known start time for limited stock
FairnessEqual chance for comparable visitors; no advantage from speed or scripts
FIFOFirst in, first out admission order
Randomised admissionShuffling the visitors who arrived before the start
Bot defenceMeasures that make automated buying expensive or detectable
Rate limitingCapping requests per client per time window
Hot eventOne event with far more demand than the rest
Hot rowA row many transactions want to lock at once (the front row)
Partition by eventPlacing all seats of one event in one partition
BulkheadIsolated resources (pools, partitions) so one event cannot starve others
Pre-warmLoading caches, CDN and memory before the spike
CacheFast copy of data that may be stale (Redis, CDN)
CDNContent delivery network serving static seat maps and pages
SSEServer-Sent Events; one-way server push over HTTP
WebSocketBidirectional connection; Laravel Reverb is a WebSocket server
ReverbLaravel's first-party WebSocket server, scales over Redis pub/sub
Stream processingContinuous computation over event streams (windows, aggregates)
DashboardLive organiser view computed from the stream
Payment provider outageThe provider is down; pause admissions, extend holds
Redis lossRedis data gone; rebuild holds from PostgreSQL
Region failureThe home region is down; fenced failover to the standby
Capacity testRehearsal with synthetic buyers aimed at the same seats
p99The latency 99% of requests beat
QPSQueries (requests) per second
EstimateStep 2 back-of-the-envelope arithmetic
InterviewThe 45-minute version of this design
lockForUpdateLaravel query-builder method that adds FOR UPDATE
Cache::lockLaravel atomic lock on a cache store, with an owner token

References ​

Built by Morteza Negahi