Design a Ticket Booking System
Understanding the Problem
🎟️ What is a ticket booking system? A ticket booking system sells assigned seats for something that happens at a fixed time: a concert, a football match, a movie showing, a train journey. Users browse what's on, look at a seat map, pick specific seats, hold them for a few minutes while they pay, and get tickets. What makes it hard is that every seat is unique, many people want the same good seats at the same moment, and a seat sold twice is a very visible failure.
You'll get this question in several forms. "Design Ticketmaster" is the classic: one company owns the inventory, and big on-sales bring millions of fans at once. "Design Fandango" adds a twist: the seats belong to many theater chains, each with its own ticketing system, and we're an aggregator in front of them. "Design IRCTC" (Indian Railways' booking site) changes the inventory model: a train seat can be sold from stop A to stop C to one person and from C to E to another. All three are the same problem at the core: show what's free, lock seats briefly, confirm with payment, never double-sell. We'll design the core around event ticketing, then cover aggregation across providers and train segments as deep dives.
Functional Requirements
Core Requirements
- Users should be able to search for and browse events (or showtimes, or trains) and see their details.
- Users should be able to view a seat map showing which seats are available.
- Users should be able to select one or more seats and hold them for a short time (say 10 minutes) while they check out.
- Users should be able to pay to confirm the booking and receive tickets.
Below the line (out of scope)
- Resale and ticket transfers.
- Dynamic pricing.
- Event creation and venue management by organizers.
- Physical ticket scanning at the gate.
Non-Functional Requirements
Ask your interviewer about the scale and, especially, the peaks. For our design: 100 million monthly users, around 50,000 events and showtimes on sale at any time, typical traffic of a few thousand requests per second, and a few mega on-sales a year where several million users show up for a stadium of 60,000 seats in the same minute.
Core Requirements
- The system must never sell the same seat to two people (strong consistency on seat state).
- The system should handle on-sale spikes of millions of concurrent users without falling over or becoming unfair.
- Seat maps should be close to real time: a seat someone else just took should disappear within a couple of seconds.
- Browse and search should be fast (under 300 ms) and highly available; they can be slightly stale.
Below the line (out of scope)
- Bot detection in depth (we'll mention the controls, not build a fraud system).
- Multi-region active-active for a single event's inventory.
The back-of-the-envelope here is about the spike, not the average:
- Contention. 3 million people for 60,000 seats means 49 out of 50 will leave without tickets. And demand isn't uniform: the front sections attract far more clicks than the back. Contention concentrates on a few thousand seats.
- Seat map traffic. If we let 3 million people look at the seat map and each polls every 2 seconds, that's 1.5 million requests per second for one event. Even letting only 50,000 shoppers in at a time, polling is 25,000 requests per second for a small amount of data that changes constantly.
- Writes. At most 60,000 successful bookings per event, plus holds that expire and get retaken. A few thousand writes per second for one event, all on one event's rows.
The write volume is not the problem. The problem is that millions of read-and-try requests are aimed at the same 60,000 rows, and most of them will fail. Design so that failing is cheap and so that most people never reach the seat map at the same time.
The Set Up
Planning the Approach
We'll build the four requirements with a straightforward design: a search index for browsing, a cached seat map, database-backed holds and a checkout flow. Then the deep dives cover seat locking in detail, surviving the on-sale spike, keeping seat maps live, selling seats we don't own (Fandango) and train seats sold by segment (IRCTC).
Defining the Core Entities
- Event: something with a time and a venue: a concert, a showtime, a train run on a date. Name, performer or film, start time, venue, on-sale time.
- Venue: the physical layout: sections, rows and seats with coordinates for drawing the map. Venue layouts change rarely and are reused across events.
- Ticket: one seat for one event. Its
statusisAVAILABLE,HELDorBOOKED, with the holder and an expiry when held. This is the contended data. - Booking: a confirmed purchase of one or more tickets by a user, with payment details and status.
Separating Venue from Ticket matters. The layout of a 60,000-seat stadium is a large static file we draw once and cache forever. The status of each seat is tiny and changes all the time. Treating them as one thing would make us ship the whole layout every time a seat changes.
API or System Interface
GET /events?query=..&city=..&from=..&to=..&cursor=.. -> { events: [...], nextCursor }
GET /events/{eventId} -> { event, venueLayoutUrl, priceTiers }
GET /events/{eventId}/seats -> { version, available: <bitmap or list> }
POST /events/{eventId}/holds { seatIds: [...] } -> 201 { holdId, expiresAt }
-> 409 { unavailable: [seatIds] }
DELETE /holds/{holdId} -> 204
POST /holds/{holdId}/checkout { paymentToken, idempotencyKey }
-> { bookingId, status: "CONFIRMED", tickets: [...] }
As always, the user comes from the auth token, not the body. That matters doubly here because per-user ticket limits ("max 4 per account") are a core anti-scalping control.
High-Level Design
1) Users should be able to search for and view events
Event data is read-heavy and changes slowly. We store it in a relational Event DB (Postgres) and index it in Elasticsearch for full-text search ("taylor"), filters (city, date range, genre) and sorting. Changes flow from the database to the index through change data capture, so the index is eventually consistent with the source of truth, which is fine for browsing.
Event pages are mostly static (description, images, venue info), so we cache them at the CDN. For a big on-sale, the event page is the first thing millions of people load, and it should cost us nothing.
2) Users should be able to view a seat map
The seat map has two layers:
- Layout: the geometry of every seat, section and aisle. It's the same for every event at the venue. We publish it as a static file (SVG or JSON) on the CDN, versioned by venue configuration.
- Status: which seats are available for this event right now. This is what changes.
The client fetches the layout from the CDN once and then asks a Seat Service for the status. The status is very compact: with seats numbered 0..59,999, a bitmap of "available" is 60,000 bits, or 7.5 KB, before compression. The Seat Service keeps that bitmap per event in Redis and serves it from there, falling back to the Tickets DB on a cache miss.
For this first version, the client polls the status every few seconds. We'll improve on that in the deep dives.
3) Users should be able to hold seats
A user clicks four seats and presses "Continue." We need all four or none, and nobody else can have any of them.
The simple, correct version uses the Tickets table with a conditional update:
BEGIN;
UPDATE tickets
SET status = 'HELD', held_by = :userId, hold_id = :holdId,
hold_expires_at = now() + interval '10 minutes'
WHERE event_id = :eventId
AND seat_id = ANY(:seatIds)
AND (status = 'AVAILABLE' OR (status = 'HELD' AND hold_expires_at < now()));
-- if rows updated < number of seats: ROLLBACK, return 409 with the seats that weren't free
COMMIT;
The WHERE clause makes the check and the write one atomic step for each row. If any seat is taken, fewer rows update than requested and we roll back, releasing the ones we did grab. Notice the second half of the condition: an expired hold counts as available, so a seat abandoned by someone who walked away comes back on its own, even before any cleanup job runs.
After the hold commits, the Seat Service's cached bitmap is updated (by the Booking Service directly, or from the change stream), so other users see those seats go grey.
4) Users should be able to pay and get tickets
At checkout the Booking Service:
- Checks the hold is still valid and moves it to a "paying" state with a conditional update, so the expiry worker can't release it mid-payment.
- Charges the payment provider (Stripe, Adyen) with an idempotency key.
- In one transaction, marks each ticket
BOOKED, creates the Booking row, and writes a "booking confirmed" event to an outbox table.
A relay publishes outbox events to Kafka, where downstream consumers issue tickets (QR codes or mobile wallet passes), send email and update analytics. An expiry worker sweeps holds past their expiry and returns them to AVAILABLE (with a conditional update, so it never touches a booked seat).
Potential Deep Dives
1) How do we lock seats so two users never get the same one?
Seat locking is the heart of this question. The hold lasts minutes, while a database transaction should last milliseconds, so the design question is where that long-lived lock lives.
Bad Solution: Hold a Database Lock for the Whole Checkout
Approach
SELECT ... FOR UPDATE the seats when the user selects them and keep the transaction open until they pay.
Challenges
A transaction open for ten minutes holds row locks and a database connection for ten minutes. With tens of thousands of shoppers, you run out of connections long before you run out of seats. If the app server crashes, the lock lasts until the database notices the dead connection. Long transactions also hurt the database in other ways (in Postgres, they hold back vacuum). Never tie a user's think time to a database transaction.
Good Solution: Hold State in the Tickets Table
Approach
What the high-level design does: the hold is data (status = 'HELD', hold_expires_at), written by a short conditional update. The lock is "held" without any open transaction, expired holds count as free in the same condition, and a sweeper cleans up.
Challenges
It's correct and simple, and for most events it's all you need. The weak spot is the on-sale. Thousands of admitted users hammering the same few thousand rows in one event's partition means lots of failed updates and row lock contention on the hottest seats. Each failure is a database round trip that achieved nothing.
Great Solution: A Redis Lock Layer in Front, the Database as the Final Word
Approach
Put the short-lived hold in Redis, where a failed attempt costs microseconds, and keep the database as the source of truth for bookings. Each seat gets a key with a TTL; a Lua script takes all requested seats or none:
-- KEYS = seat:{eventId}:{seatId} for each seat; ARGV[1] = holdId, ARGV[2] = ttl ms
for i, k in ipairs(KEYS) do
if redis.call('EXISTS', k) == 1 then return {0, i} end -- seat i is taken
end
for _, k in ipairs(KEYS) do
redis.call('SET', k, ARGV[1], 'PX', ARGV[2])
end
return {1}
A Lua script runs atomically in Redis, so no other command interleaves between the checks and the sets. Using {eventId} as a hash tag keeps an event's keys on one Redis Cluster slot, which a multi-key script requires. The TTL is the hold: if the user disappears, the key expires and the seat frees itself, with no sweeper needed for Redis.
At checkout, the Booking Service writes the booking to the database with a conditional update (status = 'AVAILABLE' → BOOKED) under a unique constraint on (event_id, seat_id) for confirmed tickets. If Redis and the database ever disagree, the database wins.
Challenges
Redis is not a perfect lock. If the primary fails over to a replica that missed the latest writes, some holds vanish, and a second user could hold a seat the first user is paying for. The database check at checkout catches it, so we never double-sell, but one user gets an error at payment time. That's rare and acceptable; tell your interviewer you'd prefer an occasional failed checkout over a sold-twice seat. If you need the lock itself to be safe across failures, the fencing-token approach in distributed lock applies, but for seat holds it's usually not worth it.
Interviewers often ask, "What if the user's hold expires while their payment is in flight?" The answer is a state change before charging: move the hold to
PAYING(and extend the Redis TTL) with a conditional update. The sweeper only releases holds inHELD. A stuckPAYINGhold is resolved by asking the payment provider about the idempotency key.
2) How do we survive a big on-sale?
At 10:00:00 three million people press "Buy tickets" for 60,000 seats.
Bad Solution: Scale Out and Hope
Approach
Autoscale the API and Booking Service, add read replicas, and let everyone in.
Challenges
The bottleneck isn't stateless compute; it's one event's seats. Everyone sees the same seat map, picks the same front-row seats, and all but one fail. They retry with other seats, which were also just taken. The experience is a stream of "sorry, that seat's gone," the database spends its time on failed attempts, and users with scripts get the best seats.
Good Solution: Rate Limit Admission to the Booking Path
Approach
Cap requests to the hold endpoint per event at what the backend handles, return 429 beyond it, and have clients retry with jitter.
Challenges
It protects the system but turns the on-sale into a lottery that rewards whoever retries the fastest, which means bots.
Great Solution: A Virtual Waiting Room, Plus Smarter Seat Selection
Approach
Users who arrive for the on-sale join a waiting room. Everyone who arrives before the start gets a random position; later arrivals queue behind them in order. The waiting room admits users at a controlled rate and gives each a short-lived signed access token, required by the seat map and hold endpoints. A user who's admitted has, say, 10 minutes to pick seats and pay.
Pick the admission rate from the inventory, not just capacity. If 60,000 seats sell at about 3 tickets per order, that's 20,000 orders. Letting in 2,000 users a minute means the event sells out in somewhere around 10-15 minutes, while the people in line get honest updates ("you're #340,000; tickets may sell out before your turn") and the waiting room closes once everything is held or booked. Since holds expire, keep admitting a trickle after the "sold out" moment as seats come back.
Inside, reduce contention on the seats themselves:
- Best available. Let users choose a section and quantity, and have the server pick the best adjacent seats. The server can spread concurrent requests across different seats instead of everyone colliding on row 1. Many large on-sales default to this mode.
- Per-user limits in the hold script (count holds per user per event) to stop one account grabbing 50 seats.
- Bot defenses at the door: logged-in accounts, verified phone numbers, CAPTCHA when joining the queue rather than when clicking a seat.
Challenges
The waiting room is a system of its own, and its position endpoint has to handle millions of polling clients. It's stateless and cacheable, so it scales, but it needs to be built and load-tested ahead of time. It also changes the product, which needs buy-in. The full treatment of the waiting room is in flash sale; the difference here is that each user is choosing specific seats, so best-available allocation does more to cut contention than any storage trick.
3) How do we keep the seat map live for everyone looking at it?
With 50,000 admitted shoppers on one event, the seat map has to reflect taken seats within a second or two, or people waste their attempts on seats that are already gone.
Bad Solution: Poll the Database
Approach
The client calls GET /seats every few seconds, which queries the Tickets table.
Challenges
50,000 clients every 2 seconds is 25,000 queries per second, each scanning 60,000 rows. That's the database doing nothing but answering "what changed?" for the event it most needs to protect.
Good Solution: Poll a Cached Bitmap
Approach
Keep the availability bitmap in Redis (SETBIT on every hold, release and booking). The status endpoint returns it with a version number, and clients send If-None-Match so unchanged responses are a cheap 304. At 7.5 KB uncompressed and much less compressed, 25,000 requests per second is a modest load for a few Redis replicas and stateless servers.
Challenges
Polling still means staleness up to the poll interval and a lot of requests returning almost the same data. Shortening the interval multiplies the load.
Great Solution: Push Changes with Server-Sent Events
Approach
Clients open a Server-Sent Events connection to the Seat Service for the event. On connect they get a full snapshot (bitmap plus version). After that they get small deltas: "seats 1204, 1205 held; seat 88 released; version 5512." The Booking Service publishes each change to a Redis pub/sub channel (or a Kafka topic) per event; every Seat Service instance subscribes for the events its clients are watching and fans the deltas out.
If a client sees a gap in version numbers, or reconnects, it fetches a fresh snapshot. For a hot on-sale, we can batch deltas into one message every 200-500 ms per event, which keeps the message rate per client low even when hundreds of seats change per second.
Challenges
Long-lived connections need load balancers and servers configured for them, and 50,000-plus connections per event spread across a fleet. That's ordinary for SSE (each connection is mostly idle) but it's capacity to plan. Pub/sub is fire-and-forget, so the version-and-resync scheme is what makes it correct. WebSockets work too, but we don't need client-to-server messages on this channel, and SSE is simpler. See real-time updates for the trade-offs.
The seat map is a hint, not a promise. Even with push, two users can click the same seat in the same 100 ms. The hold script is what decides; the map just makes collisions rarer.
4) How do we sell seats we don't own, across many providers?
This is the Fandango version. The seats belong to theater chains, each with its own ticketing system (a point-of-sale system at the theater or a chain-wide API). People also buy at the box office and on the chain's own app. We're one sales channel among several, and the provider's system is the source of truth.
The design changes in a few ways:
- Browsing from a cache. We pull showtimes and seat layouts from each provider on a schedule (every few minutes) and on change notifications if the provider offers them, and store them in our own Showtime DB and cache. Search and showtime pages never call providers synchronously; providers' APIs are slower and less available than we'd like for our read traffic.
- Seat status on demand, cached briefly. When a user opens a seat map, we ask the provider for current seat status and cache it for a few seconds per showtime. That keeps us from hammering the provider when a popular showing is open on thousands of phones.
- Holds through the provider. Our hold calls the provider's "reserve seats" API, which most ticketing systems support with their own timeout. We store our own Order row with the provider's reservation ID. Confirmation calls their "complete sale" API after our payment succeeds.
Each provider gets an adapter that maps their API (or batch files, for old systems) to our internal interface: listShowtimes, getSeatStatus, holdSeats, confirm, release. Adapters own retries, timeouts, auth and rate limits for their provider.
The booking becomes a small saga across two systems that don't share a transaction:
- Create our Order as
PENDING. - Hold seats with the provider. On failure, mark the order failed and show "seats no longer available."
- Charge the user. On payment failure, release the provider hold.
- Confirm with the provider. On failure after retries, refund the user and release.
- Mark the order
CONFIRMEDand issue the provider's ticket or confirmation code.
Every step is retried with an idempotency key or the provider's reservation ID, so a timeout doesn't produce duplicates. The hardest case is a timeout on step 4: did the provider confirm or not? We don't guess. A reconciliation job queries the provider for the reservation's status, and a nightly comparison of our confirmed orders against the provider's sales report catches anything left over.
Challenges
We inherit each provider's limits. If a chain's API is down, we stop selling its tickets but keep showing cached showtimes with "tickets unavailable" rather than failing the whole site. Circuit breakers per provider keep one slow chain from tying up all our booking threads. And a provider's hold timeout may be shorter than ours; the adapter should expose it so our hold never outlives theirs.
If the interviewer asks "why not just call the provider for everything?", the answer is that their read capacity, latency and uptime aren't ours to control. Cache everything you can show, and only go to the provider for what has to be exact: seat status at selection time, holds and confirmation.
5) How do we book train seats sold by segment?
This is the IRCTC version. A train on a date runs through stops 0, 1, 2, ..., N. A passenger from stop 2 to stop 5 occupies a seat only on segments 2→3, 3→4 and 4→5. The same seat can be sold again for 0→2 and 5→N. Inventory isn't per seat; it's per seat per segment.
Data model. For each train run and coach class, store each seat's occupancy as a bitmask over segments. A long-distance train might have 30-40 stops, so 64 bits per seat is plenty. A run with 1,200 seats in a class is 1,200 × 8 bytes, under 10 KB. A booking from stop a to stop b needs a seat whose mask has no bits set in [a, b):
need = ((1 << (b - a)) - 1) << a // bits a .. b-1
seat is free for the journey <=> (mask & need) == 0
book it : mask |= need
"How many seats are available from Pune to Delhi?" is a count of seats with (mask & need) == 0, which is fast over a few thousand integers in memory.
Choosing which seat. Picking the seat matters, because careless choices fragment inventory. If we give a 2→5 passenger a seat that's empty end to end, we may block a later 0→N booking that needed a completely free seat. A common heuristic is best fit: prefer seats whose existing bookings border the requested segment, so the gaps that remain are as large as possible. Berth preferences (lower, upper, side), keeping a group together and quotas also feed in.
Quotas, RAC and waitlist. Seats are divided into quotas (general, ladies, senior citizen, Tatkal and others), each its own pool. When a pool is full, bookings move to RAC (reservation against cancellation, where two passengers share a berth) and then a waitlist with a position. When a confirmed passenger cancels, the freed segments go to the first eligible RAC or waitlisted bookings whose journey fits. A final chart is prepared some hours before departure, after which allocations are fixed.
Concurrency. All bookings for one train run and class touch the same small piece of state, so we serialize them per train run: route every booking request for a run to one partition (a Kafka partition keyed by train run, or a single-writer actor), where a worker applies them in order against the in-memory masks and persists each result to the database before acknowledging. There are no locks, no conflicts and no retries, and one worker can apply thousands of bookings per second for its run. Different trains are independent and spread across partitions.
The Tatkal rush. Tatkal (last-minute) quota opens a day before travel at a fixed morning time, and demand on popular routes far exceeds supply in the first minutes. It's an on-sale like a concert: a waiting room with randomized positions at open time, CAPTCHA at the door, per-account limits, and the per-train serial queue behind it. The queue also gives honest feedback: a user can be told "your request is #12,431 for this train" instead of watching a spinner.
Challenges
The single-writer design needs a failover story: if a partition's worker dies, another takes over, rebuilds the masks from the database (or a snapshot plus the log), and continues from the last committed offset. Because each result is persisted before the user is told, nothing confirmed is lost. Users waiting during the takeover see a few seconds of delay.
Final Design
- Users browse events from the CDN and Elasticsearch. For a big on-sale, they first join the waiting room, which admits them at a controlled rate with signed access tokens.
- An admitted user loads the venue layout from the CDN and subscribes to the Seat Service over SSE for live seat status, served from a bitmap in Redis.
- Selecting seats calls the Booking Service, which takes all of them or none with a Lua script on per-seat Redis keys with a TTL.
- Checkout moves the hold to
PAYING, charges the payment provider with an idempotency key, then marks ticketsBOOKEDin the database under a conditional update and unique constraint. An outbox event triggers ticket issuance and email. - Expired holds free themselves in Redis; the Expiry Worker releases any database-level holds with conditional updates.
- For seats owned by partners (theater chains), the Booking Service holds and confirms through provider adapters in a saga, with reconciliation for uncertain outcomes. For trains, bookings for each run are serialized through one partition that allocates seats by segment.
What is Expected at Each Level?
Mid-level
You should split the venue layout from seat status, model tickets with AVAILABLE/HELD/BOOKED and an expiry, and hold seats with a conditional update so two users can't hold the same seat. You should know not to keep a database transaction open during checkout. With hints, you should reach caching the seat map and some form of admission control for big on-sales.
Senior
You should work through seat-locking options and land on short-lived holds (in the database or Redis with TTLs) with the database as the final check, and handle the hold-expiry-versus-payment race. Expect to design the on-sale: a waiting room with randomized positions, admission rate tied to inventory, and best-available seat assignment to reduce collisions. You should keep the seat map fresh without polling the database, ideally with SSE and snapshots plus deltas.
Staff+
You should adapt the core design to different inventory owners and models without being prompted: an aggregator that caches what it can and runs a saga with reconciliation against providers it doesn't control, and segment-based train inventory with a fragmentation-aware allocator and per-train serialization. Expect to discuss operating the on-sale (pre-scaling, load tests, kill switches, fairness as a product decision) and when the extra machinery isn't needed: a neighborhood cinema's Tuesday matinee doesn't need a waiting room.