The Problem#
A ticket booking platform such as Ticketmaster, SeatGeek, Eventbrite or BookMyShow lets people:
- discover live events (concerts, sports, theatre, comedy);
- look at an event page with a seat map;
- buy tickets for specific seats, or for general-admission capacity.
Most of the time, this is a calm, read-heavy catalogue. A few times a year it becomes one of the hardest problems in consumer software. A superstar announces a tour, and millions of people arrive at the same minute to compete for a few tens of thousands of seats in one stadium. The system must:
- never sell the same seat twice;
- stay up while a crowd many times larger than the inventory hammers a single event;
- give everyone a fair, comprehensible experience, even though most of them will leave without tickets.
Analogy. Picture a theatre box office on the morning a famous show opens bookings.
- The clerk has a seating chart on the counter, the seat map.
- When you point at seat F12, they put a paper clip on it with a note: "held for you until 10:15". Nobody else can take it while you count your cash. That is the reservation with a time-to-live (TTL).
- If you pay, they stamp the seat as sold, the booking confirmation.
- If you walk away, the clip comes off when the time is up, and the seat returns to the pool, expiry.
- When the queue outside stretches round the block, a doorman lets people in a few at a time, so the counter is never mobbed. That is the virtual waiting room.
- Posters in the window answer "what's on and when" for passers-by without bothering the clerk at all. That is cached event pages and search.
Every design choice below is a version of one of these: the clip, the stamp, the doorman and the posters.
This problem tests whether a candidate can:
- reason precisely about contention: many people wanting one item at the same time;
- choose between database-level and lock-service-level concurrency control, and explain their failure modes;
- separate the availability-first read path from the consistency-first booking path;
- design for a thundering herd with caching, admission control and real-time updates;
- integrate an external payment provider safely, with idempotency, webhooks and refunds.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| Reserved seating, general admission, or both? | Both; reserved seating is the harder case and the focus | Reserved seats need per-seat state; general admission is a counter |
| How long should a seat be held during checkout? | About 10 minutes, extendable once while payment is in flight | The hold duration drives lock TTLs and the expiry path |
| How many tickets per order? | Up to 8, typically 2 to 4 together | Multi-seat holds must be all-or-nothing |
| What is the largest single on-sale? | ~10 million interested users for one event of ~50,000 to 90,000 seats | Drives the waiting room, caching and the hot-event path |
| What is the normal read-to-write ratio? | ~100 reads per booking-related write | The catalogue and search paths need heavy caching |
| How fresh must seat availability on the map be? | A few seconds is fine; correctness is enforced at reserve time | The map can be cached and eventually consistent |
| Which payment methods? | Cards and wallets through an external processor such as Stripe | We never handle raw card data; webhooks confirm payment |
| Must search be typo-tolerant and filterable by place and date? | Yes: keyword, performer, venue, city, date range, category | A full-text search engine is justified |
| Who creates events? | Promoters and venue staff, through an admin tool (out of scope) | Ticket rows are generated from the venue's seat map at creation |
| Do we need resale, dynamic pricing or transfers? | Out of scope, mentioned as extensions | They change the inventory model, so keep them as notes |
| Is fairness a product requirement during big on-sales? | Yes: a queue with clear position and wait estimates, plus bot defences | Shapes the waiting-room design and abuse controls |
| Multi-region? | Users are global; the booking for one event can live in one home region | Avoids cross-region consensus on the hot path |
Requirements#
Functional#
- Users should be able to view an event: details, venue, performers and a seat map with current availability.
- Users should be able to search for events by keyword, performer, location, date and category.
- Users should be able to book tickets: hold seats for a few minutes, pay, and receive a confirmed booking with no double booking.
- During extreme on-sales, users should get a fair, controlled experience, through a waiting room that admits people in batches.
Out of scope:
- the "my tickets" page;
- the admin tools for creating events;
- dynamic pricing, resale and transfers;
- ticket delivery (barcodes, wallet passes) and entry scanning.
Each is discussed briefly as an extension.
Non-Functional#
- Consistency for bookings. A seat can be sold to at most one buyer, ever. This is the one property that must hold under every failure. Holds must also be exclusive: two people must not both believe they hold the same seat.
- Availability for browsing and search. Viewing and searching must stay up during the largest on-sales. Slightly stale data is acceptable there (seconds for availability, minutes for event details). In CAP terms, the read path favours availability and the booking path favours consistency (see CAP Theorem and PACELC).
- Scale.
- ~100 million monthly users.
- Up to 10 million concurrent users interested in one event.
- Event page reads in the hundreds of thousands to millions per second at the peak of an on-sale.
- Latency.
- Search under 500 ms at p99; event page under 200 ms from cache.
- A seat-hold request under 300 ms at p99, even at peak, for admitted users.
- Read-heavy. About 100:1 reads to writes in normal operation, and far higher during on-sales.
- Fairness and abuse resistance. Bots must not be able to hoard holds. Users should see an honest queue position.
- Durability. Confirmed bookings and payment records must never be lost (replicated, backed up, auditable).
The priority order is: never double-sell, then stay up, then be fast, then be fair. When they conflict, the earlier one wins. For example, if the hold service is down, the system may fail a booking at the last step rather than risk a double sale.
Capacity Estimation#
These are assumptions for a large global platform. The exact values matter less than what each number forces.
Catalogue size.
- Assume ~1 million events per year, of which ~200,000 are upcoming and searchable at any time.
- The average venue has ~2,000 seats. Clubs have hundreds, arenas ~15,000 to 20,000, stadiums 50,000 to 90,000.
- Tickets created per year ≈ 1M × 2,000 = 2 billion ticket rows.
- At ~200 bytes per row with indexes, that is roughly 400 GB per year. This fits comfortably in a sharded or even a single large relational cluster, with old events archived.
- Implication: storage is not the problem. Contention and read spikes are.
Normal traffic.
- Take 100M monthly users, ~5M daily, each doing ~20 page views or searches: about 100M reads per day, ~1,200 per second on average, with daytime peaks of ~5,000 per second.
- Bookings: if the platform sells ~500 million tickets a year in orders of ~2.5 tickets, that is 200M orders a year, about 6 orders per second on average. Hold attempts run perhaps 3 to 5 times that.
- Implication: on an ordinary day, one well-tuned relational database could handle the bookings. The design is shaped by the outliers.
The superstar on-sale.
- 10 million people want one stadium show of 60,000 seats. Demand is ~170 times supply, so 99 percent of visitors will leave without tickets. The design must make that experience orderly.
- If every visitor refreshed the event page every 5 seconds, that would be 10M / 5 = 2 million requests per second for one page.
- Implication: the event page must be served from a CDN and in-memory caches. No database can see this traffic directly.
- The seat map availability for 60,000 seats is a ~7.5 KB bitmap (1 bit per seat), or ~60 KB to 200 KB as a JSON list. Pushing 200 KB to 10M clients every few seconds would be ~400 GB/s, which is absurd. So availability must be compact, delta-encoded, and only for admitted users.
Booking throughput for a hot event.
- Selling 60,000 seats in ~15 minutes means about 70 confirmed seats per second, roughly 25 to 30 orders per second.
- Hold attempts are much higher, because many users try seats that others have just taken: perhaps 500 to 2,000 hold attempts per second for admitted users. Without a waiting room, the attempts could be 100,000+ per second.
- Implication: the waiting room's admission rate directly controls the load on the booking path. It is the single most important lever.
Waiting room.
- 10M queued users, each with a queue entry of ~100 bytes: ~1 GB in Redis. That is small.
- Position updates every ~10 to 30 seconds, for 10M connected clients, is 330k to 1M small messages per second. That needs a connection tier sized like a chat system (see Polling, Long Polling, SSE, WebSockets and Webhooks), or a static, CDN-served polling page.
Search. At ~1,000 to 5,000 searches per second normally, plus spikes when an event is announced, a small Elasticsearch cluster (a few data nodes) with caching meets the 500 ms target easily.
Holds in Redis. At any moment, at most a few hundred thousand active holds exist across all events (about 70 seats per second × 600 s of hold time × a few hot events, plus the long tail). At ~150 bytes each, that is well under 1 GB.
What these numbers tell us:
- Reads during on-sales are five orders of magnitude above bookings, so caching and CDN design matter.
- Booking contention is concentrated on one event and its hottest sections, so the hot partition must be handled deliberately.
- The waiting room is a capacity tool as much as a fairness tool.
Core Entities#
- Event: a single show at a venue on a date: name, description, category, start time, status (scheduled, on sale, sold out, cancelled), performer links, and the on-sale time.
- Venue: a physical place: address, location, capacity, and a seat map (sections, rows and seats with coordinates for rendering). It is stored once per venue layout and reused across events.
- Performer: an artist, band, team or company: name, description, links.
- Ticket: one sellable unit for one event. For reserved seating, one row per seat (section, row, number, price tier, status). For general admission, a capacity bucket with a count. Ticket rows are generated from the venue's seat map when the event is created.
- Hold (reservation): a temporary, exclusive claim by one user on one or more tickets, with an expiry time. It lives either as fields on the ticket row or as keys in a lock store (Deep Dives 1 and 2).
- Booking (order): a user's purchase of one or more tickets: user, ticket ids, total price, status (pending, confirmed, failed, refunded, cancelled), payment reference. A separate entity groups multi-ticket purchases under one payment and one status.
- Payment: the record of a payment attempt with the processor: amount, currency, processor ids, status, timestamps.
- User: the buyer, identified by the authentication system.
- Queue entry: a user's position in an event's waiting room, and their admission status.
A seat's true state at any instant combines the ticket row (available or sold) with any live hold. Much of the design is about where that combination is computed, and who owns it.
API Design#
GET /v1/events/{eventId}
-> 200 { event, venue, performers[], priceTiers[], onSaleAt, status }
# static and cacheable; seat availability comes from a separate endpoint
GET /v1/events/{eventId}/availability?since={version}
-> 200 { version, soldOrHeldBitmap | changes[], sectionsSummary[] }
# short TTL; deltas since a version keep payloads small
GET /v1/events/search?q=taylor&city=london&from=2027-06-01&to=2027-06-30
&category=concert&cursor=...&limit=20
-> 200 { results[], nextCursor }
POST /v1/events/{eventId}/queue # join the waiting room
-> 202 { queueToken, position, estimatedWaitSeconds }
GET /v1/events/{eventId}/queue/status # or an SSE stream
-> 200 { position, estimatedWaitSeconds, admitted, accessToken? }
POST /v1/events/{eventId}/holds
Headers: Authorization, X-Access-Token (from the queue), Idempotency-Key
Body: { ticketIds: [..] } | { section, quantity } # explicit or best available
-> 201 { holdId, ticketIds[], expiresAt, priceTotal }
-> 409 { unavailableTicketIds[] }
DELETE /v1/holds/{holdId} # user releases early
POST /v1/bookings
Headers: Idempotency-Key
Body: { holdId, paymentMethodToken } # token from the processor's client SDK
-> 202 { bookingId, status: "PENDING_PAYMENT", clientSecret }
GET /v1/bookings/{bookingId} # status polling or push
-> 200 { status: "PENDING_PAYMENT" | "CONFIRMED" | "FAILED" | "REFUNDED", tickets[] }
POST /v1/webhooks/payments # from the processor; signature-verifiedNotes on the API:
- The user id comes from the auth token, never from the body (see Authentication and Authorization).
- Reserve and pay are separate calls. The simplest API, one
POST /bookingscarrying seats and payment, works as a starting point. But it means a user can type in their card details and only then learn the seat is gone. Splitting hold from pay is the main UX fix of this design (Deep Dive 1). - Idempotency keys on holds and bookings make client retries safe. A retried hold returns the same hold, and a retried booking returns the same booking instead of charging twice (see Idempotency and Safe Retries).
- Static and dynamic data are split. Event details are cacheable for minutes at the CDN. Availability is a separate, compact, short-lived resource.
- The access token proves the user was admitted from the waiting room. The hold endpoint rejects requests without a valid one, for events in queue mode.
- The payment token comes from the processor's client SDK. Card numbers never touch our servers, which keeps us largely out of PCI DSS scope (see Security Fundamentals for System Design).
- Search uses cursor pagination for stable paging. Offset paging is acceptable for the first few pages, but cursors avoid deep-offset costs.
High-Level Design#
We build the design one requirement at a time, starting with the simplest thing that works and adding components only when a requirement forces them.
1) Users can view an event#
A user opens /event/123 and expects the name, date, venue, performers and a seat map showing what is still available.
Simplest version. A client calls an API Gateway, which routes to an Event Service. The Event Service reads the event, venue and performer rows from an Events DB (PostgreSQL) and returns them.
- The API Gateway handles TLS termination, authentication, rate limiting and routing (see API Gateway and Backend-for-Frontend).
- The Event Service is stateless, so it scales horizontally behind a load balancer.
Even at this stage we separate the static parts of the page from the dynamic part:
- Static: event details, venue layout and the seat map geometry. These change rarely, so they are cached aggressively at the CDN and in Redis.
- Dynamic: which seats are free right now. This is served by a separate availability endpoint with a short TTL (Deep Dive 5).
The seat map geometry belongs to the venue: section shapes, row labels and seat coordinates. The client draws it once, then colours seats using the availability data. This keeps the frequently changing part small.
Why a relational database? Events, venues, performers, tickets and bookings are highly related, and the booking path needs ACID transactions. PostgreSQL (or MySQL) fits well. DynamoDB with conditional writes and transactions would also work. What matters is atomic, isolated updates to ticket state (see Relational Databases and SQL and PostgreSQL in Practice).
2) Users can search for events#
Users search by any mix of keyword, performer, place, date and category.
Simplest version. A Search Service turns the query into SQL against the Events DB:
-- correct but slow: the leading wildcard defeats a B-tree index
SELECT id, name, starts_at, venue_id
FROM events
WHERE (name ILIKE '%taylor%' OR description ILIKE '%taylor%')
AND starts_at BETWEEN '2027-06-01' AND '2027-06-30'
ORDER BY starts_at
LIMIT 20;This works for a demo. With a leading %, though, the database cannot use an ordinary index on name, so it scans every row. That is fine at 10,000 events and hopeless at hundreds of thousands under load. It also cannot handle typos ("tayler swfit") or relevance ranking. Deep Dive 7 fixes this with a full-text index, and then with Elasticsearch fed by change data capture.
Note the shape: the database remains the source of truth. The search index is a derived, read-optimised copy, kept up to date asynchronously, typically seconds behind. Search favours availability and speed over perfect freshness, which matches the requirements.
3) Users can book tickets with no double booking#
This is the heart of the problem: two users must never pay for the same seat.
Simplest version. Add Tickets and Bookings tables, and a Booking Service. When a user submits seats and payment, the Booking Service runs one short transaction:
BEGIN;
-- only succeeds for seats still available; the row lock serialises racers
UPDATE tickets
SET status = 'BOOKED', booking_id = :booking_id
WHERE event_id = :event_id
AND id = ANY(:ticket_ids)
AND status = 'AVAILABLE';
-- application checks: rows updated == number requested, else ROLLBACK
INSERT INTO bookings (id, user_id, event_id, status, total_cents)
VALUES (:booking_id, :user_id, :event_id, 'CONFIRMED', :total);
COMMIT;The AND status = 'AVAILABLE' condition does the concurrency work. If two transactions race for the same seat:
- The first takes the row lock and flips the status.
- The second waits for the lock. Under PostgreSQL's default Read Committed isolation, it then re-checks the condition on the new row version, finds
BOOKED, and updates zero rows. - The application sees "fewer rows updated than requested" and rolls back.
No double booking is possible (see Concurrency Control and Database Locking).
Payment goes through an external processor such as Stripe. The client tokenises the card with the processor's SDK, our server creates a payment, and the processor confirms it, often asynchronously, through a webhook.
What is wrong with this first version? The user fills in a payment form for several minutes, and only at submission discovers that someone else took the seat. That is a terrible experience at popular events. It is also wasteful: people pay with no guarantee of a seat. The fix is a hold, a short exclusive reservation taken when the seat is selected, before payment. Deep Dives 1 and 2 cover how to implement it: status columns, conditional updates, or a distributed lock with a TTL.
A note on shared databases. The Event, Search and Booking services share one Events DB here. "One database per service" is a guideline, not a law. Tickets, bookings and events are tightly coupled. Booking needs ACID transactions across tickets and bookings. Splitting the data into separate databases would add distributed transactions for no benefit. State the trade-off and decide; don't recite dogma.
4) Fair, controlled access during extreme on-sales#
For a normal event, admitted users simply browse and book. For a superstar on-sale, 10 million people would otherwise hit the seat map and the booking path at once. Seats would vanish faster than anyone could click. The databases would melt, and the experience would be chaos.
We add a Waiting Room Service in front of the booking experience for events an operator flags as high-demand:
- Users join a queue before they can see the seat map.
- The service admits users in batches, at a rate the booking path can sustain.
- Each admitted user receives a short-lived access token, which the Booking Service checks.
- Queued users see their position and estimated wait over SSE, or via cheap polling of a CDN-friendly endpoint.
The full high-level design#
Putting everything together:
- The CDN absorbs the read storm for static content.
- The Event and Search services serve the catalogue from caches and Elasticsearch.
- The Waiting Room controls admission.
- The Booking Service takes holds in Redis and commits bookings in PostgreSQL.
- Payments flow through Stripe, with webhooks.
- An availability publisher pushes seat changes to admitted clients.
Components:
- CDN: serves event pages, venue seat-map geometry, images and scripts from edge locations. During on-sales it absorbs the bulk of all requests (see Content Delivery Networks (CDN)).
- API Gateway: authentication, per-user and per-IP rate limits, bot-score checks, and routing (see Rate Limiting and Throttling).
- Event Service: returns event, venue and performer details using a read-through Redis cache in front of PostgreSQL read replicas.
- Availability Service: maintains a compact per-event availability bitmap with a version number. It serves full snapshots and deltas, from Redis.
- Search Service and Elasticsearch: full-text, fuzzy, filtered search over events, fed by change data capture. Frequent queries are cached.
- Waiting Room Service: queues users per event in Redis sorted sets, admits them at a controlled rate, and issues signed, short-lived access tokens.
- SSE push tier: long-lived connections that push queue positions to waiting users and seat changes to admitted users (see Pattern: Pushing Realtime Updates).
- Booking Service: validates access tokens, takes holds (Redis locks with TTL, or conditional updates in the DB), creates pending bookings, starts payments, and finalises bookings.
- Hold store (Redis):
SET ticket:{id} holdId NX EX 600-style keys, plus a per-event sorted set of hold expiries that feeds the seat map. - Events DB (PostgreSQL): the source of truth for events, tickets and bookings. Writes for one event go to one primary; read replicas serve catalogue reads.
- Payment processor and webhook handler: Stripe tokenises cards client-side, processes the payment, and calls our idempotent webhook to confirm or fail the booking.
- CDC and Kafka: stream committed changes to update Elasticsearch, invalidate caches and update availability (see Change Data Capture and the Outbox Pattern).
Key Flows#
Flow 1: Select seats and take a hold#
- The client sends the chosen ticket ids, the waiting-room access token (if the event is in queue mode) and an idempotency key.
- The Booking Service checks the token's signature, event id, user id and expiry.
- A Lua script tries to create all the hold keys atomically. If any seat is taken, it creates none of them, so a user never ends up holding a partial set they did not ask for (Deep Dive 2).
- A pending booking row records who holds what, and when the hold expires. This gives the hold a durable trail, and lets the payment step find it.
- The seat map's "reserved" sorted set is updated so other users see the seats as unavailable within seconds.
The DB check that the seats are not already sold can happen inside the script's caller: read the ticket rows first, or rely on the final conditional update at confirmation time. Both are covered in Deep Dive 3.
Flow 2: Pay and confirm#
- Card details go directly to the processor from the client. Our servers only see a token, which keeps the platform largely out of PCI DSS card-data scope.
- Before charging, the Booking Service confirms the hold still belongs to this booking, and extends it to cover payment time (Deep Dive 1).
- The PaymentIntent carries the
bookingIdin its metadata and uses an idempotency key, so a retried request never creates a second charge. - The webhook is the authority for "payment succeeded". The handler is idempotent: if the booking is already
CONFIRMED, it returns 200 without changes. - The final transaction flips tickets to
SOLDonly if they are still unsold, and marks the bookingCONFIRMED. This is the last line of defence against double booking, even if the hold store failed (Deep Dive 3).
Flow 3: Join the waiting room and get admitted#
- Joining is a single
ZADD ... NXkeyed by user: re-joining does not move a user back, and does not duplicate them. - Positions are computed with
ZRANK. Wait estimates use the measured admission rate (Deep Dive 6). - The admission worker pops a batch sized to what the booking path can absorb, adjusted by feedback such as hold latency and seats remaining.
- The access token is signed (for example a JWT with event id, user id and a 10 to 15 minute expiry). Every booking-path instance can verify it locally, without a Redis round trip.
Data Model#
Users live in the identity system and are referenced by user_id. The venue's seat-map geometry is a versioned JSON document in object storage, and performers link to events through an event_performers join table.
The core tables in SQL:
CREATE TABLE tickets (
id BIGINT PRIMARY KEY,
event_id BIGINT NOT NULL REFERENCES events(id),
section TEXT NOT NULL,
row_label TEXT NOT NULL,
seat_number TEXT NOT NULL,
price_cents INT NOT NULL,
status TEXT NOT NULL DEFAULT 'AVAILABLE', -- AVAILABLE | RESERVED | SOLD
hold_expires_at TIMESTAMPTZ, -- used only in the DB-hold variant
booking_id UUID,
version INT NOT NULL DEFAULT 0, -- for optimistic concurrency
UNIQUE (event_id, section, row_label, seat_number)
);
CREATE INDEX tickets_event_status ON tickets (event_id, status, section);
CREATE TABLE bookings (
id UUID PRIMARY KEY,
user_id BIGINT NOT NULL,
event_id BIGINT NOT NULL,
status TEXT NOT NULL, -- PENDING_PAYMENT | CONFIRMED | FAILED | EXPIRED | REFUNDED
total_cents INT NOT NULL,
hold_expires_at TIMESTAMPTZ,
idempotency_key TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (user_id, idempotency_key)
);
CREATE INDEX bookings_user ON bookings (user_id, created_at DESC);Why these choices:
- Relational, ACID storage for tickets and bookings, because the booking transaction must update several rows atomically and in isolation. PostgreSQL is a good default. See Choosing a Database: A Decision Guide.
- One row per seat for reserved seating. A 60,000-seat stadium becomes 60,000 rows, which PostgreSQL handles easily. It makes per-seat locking and status updates natural. General admission uses a counter row per price tier instead:
capacityandsold, decremented with a conditional update (Deep Dive 10). UNIQUE (event_id, section, row_label, seat_number)makes it impossible to create two tickets for one physical seat, even through a buggy admin import.booking_idon tickets links seats to the order that bought them. A sold ticket must have exactly one booking.versionsupports optimistic concurrency control if we choose it over row locks:UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?(Deep Dive 3).UNIQUE (user_id, idempotency_key)on bookings turns a retried "create booking" into a harmless conflict that returns the existing booking.- The index on
(event_id, status, section)makes "how many seats are left in section 104" and "pick the best available seats" fast, without scanning the whole event.
Partitioning. All tickets and bookings for an event share an event_id. That is the natural shard key:
- One event's booking transactions never cross shards.
- Different events spread across shards.
- The catch is that one hot event lives on one shard, so its write throughput is bounded by one primary. With the waiting room capping admissions, that is usually enough: hundreds of orders per second is well within one PostgreSQL primary (Deep Dive 11).
Where each kind of data lives:
| Data | Store | Why |
|---|---|---|
| Events, venues, performers | PostgreSQL (plus read replicas), cached in Redis and at the CDN | Relational, rarely changing, read-heavy |
| Tickets and bookings | PostgreSQL, sharded by event id | ACID transactions, row-level concurrency control |
| Seat holds | Redis (SET NX EX) or columns on the ticket row | Automatic expiry, fast, exclusive |
| Availability bitmap and deltas | Redis, pushed via SSE and cached briefly at the CDN | Compact, fast, derived from tickets and holds |
| Search index | Elasticsearch, fed by CDC through Kafka | Full-text, fuzzy, geo and date filters |
| Waiting-room queues | Redis sorted sets per event | Ordered, atomic pops, millions of entries |
| Payments | PostgreSQL (our records) plus the processor (Stripe) | Audit trail plus external authority |
| Seat-map geometry | Object storage plus CDN (JSON or SVG per venue layout) | Large, static, shared across events |
Deep Dives#
1. How do we reserve seats so users don't lose them during checkout?#
The first design checks availability only when the user pays. Someone can spend five minutes on the payment form and then learn that a faster typist got the seat. Every serious ticketing, airline and hotel site solves this the same way: when you select seats, they are held for you for a fixed time, shown by a countdown timer. We need three behaviours:
- Exclusive: while I hold seat F12, nobody else can hold or buy it.
- Released on abandonment: if I wander off, the seat returns to the pool when the time is up, without anyone having to clean up.
- Converted on purchase: if I pay in time, the hold becomes a sale.
Bad: a long-running database lock
How it works. When the user selects a seat, open a transaction and lock the row:
BEGIN;
SELECT * FROM tickets WHERE id = 42 FOR UPDATE; -- row lock held...
-- ...while the user fills in the payment form for up to 10 minutes...
UPDATE tickets SET status = 'SOLD', booking_id = :b WHERE id = 42;
COMMIT;Other transactions that try to lock row 42 block until this one commits or rolls back. This is sometimes called an interactive transaction: one that stays open across user think-time.
Why it fails:
- Database locks are designed for milliseconds, not minutes. Each open transaction pins a connection, and an application server or a pooler such as PgBouncer typically has hundreds of connections, not hundreds of thousands. Ten thousand concurrent checkouts would need ten thousand open transactions.
- Long transactions hurt the whole database. In PostgreSQL, a long-open transaction prevents vacuum from cleaning up dead row versions created after it started. Tables bloat and queries slow down for everyone.
- Waiters block instead of failing fast. A second user who clicks the same seat hangs until the first transaction ends.
lock_timeoutorNOWAITcan turn the wait into an error, but then each user flow needs custom handling. - Cleanup on crashes is fragile. If the app server dies, the connection drops and the lock is released, which is good. But if the connection stays alive and the user simply leaves, the lock persists until a session timeout fires. That logic lives in the application and is easy to get wrong.
- It couples the UX timer to database internals. "Your hold expires in 9:41" has to be enforced by something, and a database lock has no notion of expiry.
Verdict: never hold database locks across user think-time. Use locks only inside short transactions.
Good: a status column, an expiry time and a cron sweeper
How it works. Add an explicit RESERVED state and an expiry timestamp to the ticket row:
- AVAILABLE → RESERVED: a short transaction sets
status = 'RESERVED',hold_expires_at = now() + 10 min, and records the holder. - RESERVED → SOLD: on payment, another short transaction.
- RESERVED → AVAILABLE: a cron job runs every minute and releases holds whose expiry has passed:
UPDATE tickets
SET status = 'AVAILABLE', hold_expires_at = NULL, booking_id = NULL
WHERE status = 'RESERVED' AND hold_expires_at < now();Why it is better: every transaction is short. The hold is visible in the database, so the seat map can read it. The state machine is explicit and auditable.
Why it is not great:
- Release lag. With a one-minute cron, an expired seat stays unavailable for up to a minute after the timer hits zero. For a hot on-sale, that is a meaningful slice of inventory held hostage: at 70 seats per second of sales, a minute of lag is thousands of seat-minutes.
- The cron is now on the critical path. If it fails, stalls or falls behind, holds never expire. Seats appear taken forever, and sales stop. A background job whose failure halts the business is a liability.
- Sweep cost. A periodic
UPDATEacross many rows competes with booking traffic on the hot shard, unless it is batched and indexed carefully.
This is the bar for a mid-level answer, because it does solve the problem correctly.
Great: implicit expiry (a conditional update that treats expired holds as free)
The insight. A ticket is available if its status is AVAILABLE, or if it is RESERVED and the hold has expired. We do not need anyone to flip expired holds back. Every reader and writer can simply interpret an expired hold as free.
-- Take a hold: succeeds if free, or if the previous hold has expired
UPDATE tickets
SET status = 'RESERVED',
booking_id = :booking_id,
hold_expires_at = now() + interval '10 minutes'
WHERE event_id = :event_id
AND id = ANY(:ticket_ids)
AND (status = 'AVAILABLE'
OR (status = 'RESERVED' AND hold_expires_at < now()));
-- rows updated must equal the number requested, else ROLLBACKWhy it is great:
- Holds expire exactly on time, with no background job on the critical path.
- It uses only the database we already need, with short transactions and one round trip.
- Atomicity is free: a multi-seat hold is one statement in one transaction, so it takes all the seats or none.
- Correctness is easy to argue: the row lock that
UPDATEtakes serialises racers, and theWHEREclause is re-checked on the latest row version.
Its costs:
- Reads must apply the same rule. The seat map query becomes
status = 'SOLD' OR (status = 'RESERVED' AND hold_expires_at > now())to count a seat as unavailable. A compound index on(event_id, status, hold_expires_at)keeps it fast, or a materialised availability structure can be maintained (Deep Dive 5). - The table is less legible to analysts and other consumers, because some rows marked
RESERVEDare really free. A lazy sweeper can still reset expired rows for tidiness. The difference from the cron design is that the system stays correct even if the sweeper is late or dead. - The hot rows see more writes. Every hold attempt is a write on the primary for that event. With waiting-room admission control, this is acceptable (Deep Dive 11).
Great: a distributed lock with a TTL (Redis)
How it works. Keep the ticket table to two durable states, AVAILABLE and SOLD, and move the temporary hold into Redis, which has built-in key expiry:
SET hold:ticket:42 <holdId> NX EX 600NXmeans "only set if the key does not exist", so exactly one client wins. The command is atomic.EX 600sets a 10-minute TTL, so Redis deletes the key automatically when the hold lapses.- The value is the hold id, tied to the user's pending booking. At confirmation we check that the hold still belongs to this booking, not just that a hold exists.
- To release early (the user cancels, or payment completes), delete the key, but only if its value is still our hold id. Use a compare-and-delete Lua script, never a blind
DEL, which might delete someone else's newer hold.
Why one might add Redis when PostgreSQL is already consistent: PostgreSQL has no row-level TTL. Expiry needs either a sweeper or the implicit-expiry predicate. Redis offers expiry natively, and its in-memory, single-threaded execution makes acquiring and releasing tens of thousands of locks per second cheap. It also takes the per-click hold traffic off the database primary. Only the much rarer purchase reaches PostgreSQL.
Its challenges:
- The seat map must learn about holds. Holds no longer live in the database, so the availability view must read Redis as well. A plain Redis set of held ticket ids does not work: set members do not expire when the lock keys do, so abandoned holds would leave ghost entries showing seats as taken forever. Instead, keep a sorted set scored by hold expiry:
ZADD event:123:held <expiresAtMs> 42. Readers count only members with a score in the future (ZRANGEBYSCORE event:123:held <nowMs> +inf), and anyone touching the set trims dead members withZREMRANGEBYSCORE event:123:held -inf <nowMs>. Expired holds then vanish from the map on their own. The alternative is to write a "reserved" marker to the database too, treating Redis as the authority for expiry and sweeping stale DB markers lazily. - Redis can fail. If the hold store is down, users cannot take holds. They can still be allowed to try buying directly, and the final database transaction still prevents double booking, because it only sells unsold seats. The degraded experience, "sorry, someone beat you to it" after payment entry, is better than the cron failure mode, where every seat looks taken.
- The TTL can expire during payment. If user A's hold expires at minute 10 but their payment completes at minute 11, user B may have taken the seat in between. The final transaction lets only one of them win. The loser's payment must then be refunded automatically. Reduce how often this happens by extending the hold when payment starts. A 10-minute timer for form filling, plus a few minutes of grace once payment is in flight, usually suffices.
Which great option to choose? Both are correct. The trade-offs are the subject of Deep Dive 2, and the database guard that makes either safe is Deep Dive 3.
The ticket lifecycle is the same whichever implementation is chosen. What differs is where each state lives: in the row, in Redis, or split between them.
2. Distributed lock or status column: which should hold the seat?#
This is the question interviewers most like to probe, because each answer has a respectable defence. It helps to separate two roles:
- The hold: a soft, temporary, exclusive claim that makes the UX pleasant.
- The sale: the hard invariant that a seat is sold at most once.
The sale must always be enforced by the database. The hold can live in either place.
Option A: the hold lives in the ticket row (implicit-expiry status column).
- One source of truth. The seat's full state is in one row. A booking is just a state transition on that row. There is no dual-write problem, and nothing to reconcile.
- Atomic multi-seat holds come free with one SQL statement.
- Fewer moving parts: no lock service to run, monitor and fail over.
- Cost: every seat click is a write on the event's primary. Each write takes a row lock, writes WAL (the write-ahead log), and creates a new row version that vacuum must later clean. Under extreme concurrency, the hot rows (front sections) see repeated contention.
Option B: the hold lives in Redis (TTL lock), the sale in the database.
- Native expiry at millisecond precision, with no predicate gymnastics.
- Cheap, fast holds: tens of thousands of
SET NXoperations per second per shard, on memory, without touching the database primary. - Protects the database: only confirmed purchases reach PostgreSQL. That is roughly one write per order, rather than one per click.
- Cost: two systems hold parts of the truth, so there are new failure modes:
- Redis fails over and loses a recent hold (asynchronous replication).
- A process pauses (a GC pause or VM stall) past its TTL and then acts as if it still holds the lock.
- The seat map needs both sources.
The "two holders" problem, and why the database guard saves us. Consider this sequence:
- User A acquires
hold:ticket:42. - A's request handler stalls for 11 minutes: a long GC pause, a stuck payment call, a paused VM.
- The TTL expires, and user B acquires the hold and starts paying.
- A's handler wakes up, still believing it holds the seat, and tries to finalise.
A lock with a TTL is really a lease: it is only valid until it expires, and a paused process cannot know time has passed. Martin Kleppmann's 2016 analysis of Redis-based locking ("How to do distributed locking") made this point. It is why a lease used for correctness needs a fencing token: a number that increases with every acquisition, which the protected resource checks so it can reject stale holders.
In our design, the protected resource is the ticket row. The final transaction is the fence:
-- Finalise: only if the seat is still unsold (and, with OCC, unchanged)
UPDATE tickets SET status = 'SOLD', booking_id = :booking_id, version = version + 1
WHERE id = :ticket_id AND status = 'AVAILABLE';
-- 0 rows -> someone else bought it: fail this booking and refund the paymentWhatever Redis believes, at most one of A and B can flip the row from AVAILABLE to SOLD. Redis is an efficiency lock: it makes conflicts rare and the UX smooth. The database is the correctness lock: it makes double booking impossible. That distinction lets us use a single Redis primary with replicas. There is no need for multi-node Redlock with clock assumptions, because occasionally losing a hold costs only a rare, refundable conflict, never a double sale (see Distributed Locks).
Multi-seat holds in Redis. A family wants seats 41, 42 and 43 together. Taking the locks one by one risks this: you get 41 and 42, then 43 fails, and you must undo. Meanwhile, others saw 41 and 42 taken for a moment. Better: a Lua script that checks all the keys and sets all of them, or none, in one atomic step:
-- KEYS = hold keys for each seat; ARGV[1] = holdId, ARGV[2] = ttl seconds
for i, k in ipairs(KEYS) do
if redis.call('EXISTS', k) == 1 then
return {0, k} -- conflict: report the first taken seat
end
end
for i, k in ipairs(KEYS) do
redis.call('SET', k, ARGV[1], 'EX', ARGV[2])
end
return {1}Redis Cluster runs a script only if all its keys are in the same hash slot. Use a hash tag per event, such as hold:{evt123}:ticket:42, so one event's holds co-locate on one shard. That shard then carries all the hold traffic for a hot event. At thousands of operations per second, that is fine: one Redis shard handles on the order of 100,000 simple operations per second.
Comparison:
| Aspect | Status column with implicit expiry | Redis TTL lock plus DB guard |
|---|---|---|
| Source of truth for holds | The database row | Redis (holds), database (sales) |
| Expiry | Implicit in the predicate; optional lazy sweep | Native key TTL |
| Load on DB primary | One write per hold attempt plus one per sale | One write per sale (plus a pending-booking row) |
| Multi-seat atomicity | One SQL statement | Lua script in one hash slot |
| Failure of the hold mechanism | Rides on DB availability | Redis down: fall back to buy-direct with the DB guard |
| Seat-map read | One indexed query | DB sold state plus the Redis held sorted set |
| Operational complexity | Lower | Higher (another stateful system) |
| Best fit | Moderate contention, smaller teams, strict audit needs | Extreme contention, very hot events, waiting rooms |
A sensible recommendation. Start with the status column with implicit expiry: it is simpler, with one source of truth. Move holds to Redis when the click rate on hot events makes the primary's write load or row contention a bottleneck. In either case, keep the conditional final update in the database as the unbreakable guard. Saying exactly that in an interview signals senior-level judgement.
3. How does the database guarantee no double booking?#
Whichever hold mechanism we choose, the database must make a double sale impossible. There are several tools, and an advanced candidate should know how each behaves.
Atomic conditional update (recommended). The UPDATE ... WHERE status = 'AVAILABLE' pattern is a compare-and-set in SQL:
- In PostgreSQL under Read Committed (the default), a concurrent second updater waits for the first's row lock. When the first commits, PostgreSQL re-evaluates the
WHEREclause against the new row version (the "EvalPlanQual" re-check), finds it no longer matches, and skips the row. - The application compares "rows updated" with "seats requested", and rolls back on a mismatch.
- It is one round trip, holds the lock for only milliseconds, and is easy to reason about.
Pessimistic locking, briefly. Sometimes you must read before deciding, for example to check a per-user ticket limit. Then lock briefly, inside a short transaction:
BEGIN;
SELECT id, status FROM tickets
WHERE event_id = :e AND id = ANY(:ids)
ORDER BY id -- consistent lock order prevents deadlocks
FOR UPDATE;
-- check all are AVAILABLE and the user's limit; then UPDATE ...; COMMITLock ordering matters. If user A locks seats 41 then 42, and user B locks 42 then 41, each waits for the other: a deadlock. PostgreSQL detects it after deadlock_timeout (1 second by default) and aborts one transaction. Always lock in a canonical order, such as ascending id, so cycles cannot form.
FOR UPDATE SKIP LOCKED for "best available". When the user asks for "2 seats, best available, section 104", we do not care which two free seats we get. We only want to avoid queueing behind other buyers:
SELECT id FROM tickets
WHERE event_id = :e AND section = '104' AND status = 'AVAILABLE'
ORDER BY row_rank, seat_rank
LIMIT 2
FOR UPDATE SKIP LOCKED; -- skip rows other transactions are locking right nowConcurrent buyers each grab different free seats, without blocking each other. This is the same technique job queues use to hand out work (see Pattern: Dealing with Contention). Contiguous seats need extra care, covered in Deep Dive 10.
Optimistic concurrency control (OCC). Read the row with its version. Later, update with WHERE id = ? AND version = ?. If someone else changed it, zero rows update and you retry or fail. OCC avoids holding locks while doing other work, and it suits low-contention rows. For the hottest seats in an on-sale, OCC degenerates into many failed attempts, but each failure is cheap and fast, which is acceptable when users are retrying anyway.
Stronger isolation levels.
- Under Repeatable Read, PostgreSQL aborts the second writer with a serialisation error instead of re-checking.
- Under Serializable (SSI, Serializable Snapshot Isolation, introduced in PostgreSQL 9.1 based on Cahill, Röhm and Fekete's 2008 SIGMOD paper), the database detects dangerous read/write patterns and aborts one transaction.
Both are correct, but they push retries onto the application. For a single-row compare-and-set, Read Committed plus the conditional WHERE is the cheapest correct choice. Serializable earns its keep for multi-row invariants that span rows no single statement touches, such as "no more than 8 tickets per user per event across all orders".
Constraints as a backstop. Database constraints are enforced even if application code is buggy:
UNIQUE (event_id, seat)on tickets.- A partial unique index, such as
CREATE UNIQUE INDEX ON booking_items (ticket_id) WHERE active, guarantees that no ticket appears in two active bookings, even if some code path forgets the conditional update. - PostgreSQL exclusion constraints can prevent overlapping time ranges. They are not needed for seats, but they are the same idea in hotel booking (see the hotel-booking problem).
Idempotent finalisation. The webhook can be delivered more than once, so finalisation must be idempotent:
BEGIN;
UPDATE bookings SET status = 'CONFIRMED'
WHERE id = :b AND status = 'PENDING_PAYMENT'; -- 0 rows if already done
UPDATE tickets SET status = 'SOLD', booking_id = :b
WHERE id = ANY(:ids) AND (status = 'AVAILABLE' OR booking_id = :b);
COMMIT;The second statement accepts rows already sold to this booking, so a replay is a no-op. It rejects rows sold to anyone else, which triggers the refund path.
4. How do we serve event pages to millions of users at once?#
When a superstar's tickets go on sale, millions of people sit on the event page and press refresh. The read path must stay available and fast, while the database sees only a trickle. The tools are caching at several layers, stateless horizontal scaling, and load balancing, applied with an understanding of which data changes how often.
Classify the data by volatility:
| Data | Changes | Cache where | TTL / invalidation |
|---|---|---|---|
| Venue, seat map geometry, performer bios, images | Rarely (days to never) | CDN, browser, Redis | Hours to days, plus versioned URLs |
| Event details: name, date, lineup, prices | Occasionally (an announcement, a lineup change) | CDN and Redis | Minutes, plus invalidation on change |
| On-sale status (not yet / on sale / sold out) | A few times per event | CDN with a short TTL | 5 to 30 seconds, plus purge on change |
| Seat availability | Constantly during an on-sale | Redis bitmap; CDN micro-cache for anonymous views | 1 to 5 seconds, or pushed deltas |
| Hold and booking state for a user | Per request | Not cached | Always from the source |
Layer 1: the CDN. The event page shell, scripts, images and the seat map geometry (a JSON or SVG file per venue layout, often hundreds of KB) are immutable per version. Serve them with long cache lifetimes and versioned URLs, for example /venues/88/seatmap.v14.json. A change publishes a new URL instead of purging an old one, which avoids stale-cache races. The event details API response can be cached at the edge for 30 to 60 seconds with stale-while-revalidate. The CDN then serves a slightly stale copy instantly while refreshing in the background. Millions of refreshes per second become a few origin requests per second per edge location.
Request collapsing. When a cached object expires, an edge that receives 10,000 simultaneous requests for it should send one request to the origin and serve the rest from that response. Most CDNs support this (often called request coalescing or collapsed forwarding). Without it, every expiry is a mini-stampede on the origin.
Layer 2: the application cache (Redis or Memcached). Behind the CDN, the Event Service uses a read-through or cache-aside cache keyed by event:{id}. On a miss, it loads from a read replica and populates the cache. On a hot key, one Redis shard may receive the requests of every Event Service instance. Two defences:
- a small in-process cache in each instance with a TTL of a second or two, which cuts the shard's load by the number of instances;
- replicating the hot key to several shards under suffixed names (
event:123#0toevent:123#7), each instance reading a random one.
See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
Invalidation. When an organiser edits an event, the change must reach users in seconds to minutes:
- Change data capture from PostgreSQL publishes a change event to Kafka.
- A consumer deletes
event:{id}from Redis and purges the event's API URL at the CDN (most CDNs offer purge-by-URL or purge-by-tag APIs). - TTLs act as a safety net, so that even a missed invalidation heals itself.
Database triggers that notify the cache are an older alternative. CDC is preferred, because it decouples the database from cache logic, and because it captures every committed change, including ones made by scripts and migrations (see Cache Eviction and Invalidation).
Stampede protection at origin. If a popular key expires, many instances may miss at once and all query the database. Options:
- a single-flight lock, so one loader fetches while the others wait for its result;
- probabilistic early expiration, where each reader refreshes slightly before expiry with a probability that rises as expiry approaches (the "XFetch" approach of Vattani, Chierichetti and Lowenstein, VLDB 2015);
- simply never expiring hot event objects, refreshing them proactively on change events instead.
Horizontal scaling. The Event Service is stateless, so instances scale out behind a load balancer using round robin or least-connections. Autoscaling reacts too slowly for a spike that arrives in seconds. For scheduled on-sales, pre-scale the read tier, the push tier and the caches before the on-sale time, and load-test at the expected peak (see Load Balancing and Capacity Planning and Load Testing).
Graceful degradation. If the origin is overwhelmed, the CDN can keep serving stale event pages (stale-if-error) rather than errors. Shed non-essential widgets ("you might also like", reviews) first. Keep the read path available even when the booking path is saturated.
Worked example. 5 million users refresh an event page every 10 seconds: 500,000 requests per second.
- The CDN serves 99.9 percent of them from the edge. Request collapsing and a 30-second TTL mean each of ~200 edge locations sends about one request per 30 seconds to origin. That is only ~7 origin requests per second for the page shell.
- Availability is a different story. It is fetched by admitted users only, as small deltas (Deep Dive 5), so its load is bounded by the waiting room's admission rate rather than by the crowd.
This is the scaling-reads pattern in its purest form (see Pattern: Scaling Reads and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind).
How to introduce caching in the interview. Name the bottleneck with numbers ("2 million page views per second against a database that serves perhaps 20,000 simple reads per second per replica"). Say what you cache and with what key. Choose the pattern (read-through at the app, CDN at the edge). Pick eviction (LRU plus TTL). Address the downsides, especially stampedes and invalidation. Don't recite every cache problem; pick the one or two that matter here: the hot event key and the expiry stampede.
5. How do we keep the seat map fresh without melting the system?#
A static seat map goes stale in seconds during an on-sale. Users click a seat that looks free, get "already taken", click another, and get the same again. We want the map to be nearly live, but cheap.
Represent availability compactly. For each event, maintain an availability bitmap: one bit per seat, in a fixed seat order defined by the venue layout. A 60,000-seat stadium needs 60,000 bits, about 7.5 KB, and under 2 KB compressed when most seats are in long runs of 0s or 1s. Store it in Redis as a string, and use SETBIT and GETBIT to flip seats. Alongside it keep:
- a version number, incremented on every change;
- a short change log of the last few thousand changes,
(version, seatIndex, newState).
A client that knows version 1,200 can ask for "changes since 1,200" and receive a few hundred bytes instead of the full map. Section-level summaries (seats left per section and price tier) are computed from the bitmap, and let the map show "Section 104: 12 left" without per-seat detail.
How the bitmap is updated. Every hold, release, expiry and sale changes a seat's state:
- Redis holds: the Booking Service updates the bitmap in the same Lua script that takes or releases the hold, so they cannot diverge.
- TTL expiries happen silently in Redis. The availability service learns of them either from Redis keyspace notifications (best-effort, not guaranteed delivery) or by periodically comparing the held sorted set against the clock. The sorted-set approach is more reliable.
- Sales, committed in PostgreSQL, arrive via CDC, so the bitmap converges to the durable truth even if a direct update was lost.
Because the bitmap is advisory, small errors only cause a few extra "already taken" responses, never a double booking.
Options for delivering updates:
- Basic: client polling. Each admitted client polls
availability?since=vevery 2 to 5 seconds. It is simple, stateless and CDN-friendly: anonymous viewers can share a 1-second micro-cached response. With 50,000 admitted users polling every 3 seconds, that is ~17,000 requests per second against Redis-backed endpoints. That is manageable, but there are delays of up to the poll interval, and much of the work is wasted on "no change" responses. - Better: Server-Sent Events (SSE). Admitted clients hold an SSE connection, and the server pushes deltas as they happen. SSE is one-directional (server to client) over plain HTTP, reconnects automatically, and resumes with
Last-Event-ID, which maps naturally to our version number. It fits a one-way feed of seat changes well. A push tier subscribes to the event's change channel (Redis Pub/Sub or a Kafka topic) and fans out to its connected clients. Coalesce updates into batches every 250 to 500 ms, so a burst of 1,000 changes is one message, not 1,000. - WebSockets work too. They are needed only if the client must send frequent messages on the same channel. For seat updates, SSE is simpler.
Why live maps are not enough for the biggest events. For a moderately popular show, live updates make the map trustworthy. For a superstar on-sale, a live map makes things worse. With 100,000 people looking at 60,000 seats, the map would turn grey within seconds, and every click would race against a thousand others. The experience is disorienting, and it is unfair to anyone on a slower connection. The fix is not better technology on the map. It is changing who sees the map, and when: the waiting room in Deep Dive 6. Recognising that the right answer is a product change, not a faster pipe, is the kind of judgement that separates staff-level answers.
6. How does a virtual waiting room work?#
For extremely popular events, an operator switches the event into queue mode. Users then wait in a virtual queue before they can even see the seat map. The queue admits them at a rate the booking path can serve. It does three jobs at once:
- Capacity control: the booking path sees a steady, bounded load instead of a spike of millions.
- Fairness: first come, first served, or randomised at the start, instead of "whoever's script clicks fastest".
- Experience: an honest position and wait estimate, instead of errors and a grey map.
The basic mechanics:
- Join. A user opening the event during queue mode is sent to the waiting room. The service adds them to a per-event Redis sorted set, scored by arrival time:
ZADD wr:{evt} NX <arrivalMs> <userId>.NXmeans refreshing the page does not reset or duplicate a position. - Wait. The client holds an SSE connection, or polls a cheap status endpoint. Position comes from
ZRANK wr:{evt} <userId>, which is logarithmic in the queue size and fast even with 10 million members. - Admit. An admission worker periodically pops the next batch, with
ZPOPMIN wr:{evt} <n>, and marks those users as admitted, for exampleSET wr:adm:{evt}:{user} 1 EX 900, or adds them to an admitted set. It notifies them through the push tier. - Enter. Each admitted user receives a signed access token, such as a JWT with
{eventId, userId, admittedAt, exp}. Booking-path services verify it locally, with no Redis lookup, and reject any hold request without a valid token. Tokens expire (10 to 15 minutes), so an admitted user who leaves frees their slot.
How many to admit, and how often? Treat the booking stage as a system with a target concurrency. Little's law says that the average number of users inside equals the arrival rate multiplied by the average time spent: L = λ × W.
- Suppose admitted users spend on average W = 4 minutes choosing seats and checking out.
- Suppose we want at most L = 20,000 users in the booking stage, which load tests show the hold path handles comfortably.
- Then the admission rate is λ = L / W = 20,000 / 240 s ≈ 83 users per second, or 500 every 6 seconds.
Better still, make admission feedback-driven. Raise the rate while hold latency and error rates are healthy, and lower it when they degrade, like TCP congestion control. Also slow down as inventory runs out. When only 500 seats remain, admitting 20,000 people creates only disappointment.
Estimating the wait. Position ÷ the measured admission rate gives a first estimate. For example, position 1,200,000 at 83 per second is about 4 hours. Smooth the rate with a moving average, and show ranges rather than false precision ("more than an hour"). Two caveats keep estimates honest:
- Abandonment: many queued users leave, so positions improve faster than the raw maths suggests.
- Sell-out: once inventory is gone, tell everyone immediately, rather than letting them wait for nothing.
Fairness at the opening moment. If the queue opens at 10:00:00 exactly, ordering by arrival time rewards those with the lowest network latency, or with bots. A common approach:
- Let users join a pre-queue (a "waiting area") before the on-sale time.
- At the on-sale instant, assign everyone in the pre-queue a random position.
- Then append later arrivals in arrival order.
The random shuffle removes the incentive to hammer the button at 09:59:59.
Making the waiting room itself survive 10 million users:
- Serve the waiting-room page from the CDN as a static page. It only calls a tiny status API, never the event's heavy endpoints.
- Make the status API cheap: one
ZRANKand one token check. Or push position updates over SSE every 15 to 30 seconds, rather than having clients poll every second. - Shard by event: each event's queue is one sorted set. A 10-million-member sorted set is roughly 1 GB in Redis, which is fine. If a single event's queue rate is extreme, partition the queue into N sub-queues by user hash, and admit round-robin across them.
- Edge enforcement: the CDN or gateway rejects booking-path requests without a valid token before they reach origin. The waiting room then protects capacity even against clients that skip the queue page.
Handling no-shows and duplicates:
- One position per account. Key queue entries by authenticated user id, not by session, so opening ten tabs does not give ten positions.
- Re-admission policy. An admitted user whose token expires without a purchase goes back to the end of the queue, or receives one grace re-entry. That is a product decision.
- Fraud signals (many accounts from one device, fingerprinting, CAPTCHA failures) can deprioritise or remove queue entries (Deep Dive 12).
Build or buy? Managed waiting rooms exist: CDN providers and specialist vendors offer them, for example Cloudflare Waiting Room and Queue-it, and AWS publishes a reference "Virtual Waiting Room" solution. They enforce admission at the edge, so overflow traffic never reaches the origin. A large ticketing company may still build its own, to tie the queue to verified-fan programmes, inventory and fraud systems. Either way, the architecture is the same.
Trade-offs to name:
- Long waits frustrate users. Real-time position updates and honest estimates mitigate that.
- An overly cautious admission rate leaves seats unsold for longer, and an overly aggressive one recreates the stampede. Feedback control balances them.
- The queue concentrates load on one Redis key per event. Plan for that shard's memory and CPU, and replicate it.
- Some users will see "sold out" after a long wait. Communicating early (inventory remaining, estimated chance) is better UX, and it reduces load.
This is a classic case of solving a technical problem with a product mechanism. Instead of trying to make 10 million simultaneous seat pickers work, we change the experience so that only thousands pick at once.
7. How do we make event search fast and forgiving?#
Users type "taylor swift london", "tayler swfit", "arsenal", "comedy this weekend near me". They expect relevant results in well under half a second.
Bad: LIKE '%term%' on the primary database
A LIKE with a leading wildcard cannot use a B-tree index, because B-trees are ordered by a value's prefix, and %taylor% has no fixed prefix. So the database scans every row in the events table and tests each one. With 200,000 upcoming events that might take tens to hundreds of milliseconds per query. Under thousands of queries per second, it saturates the database that bookings also depend on. There is no typo tolerance and no relevance ranking either: "Taylor Swift" and "a tribute act mentioning Taylor" rank the same.
Good: proper indexes and query tuning
- Index what is filtered and sorted:
(starts_at),(venue_id, starts_at),(category, starts_at)and a geospatial index on venue location. Prefix searches (name LIKE 'Tay%') can use a B-tree with the right operator class. - Inspect plans with
EXPLAIN ANALYZEto confirm index use and spot sequential scans. - Select only the needed columns instead of
SELECT *. AlwaysLIMIT. Prefer keyset pagination (WHERE starts_at > :last ORDER BY starts_at LIMIT 20) over large offsets. - Split
ORacross different columns into aUNIONof indexed queries, when the planner cannot combine indexes efficiently.
This makes structured filters fast. It does not solve substring matching, typos or relevance. Indexes also cost space and slow writes, so add them for real query patterns only (see Database Indexing and Database Performance and SQL Tuning).
Great: full-text indexes in the database
PostgreSQL has built-in full-text search:
- A
tsvectorcolumn holds normalised words (lexemes), produced by stemming ("concerts" becomes "concert") and stop-word removal. - A GIN (Generalised Inverted Index) index maps each lexeme to the rows that contain it.
- Queries use
to_tsqueryand rank withts_rank. - The
pg_trgmextension adds trigram indexes, which makeILIKE '%tay%'and similarity matching fast, giving modest typo tolerance.
ALTER TABLE events ADD COLUMN search tsvector
GENERATED ALWAYS AS (to_tsvector('english', name || ' ' || coalesce(description, ''))) STORED;
CREATE INDEX events_search ON events USING GIN (search);
SELECT id, name, ts_rank(search, q) AS rank
FROM events, to_tsquery('english', 'taylor & swift') AS q
WHERE search @@ q AND starts_at > now()
ORDER BY rank DESC LIMIT 20;MySQL offers its own FULLTEXT indexes. Neither uses Lucene, the library behind Elasticsearch, but for a catalogue of a few hundred thousand events this can be enough. The costs are extra storage, slower writes, query syntax that is more specialised, and search load landing on the transactional database.
Great: a dedicated search engine (Elasticsearch) fed by CDC
For a large, global catalogue with typo tolerance, relevance tuning, geo and facets, use Elasticsearch or OpenSearch:
- Inverted index: each term maps to the list of documents containing it (a posting list). Queries intersect and score these lists. Documents are scored with BM25, the default similarity, which rewards rare terms and normalises for field length.
- Analysers tokenise, lowercase, strip accents and stem. Separate analysers for names (no stemming, plus edge n-grams for prefix autocomplete) and descriptions (stemmed) improve relevance.
- Fuzzy matching finds terms within a small Levenshtein edit distance: "tayler" is one substitution from "taylor".
fuzziness: AUTOallows 0, 1 or 2 edits, depending on term length. - Filters (date range, category,
geo_distancefrom the user's location) are cached as bitsets and do not affect scoring. - Ranking boosts via
function_score: favour events that are soon, popular (recent page views or sales velocity) or nearby, so a sold-out stadium show ranks above an obscure namesake.
{
"query": { "function_score": {
"query": { "bool": {
"must": [{ "multi_match": { "query": "tayler swift", "fields": ["performer^3", "name^2", "venue", "city"], "fuzziness": "AUTO" } }],
"filter": [{ "range": { "starts_at": { "gte": "now" } } },
{ "geo_distance": { "distance": "50km", "venue_location": { "lat": 51.5, "lon": -0.12 } } }] } },
"functions": [{ "field_value_factor": { "field": "popularity", "modifier": "log1p" } }],
"boost_mode": "multiply" } },
"size": 20
}Keeping the index in sync. The database is the source of truth. Use change data capture: for example, Debezium reads PostgreSQL's write-ahead log and publishes row changes to Kafka, and an indexer consumes them and upserts documents. Compared with having the application write to both stores ("dual writes"), CDC cannot miss a change if one write fails, and it preserves per-row order. Lag is typically seconds. Reindexing from scratch (when mappings change) uses an alias swap: build a new index from a snapshot plus the CDC stream, then atomically point the alias at it (see Elasticsearch and Search Systems).
Denormalise for search. Each event document embeds performer names, venue name, city and location, so one query needs no joins. When a performer is renamed, the indexer updates all of that performer's event documents. That is rare and acceptable.
Costs: another cluster to run, eventual consistency between the DB and the index (seconds), and the sync pipeline to monitor. For this product, those costs are well worth it.
8. How do we cut repeated search load further?#
Search traffic is very skewed. When a tour is announced, a large share of all searches are the same few queries. Caching their results saves most of the work.
Good: cache result pages in Redis.
- Key: a normalised form of every parameter that changes the result, e.g.
search:v3:q=taylor swift|city=london|from=2027-06-01|to=2027-06-30|cat=concert|page=1. Normalisation means lowercasing, trimming, sorting parameters and rounding coordinates to a grid. It raises the hit rate: "Taylor Swift " and "taylor swift" share an entry. Thev3prefix lets a ranking change invalidate everything by bumping a version. - TTL: short for queries whose results change (a minute or so during announcements), longer for evergreen ones.
- Value: the list of event ids and display fields. Hydrate volatile fields, such as "sold out", from the event cache at response time, so a cached search result never shows stale availability.
The challenges are invalidation and misses. Exactly which cached queries a new event should appear in is unknowable in general: any query might match it. Rely on short TTLs plus cache tags: tag each entry with the performers, venues and cities it involves, and purge by tag when one of them changes. Cached fuzzy results make tagging harder, because they may match on misspellings. Accept TTL-based freshness for those.
Great: use the engine's caches, plus the CDN.
- Elasticsearch keeps a per-node query cache for filter clauses, which are cached as bitsets and reused across queries. It also keeps a shard request cache for whole responses, especially aggregation-heavy ones such as facet counts. Both are invalidated automatically when a shard refreshes with new data.
- For non-personalised queries, cache the search API response at the CDN for 30 to 60 seconds, keyed on the normalised query string. A trending query is then served from the edge worldwide. Personalised results (ranked by the user's history or exact location) must not be edge-cached, or must vary on a coarse key, such as the city.
- Autocomplete suggestions for prefixes are a tiny, extremely hot dataset. Precompute the top suggestions per prefix and cache them aggressively (see the search-autocomplete problem).
Trade-offs: consistency between cached and live data needs care. New events appear after the TTL, not instantly, which is acceptable for discovery. Operating CDN cache rules, tags and purges is extra infrastructure. But this layered approach serves trending searches in a few milliseconds from the edge, and keeps the search cluster small (see Caching Fundamentals).
9. How do we integrate payments safely?#
Payment is where money and inventory must agree. A booking is correct only if paid implies seat sold to this buyer, and seat sold implies paid, even when networks time out, webhooks repeat, and users close tabs.
Use a payment processor; never touch card numbers. Processors such as Stripe, Adyen or Braintree provide client SDKs that collect card details in fields hosted by the processor and return a token. Our servers see only the token, which dramatically reduces PCI DSS scope. The processor also handles fraud screening, card-network rules and Strong Customer Authentication (3-D Secure challenges, required for many European cards).
The payment object. With Stripe, the server creates a PaymentIntent for the amount, with the bookingId in its metadata. It passes an idempotency key, such as booking-<bookingId>, so a retried create returns the same intent instead of making a second one. The client confirms the intent, completing any 3-D Secure challenge. The intent moves through states such as requires_payment_method, requires_action, processing, and succeeded or canceled. Other processors have equivalent objects.
Authorise, then capture. Cards support two steps:
- Authorisation reserves the funds on the customer's card.
- Capture actually takes them.
A useful pattern for ticketing: authorise when the user pays, finalise the seats in the database, and capture only after the seats are confirmed as SOLD to this booking. If the database step fails (the rare lost race of Deep Dive 2), void the authorisation instead of refunding a capture. Voids are cheaper, faster and cleaner for the customer than refunds. Some payment methods do not support separate capture, so the design must also handle the refund path.
Webhooks are the source of truth for payment outcomes. The client's "payment succeeded" redirect can be lost, faked or interrupted, so we confirm via the processor's webhook, a server-to-server call to our endpoint:
- Verify the signature on every webhook (processors sign payloads with a shared secret), and reject unsigned ones.
- Expect at-least-once delivery: the same event may arrive several times. Record processed event ids in a table with a unique constraint, and make every handler idempotent (Deep Dive 3).
- Expect out-of-order delivery. Decide based on the current state fetched from the processor, or on monotonic state transitions, not on arrival order.
- Respond fast (200 within a few seconds) and do heavy work asynchronously, through a queue, so the processor does not time out and retry.
Status updates to the client. After submitting payment, the user waits on a "processing" screen. The booking moves through PENDING_PAYMENT → CONFIRMED (or FAILED), and the client learns of it by:
- polling
GET /bookings/{id}every second or two, which is simple and robust; or - an SSE push from the booking service when the webhook lands.
Show a clear terminal state in all cases. Because the webhook can lag, the confirmation page should also handle "still processing" gracefully, and emailing the result makes closing the tab harmless.
Timeouts and unknown outcomes. If our call to the processor times out, we do not know whether the payment was created. Never assume failure and retry with a new key, because that risks a double charge. Either retry with the same idempotency key, which is safe by design, or query the processor for the intent by our reference. A reconciliation job compares our bookings with the processor's records (and its settlement reports) daily, and flags mismatches:
- paid but not confirmed → confirm or refund;
- confirmed but not paid → investigate.
See Idempotency and Safe Retries and the payment-system problem.
Side effects through an outbox. Confirmation triggers emails, ticket issuance (barcodes, wallet passes) and analytics. Write these as outbox rows in the same transaction that confirms the booking. A relay then publishes them to Kafka, so no confirmed booking misses its ticket email, and no email goes out for an unconfirmed booking (see Distributed Transactions: 2PC, Sagas and Outbox).
The booking as a saga. Hold → create payment → confirm seats → capture → issue tickets is a multi-step process. Each step has a compensation: release the hold, void or refund, un-sell seats. The steps can be orchestrated by the Booking Service with a persisted state machine, or by a workflow engine such as Temporal, which makes the timeouts ("expire the hold after 10 minutes unless paid") durable timers instead of fragile cron jobs (see Pattern: Multi-Step Processes and Workflows and Temporal and Workflow Engines).
10. How do we assign seats: chosen, best available and general admission?#
User-chosen seats are what we have covered: the client sends explicit ticket ids, and the hold succeeds only if all are free.
Best available. Many buyers say "2 seats in the lower bowl, best available". The server must choose good seats quickly while hundreds of others do the same:
- Give every seat a quality rank at venue setup (distance to stage, centre versus side, sight lines), and order free seats by it.
- Use
FOR UPDATE SKIP LOCKED(Deep Dive 3), or atomic Redis operations, so concurrent requests take different seats without blocking. - Contiguity: "2 together" means adjacent seats in the same row. Store each row's free seats as a bitmap, and search it for a run of k free bits. The best run is the one with the best rank. In Redis, that is one Lua script per row candidate; in SQL, a window-function query over the row's seats.
- Avoid orphans: do not leave a single empty seat between two sold blocks, because single seats are hard to sell. Many ticketing systems apply a "no single seat gap" rule when allocating: prefer blocks that start at an aisle or abut sold seats.
General admission (GA). A standing-room floor of 20,000 has no seat ids, just capacity. Model it as a counter per price tier:
UPDATE ga_inventory SET sold = sold + :qty
WHERE event_id = :e AND tier = 'FLOOR' AND sold + :qty <= capacity;
-- 1 row -> success; 0 rows -> not enough leftA single hot counter row serialises all buyers. That is fine at hundreds of orders per second, but at extreme rates every transaction queues on one row lock. Mitigations:
- Redis atomic counters for holds, with a Lua script that decrements only if enough remain, plus the database for sales.
- Sharded counters: split capacity into N buckets (for example 20 × 1,000). Each request picks a random bucket with stock, and buckets rebalance near the end.
- Batch allocation: a single allocator process takes requests from a queue and assigns capacity in order. This trades a little latency for no contention, the same idea as a flash-sale inventory queue (see the flash-sale problem).
Holds on GA capacity work just like seat holds: a hold decrements an "available" counter in Redis with a TTL record per hold, and expiry restores the count. The sorted-set-of-expiries technique from Deep Dive 1 applies: a periodic job, or a lazy check on each request, adds back expired holds' quantities. Because a missed restore would leak capacity, back this with periodic reconciliation against the durable record of holds.
Price tiers and dynamic pricing (extension). Prices live on ticket rows or tiers. Dynamic or "platinum" pricing changes them during the sale. The hold must lock in the price shown to the user at hold time, by storing it on the pending booking, so a price change mid-checkout cannot surprise them. The event cache and search documents then update via CDC.
11. How do we scale the booking path, shard data and survive a hot event?#
Shard by event. All tickets, holds and bookings for one event share an event_id, so we partition by it:
- Booking transactions stay single-shard (no distributed transactions).
- The many quiet events spread evenly across shards.
- A directory or consistent-hashing map routes each event to its shard (see Partitioning and Sharding).
User-centric queries ("my bookings") need a different access path. A secondary table keyed by user_id, maintained via CDC, or a separate bookings-by-user index, answers them without scatter-gather.
The hot shard. One superstar event lands on one shard. Can a single PostgreSQL primary handle it?
- With Redis holds, the database sees only purchases: ~30 orders per second for a 60,000-seat sell-out in 15 minutes. Even 10 times that is comfortably within one primary's capacity. A tuned PostgreSQL primary sustains thousands of short write transactions per second.
- With database holds, it also sees hold attempts. With the waiting room capping admitted users at ~20,000 and each making a few attempts per minute, that is ~1,000 to 2,000 conditional updates per second, concentrated on a few thousand hot rows. This is feasible, but contention on the most desirable rows (front sections) causes lock waits. That is the point at which moving holds into Redis pays off.
- Isolate hot events. The directory can place a known on-sale on a dedicated shard beforehand, so it cannot slow other events. Pre-warm its caches and buffer pool, and pre-scale its connection poolers.
Read replicas serve the catalogue and "my bookings", never the booking decision itself. A read from a lagging replica could show a seat as free that was just sold. That is acceptable for display, because the hold and the final update always go to the primary (see Database Replication).
Redis for holds and queues. One event's holds share a hash tag, so they live on one Redis shard: tens of thousands of operations per second is easy. Give each Redis primary a replica, with automatic failover. Remember that failover can lose the last moments of writes, because replication is asynchronous. That is acceptable here, because the database guard prevents a double sale, and the worst outcome is that a hold vanishes and the user gets a conflict at confirmation.
Connection management. Thousands of Booking Service instances × a connection pool each can exceed PostgreSQL's practical connection limit (each connection is a backend process using memory). Put PgBouncer in transaction-pooling mode in front, so many app connections share a few hundred database connections. This only works because every transaction is short, which is another reason never to hold locks across user think-time.
Multi-region. Users are worldwide, but one event's inventory should have one home region, usually near the venue:
- Reads (event pages, search, seat maps) are served from every region via CDN, replicated caches and regional search clusters.
- Writes for that event (holds, bookings) are routed to its home region, adding ~100 to 200 ms for distant users. That is tolerable at checkout.
- Avoid multi-leader writes for inventory: resolving two regions both selling seat F12 after the fact is unacceptable. If the home region fails, promote a synchronous or semi-synchronous standby in a nearby region (see Multi-Region and Global Data and Disaster Recovery and Backups).
12. How do we stop bots and keep the sale fair?#
High-demand tickets are worth far more on the resale market than at face value, so automated buying is a constant threat. Bots:
- join the queue thousands of times;
- hold seats they never buy, so others cannot;
- buy at machine speed and resell at a markup.
Fairness is therefore a real requirement, not a nice-to-have. In the US, the 2016 BOTS Act made it illegal to circumvent ticket-purchasing controls, which shows how serious the problem became.
Layers of defence:
- Identity before access. Require a logged-in, verified account (email plus phone) to join a queue. For the biggest events, use a pre-registration or "verified fan" style programme: users register days ahead, are screened for bot signals, and receive access codes. The on-sale then serves known people, not anonymous traffic.
- Per-account and per-payment limits. Cap tickets per account and per event (for example 4 or 8), and enforce the cap across accounts that share a payment card, device or address. The rule spans many rows, so check it inside the booking transaction, using a per-user counter row with a conditional update, or Serializable isolation (Deep Dive 3).
- Rate limits per account, device, IP and subnet, at the gateway: token buckets on hold attempts, and much stricter limits on the queue-join endpoint (see Rate Limiting and Throttling).
- Bot detection: device fingerprinting, behavioural signals (mouse and touch patterns, timing), reputation of IP ranges (data-centre IPs are suspicious for consumer traffic), and CAPTCHAs or proof-of-work challenges when risk is high. Scores feed queue position (deprioritise or remove) and hold permission.
- Hold abuse limits: only one active hold per account per event, short hold TTLs, and a cooldown after repeated abandoned holds. Holding without buying is the cheapest attack, so make it unprofitable.
- Signed, bound tokens. Bind the waiting-room access token to the account and the device fingerprint, and keep its lifetime short, so admission cannot be shared or sold.
- Post-sale review: cancel orders later found to be fraudulent and release the seats back. Name-on-ticket or delayed delivery of barcodes (rotating barcodes revealed shortly before the event) reduces the resale value of bot purchases.
Trade-offs: every friction step (verification, CAPTCHA, limits) also costs genuine fans. Calibrate defences by event risk: none for a local gig, the full stack for a stadium tour. Monitor false-positive rates, because a fan wrongly blocked is a lost customer.
Security of the rest of the system:
- Webhook signatures and the API's authentication must be enforced.
- The admin tools that create events and inventory are a high-value target: use strong authentication and audit logs.
- Access tokens must be validated server-side on every booking-path request.
See Security Fundamentals for System Design.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Read storm on one event page at on-sale | Origin and DB overload, outage for everyone | CDN with long TTLs for static parts, request collapsing, stale-while-revalidate, in-process cache for hot keys, pre-scaling |
| Cache expiry stampede on a hot event key | Burst of identical DB queries | Single-flight loading, probabilistic early refresh, proactive refresh on change events |
| Row contention on the best seats | Lock waits, latency spikes, failed holds | Redis holds to take clicks off the DB, SKIP LOCKED for best available, waiting room caps concurrency |
| Hold store (Redis) primary fails | Holds lost or unavailable for seconds | Replica failover; DB conditional update still prevents double sale; allow buy-direct in degraded mode |
| Hold TTL expires during slow payment | Two buyers pay for one seat | Extend hold when payment starts; final conditional update picks one; authorise-then-capture so the loser is voided |
| Webhook delayed, duplicated or out of order | Booking stuck pending, or double processing | Signature check, idempotent handler with processed-event table, state-based transitions, reconciliation job |
| Payment call times out with unknown outcome | Possible double charge on naive retry | Retry with the same idempotency key, look up by reference, daily reconciliation with processor reports |
| Cron or sweeper falls behind | Expired holds still look taken (cron design) | Implicit-expiry predicate or Redis TTL so correctness never depends on the sweeper |
| Waiting room overwhelmed by joins | Queue page errors, unfairness | Static queue page on CDN, ZADD NX by account, edge rate limits, pre-queue with random order at open |
| Admission rate mis-tuned | Stampede (too fast) or unsold inventory (too slow) | Feedback-controlled admission using hold latency, error rate and seats remaining |
| Search index lag or CDC pipeline stall | New events missing from search, stale details | Lag monitoring and alerts, replayable Kafka topics, reindex with alias swap, TTLs on result caches |
| Bots hoarding holds or buying out inventory | Real fans locked out, reputational damage | Verified accounts and pre-registration, one hold per account, limits across linked identities, bot scoring |
What Interviewers Expect#
Mid-level#
- Clear requirements, entities and a working API for viewing, searching and booking.
- A high-level design with an Event Service, a Search Service, a Booking Service and a relational database.
- Solve no double booking at least with the status plus expiry plus cron approach, explaining why a long-held database lock is wrong.
- Recognise that event pages should be cached.
Senior#
- Move quickly through the basics, then go deep on:
- reservations, landing on implicit expiry or a Redis TTL lock with the database as the final guard;
- search, with Elasticsearch fed by CDC, fuzzy matching and caching of hot queries;
- popular events, with CDN, caching and stampede protection.
- Explain isolation levels and conditional updates precisely.
- Discuss sharding by event, the hot-shard problem, replicas and failover.
- Integrate payments with idempotency and webhooks.
Staff+#
- Lead the conversation and identify the real problem early: demand exceeds supply by orders of magnitude, so this is an admission and fairness problem as much as a database problem. Propose the virtual waiting room with feedback-controlled admission.
- Distinguish efficiency locks (Redis holds) from correctness guards (the database), and reason about leases, process pauses and fencing.
- Cover failure modes end to end:
- Redis failover;
- TTL expiry during payment, with authorise-then-capture and voids;
- webhook semantics and reconciliation;
- multi-region ownership of inventory.
- Bring bot defence, verified-fan programmes and ticket limits into the design, and quantify trade-offs, such as Little's law for admission rates and bitmap sizes for seat maps.
Deep Dive: Two buyers, one seat, step by stepShow
Here is exactly what PostgreSQL does when two final transactions race for seat 42, under each isolation level. T1 belongs to Alice and T2 to Bob. Both run UPDATE tickets SET status='SOLD', booking_id=:b WHERE id=42 AND status='AVAILABLE'.
| Step | Read Committed (default) | Repeatable Read | Pessimistic lock first |
|---|---|---|---|
| 1 | T1 updates row 42, taking its row lock | Same | T1 runs SELECT ... FOR UPDATE on row 42 and gets the lock |
| 2 | T2 tries to update row 42 and waits on the lock | T2 waits on the lock | T2 runs SELECT ... FOR UPDATE and waits |
| 3 | T1 commits | T1 commits | T1 checks AVAILABLE, updates, commits |
| 4 | T2 wakes, re-checks WHERE on the new version, sees SOLD, updates 0 rows | T2 wakes and fails with a serialisation error, because the row changed after its snapshot | T2 wakes, reads the row (now SOLD), and sees it is unavailable |
| 5 | The app sees 0 rows and fails Bob's booking | The app catches the error and fails or retries Bob's booking | The app fails Bob's booking |
All three are correct. They differ in how the loser finds out: a zero row count, an exception, or an explicit read.
The dangerous version is the one with no lock and no condition: T1 and T2 both SELECT status, both see AVAILABLE, and both UPDATE ... SET status='SOLD' without a WHERE status check. Under Read Committed, both succeed, and the seat is sold twice. This is the classic lost update (read-modify-write) anomaly.
Every correct design either puts the condition in the write or takes the lock before the read. Interviewers often ask candidates to spot this bug in a naive implementation.
The same race in Redis. Two SET hold:42 ... NX commands arrive at the same instant. Redis executes commands one at a time on a single thread, so one runs first and creates the key, and the other sees the key exists and returns nil. There is no interleaving to reason about. That simplicity is part of Redis's appeal for holds.
The same race in DynamoDB. A PutItem or UpdateItem with ConditionExpression: attribute_not_exists(holder) OR holdExpiresAt < :now is evaluated atomically on the item. One write succeeds, and the other fails with ConditionalCheckFailedException. Multi-seat holds use TransactWriteItems, which is all-or-nothing across up to 100 items (see Amazon DynamoDB in Practice).
Deep Dive: After the sale, ticket issuance and entryShow
Out of scope for most interviews, but it completes the picture, and it shapes the anti-fraud design.
Issuance. Once a booking is confirmed, an outbox event triggers ticket issuance:
- Generate a ticket credential per seat: a random identifier, or a signed token encoding event, seat and owner.
- Deliver it to the app and wallet passes.
- Email a confirmation.
Issuance must be idempotent, keyed by ticket id, so retries never mint two valid credentials for one seat.
Static versus rotating barcodes.
- A static barcode (a printed PDF) can be screenshotted and sold many times. Only the first scan at the gate gets in, and everyone else is turned away.
- To prevent this, modern mobile tickets often use rotating barcodes. The app derives a short-lived code from a secret bound to the ticket and the current time, in the style of TOTP (time-based one-time passwords) codes, so a screenshot stops working within seconds. Ticketmaster's SafeTix is a widely known example of this approach.
- Delaying delivery of the credential until shortly before the event also reduces speculative resale.
Entry scanning. Gates must work even if stadium connectivity is poor.
- Scanners download the event's valid ticket list (or the verification keys for signed tokens) before doors open.
- Scanners validate offline, recording each scan locally and syncing to peers and the server so that a ticket scanned at gate A is rejected at gate B.
- That sync is an eventually consistent set of used ticket ids. Duplicates scanned at two gates within the sync window are possible, but they are rare and detected afterwards.
- This is a nice example of choosing availability over consistency where the cost of the inconsistency is small and bounded.
Transfers and resale change the owner and must invalidate the old credential. With signed rotating codes, re-keying the ticket's secret does this instantly for all future codes.
Deep Dive: Choosing the hold durationShow
The hold TTL looks like a UX detail, but it directly controls how much inventory is locked up and not selling at any moment.
Inventory in limbo. By Little's law again, the number of seats held at once equals the hold rate multiplied by the average time a hold lives.
- Suppose 60 holds per second succeed, averaging 2.5 seats each: 150 seats per second enter holds.
- Buyers who complete do so in about 3 minutes on average. Abandoners keep their hold until the full TTL expires.
- With a 10-minute TTL and 30 percent abandonment, the average hold lifetime is 0.7 × 3 + 0.3 × 10 = 5.1 minutes. That gives 150 × 306 s ≈ 46,000 seats in holds at peak, most of a 60,000-seat stadium.
- With a 5-minute TTL, the average lifetime becomes 0.7 × 3 + 0.3 × 5 = 3.6 minutes, about 32,000 seats.
Shorter TTLs recycle abandoned seats much faster, which matters enormously when demand vastly exceeds supply.
But too short hurts real buyers. Entering card details, completing a 3-D Secure challenge, or switching to a banking app can take several minutes. A TTL that expires mid-payment produces the worst outcome: a paying customer who loses the seat. Hence the common two-stage design:
- a selection-to-payment TTL of 5 to 10 minutes, with a visible countdown;
- an extension of a few minutes once payment is actually submitted, granted only once.
Tune per event. Calm events can afford generous holds. Hot on-sales benefit from shorter ones, plus a one-hold-per-account rule (Deep Dive 12). Measure the distribution of time-to-pay among successful buyers, and set the TTL near its 95th to 99th percentile, so that almost every genuine buyer finishes in time while abandoned holds recycle quickly.
Early release. When a user removes seats from their basket or closes checkout, release the hold immediately with a compare-and-delete. Do not wait for the TTL. Every early release returns a seat to the pool minutes sooner.
Deep Dive: The hold handler in codeShow
A compact TypeScript sketch of the hold endpoint, using Redis holds and the database as the guard:
async function createHold(req: HoldRequest, user: User): Promise<HoldResult> {
const evt = await events.getCached(req.eventId);
if (evt.queueMode) verifyAccessToken(req.accessToken, user.id, evt.id); // throws 403
if (req.ticketIds.length > evt.maxPerOrder) throw new HttpError(400, "too many");
const existing = await bookings.findByIdempotencyKey(user.id, req.idempotencyKey);
if (existing) return existing.toHoldResult(); // safe retry
const sold = await tickets.findSold(evt.id, req.ticketIds); // primary read
if (sold.length) return { conflict: sold };
const holdId = uuid();
const ttl = 600;
const keys = req.ticketIds.map(t => `hold:{evt${evt.id}}:t:${t}`);
const [ok, taken] = await redis.evalsha(HOLD_ALL_OR_NONE, keys, [holdId, ttl]);
if (!ok) return { conflict: [taken] };
try {
await bookings.insertPending({ id: holdId, userId: user.id, eventId: evt.id,
ticketIds: req.ticketIds, priceCents: evt.priceFor(req.ticketIds),
holdExpiresAt: Date.now() + ttl * 1000, idempotencyKey: req.idempotencyKey });
} catch (e) {
await redis.evalsha(RELEASE_IF_OWNER, keys, [holdId]); // undo on failure
throw e;
}
await availability.markHeld(evt.id, req.ticketIds, Date.now() + ttl * 1000);
return { holdId, expiresAt: Date.now() + ttl * 1000 };
}Points worth noticing:
- The idempotency lookup comes first, so a client retry after a timeout returns the original hold.
- The sold check reads the primary, not a replica, to avoid a stale "available".
- The Redis script is all-or-none, and keys share the event's hash tag.
- If the pending-booking insert fails, the hold is released with a compare-and-delete, so we never strand a hold without a booking.
- The availability update is best-effort. If it fails, the CDC and expiry paths heal the map, and correctness never depends on it.
Deep Dive: Contention maths, why the best seats collideShow
Why do conflicts concentrate so sharply? Model admitted users choosing seats.
- Suppose 2,000 users are choosing in the same 30-second window, and each picks among the best 200 visible seats, with preferences skewed towards the very best.
- Even with uniform choice among 200 seats, 2,000 picks means an average of 10 users per seat. Almost every hold attempt on those seats collides.
This is the birthday problem at scale. With n users choosing uniformly among m seats, the expected number of colliding pairs is about n² / (2m). For n = 2,000 and m = 200, that is about 10,000 colliding pairs. Conflicts are the norm, not the exception.
Three consequences for the design:
- Conflicts must be cheap. A failed
SET NXin Redis costs microseconds. A failed conditionalUPDATEin PostgreSQL costs a lock wait plus a transaction. At these collision rates, the cheap path matters, which is one argument for Redis holds. - The UI must help users avoid conflicts. Live-ish availability (Deep Dive 5) and best-available allocation (Deep Dive 10) let the server spread users across free seats instead of letting them all click the same ones.
- Admission rate interacts with collisions. Halving concurrent users roughly quarters colliding pairs (n² scaling). That is a strong reason to keep the booking-stage population moderate, rather than admitting as many as the servers could technically handle.
Lock wait time under contention. If one hot row receives λ update attempts per second, and each holds the row lock for s seconds, utilisation is ρ = λs. For s = 2 ms and λ = 300 per second, ρ = 0.6. Queueing theory (an M/M/1 approximation) gives mean waiting time s × ρ / (1 − ρ) ≈ 3 ms. That is fine. At λ = 450 per second, ρ = 0.9, and the wait is 18 ms. As ρ approaches 1, waits explode. This is the quantitative reason not to let thousands of users per second hammer the same rows in the database, and why holds and admission control exist.
Deep Dive: A worked on-sale timelineShow
A stadium show with 60,000 seats goes on sale at 10:00. 3 million users are in the pre-queue, and 2 million more join in the first hour.
- 09:00 to 10:00, pre-queue.
- The waiting-room page is static and CDN-served. Joins are ~1,000 per second at peak, each a
ZADD NX. - The read tier, push tier, Redis shards and the event's dedicated database shard are pre-scaled. Caches are warmed with the event, venue and seat-map geometry.
- The waiting-room page is static and CDN-served. Joins are ~1,000 per second at peak, each a
- 10:00:00, open.
- The pre-queue is shuffled into random order, and the first batch is admitted.
- The target booking-stage population is 20,000, with ~4 minutes average stay, so admission runs at ~80 per second.
- Queued users receive position updates every 20 seconds over SSE: 3M / 20 = 150,000 messages per second across the push tier. Dozens of push nodes handle that comfortably.
- 10:00 to 10:20, selling.
- ~2,000 hold attempts per second in Redis, ~40 percent conflicting. ~60 holds succeed per second. ~70 percent of holds convert to purchases.
- The database sees ~25 to 30 order confirmations per second, plus pending-booking inserts.
- Payment webhooks arrive within seconds. A handful of TTL-expired-during-payment races are resolved by voiding authorisations.
- 10:20, nearly sold out.
- With 2,000 seats left, admission slows sharply. The queue page shows "limited tickets remaining", and many users leave.
- 10:27, sold out.
- The event status flips to
SOLD_OUT, the CDN is purged, and the queue is closed with a clear message. - Released seats from expired holds and failed payments trickle back over the next 15 minutes. They go to users still in the booking stage, or the queue is reopened briefly.
- The event status flips to
The numbers that matter were set in advance: the admission rate, the hold TTL and the pre-scaling. That is the essence of designing for a known spike.
Deep Dive: Failure walkthroughsShow
Redis hold shard fails over mid-sale. A few seconds of hold attempts fail, and some just-created holds may be lost (asynchronous replication).
- Users whose holds vanished may see someone else take their seat. At confirmation, the database conditional update picks a single winner, and the loser's authorisation is voided.
- The availability bitmap may show stale state. CDC from sales and the expiry sorted set repair it.
- Outcome: some disappointed users, no double sales.
PostgreSQL primary of the hot shard fails. Booking for that event pauses for the failover duration, typically seconds to a minute with automated tooling such as Patroni.
- Holds in Redis continue to tick, so extend all active holds by the outage duration, or users lose seats through no fault of their own.
- Pending webhooks queue at the processor, which retries.
- With a synchronous standby, no committed booking is lost.
Payment processor outage. New payments fail.
- Stop admitting from the queue, or pause the event's sale, and extend holds.
- Showing "payments temporarily unavailable" beats letting users hit errors repeatedly.
- Some platforms integrate a second processor for failover. That is a considerable investment (separate tokens, reconciliation), justified only at large scale.
CDN or edge provider incident. The read path falls back to origin, which cannot handle the full storm. Mitigations:
- a second CDN with DNS failover;
- origin shields;
- a minimal "static mode" for event pages;
- tighter admission so the booking path is protected even if browsing suffers.
CDC pipeline stalls. Search and availability go stale, but bookings stay correct. Alert on lag. Replay from Kafka offsets when it recovers.
Clock skew between servers. Hold expiry decisions should use a single clock:
- the database's
now()for the implicit-expiry design; - Redis's own TTL for the lock design.
Comparing timestamps from many app servers' clocks invites off-by-seconds bugs.
Deep Dive: Observability for an on-saleShow
What the on-call engineer watches during a big sale (see Observability: Logs, Metrics and Traces):
Funnel metrics per event:
- queue size and join rate;
- admission rate and booking-stage population;
- holds attempted, succeeded and conflicted;
- payments started, succeeded and failed;
- seats remaining;
- time-to-sell-out projection.
Latency SLOs:
- p99 hold latency, alerting above 300 ms;
- event page p99 from origin;
- search p99;
- webhook processing lag.
Health:
- Redis CPU and memory per shard (especially the event's hash slot);
- PostgreSQL lock waits, transaction rate, replication lag, connection-pool saturation;
- CDN hit ratio (should be above 95 percent for event pages);
- SSE connection counts per push node.
Correctness monitors:
- any ticket with two active bookings (should be impossible; page immediately);
- bookings confirmed without captured payment, and vice versa;
- holds without pending bookings.
Run these as continuous queries during the sale, and in the daily reconciliation.
Business guardrails:
- conversion from admission to purchase;
- abandonment in the queue;
- bot-score distributions;
- share of orders hitting the per-account limit.
A pre-sale game day. Load-test the full path at 1.5 times the expected peak, with synthetic users going through queue → hold → pay (against the processor's test mode). Then rehearse the failovers above.
Deep Dive: A 45-minute interview planShow
- Requirements and scale (5 minutes). View, search, book. Consistency for booking, availability for browsing. 10M users for one event, 100:1 reads.
- Entities and API (5 minutes). Event, Venue, Performer, Ticket, Booking. Split hold from pay early, or flag that you will.
- High-level design (10 minutes). Event, Search and Booking services; PostgreSQL; Stripe with webhooks. Show the conditional update that prevents double booking.
- Deep dive: reservations (8 minutes). Bad lock, then status plus cron, then implicit expiry or a Redis TTL lock with the DB guard. Expiry during payment.
- Deep dive: popular events (8 minutes). CDN and caching for event pages, then the waiting room with admission control and tokens.
- Deep dive: search (5 minutes). Elasticsearch with CDC, fuzziness and result caching.
- Wrap-up (4 minutes). Sharding by event, the hot shard, failure modes, bots.
If the interviewer pushes on one area, follow them. The plan ensures that the three things almost always probed (double booking, popular events and search) all get time.
Deep Dive: Real-world notes and variantsShow
Real-world notes (hedged where details are not public):
- Ticketmaster's November 2022 presale for Taylor Swift's Eras Tour drew demand far beyond what its systems were prepared for. The company cancelled the planned general public sale, citing extraordinarily high demand and insufficient remaining inventory, and the episode prompted a US Senate hearing in early 2023. It is the canonical example of why admission control, verified-fan pre-registration and bot defence are central, not optional.
- Waiting rooms are offered as managed products by CDN and security vendors, and as open reference architectures by cloud providers. That shows how standard the pattern has become for flash sales and ticketing.
Variants:
- Cinema booking (for example BookMyShow): many small venues and showtimes, with lower contention per show but huge numbers of shows. The same hold-with-TTL design applies, and sharding by show spreads load naturally.
- Airline seats and hotel rooms: inventory spans time (date ranges, flight legs) and is often sold through external distribution systems. Overbooking is deliberate. See the flight-booking and hotel-booking problems.
- Resale marketplaces: a ticket can change owner many times. Each listing is a single unit, sold with the same conditional update, plus escrow-style payments and payouts to the seller.
- Dynamic pricing: prices change with demand during a sale. Holds must lock in the displayed price, and caches must carry versioned prices.
- Season tickets and memberships: priority windows before the public on-sale, implemented as separate queues or presale codes with their own inventory allocations.
- Flash sales of physical goods: the same contention and admission ideas, with counters instead of seats, plus shipping. See the flash-sale problem.
Key Takeaways#
- Separate the hold from the sale.
- A temporary hold with a TTL (implicit expiry in the row, or a Redis lock) gives users a fair chance to pay.
- A conditional update in the database is the unbreakable guard against double booking.
- Never hold database locks across user think-time.
- See Pattern: Dealing with Contention and Distributed Locks.
- Treat a TTL lock as a lease. A paused process can outlive its lease, so correctness must be fenced at the resource, here by the ticket row's state. Redis is the efficiency lock, and PostgreSQL is the correctness lock.
- Split static from dynamic data.
- Event details and seat-map geometry are cached at the CDN and in Redis, with versioned URLs and CDC-driven invalidation.
- Availability is a compact bitmap with deltas, pushed via SSE.
- See Pattern: Scaling Reads.
- When demand exceeds supply by orders of magnitude, control admission. A virtual waiting room, sized with Little's law and feedback, turns millions of simultaneous users into a steady stream of thousands. It also delivers fairness and a better experience.
- Make search a derived index. Elasticsearch fed by CDC gives fuzzy, ranked, filtered search under 500 ms. Layered caches (Redis, engine caches, CDN) absorb trending queries.
- Integrate payments defensively.
- Tokenise on the client, and use idempotency keys and signature-verified, idempotent webhooks.
- Authorise, then capture, so a lost race can be voided.
- Reconcile daily, and run the booking as a saga with compensations (see Pattern: Multi-Step Processes and Workflows).