12 min read
Designing ticketmaster
In this article, we shall see the designing of ticketmaster system.
On this page
Requirements#
Functional#
User would want to:
- View events.
- Search for events.
- Book ticket(s) for events.
Non-functional#
- For searching and viewing, we need to prioritize availability over consistency.
- While ticket booking and payment, we need to prioritize consistency over availability.
- The scaling is very important because this can sometimes be accessed by tens of millions of users to book tickets for popular events.
- Searching should be low latency.
- Read heavy traffic, since more users will browse, and the actual number of people buying will be less.
Core entities#
- Event
- Performer (One event can have many performers)
- Venue (One event will have one venue)
- Ticket (One event can have many tickets)
- Booking (One booking can have many tickets)
- User
APIs#
GET /events/{event_id}, returns the event, venue, performer, and Ticket[] (so the client can render the interactive seat map).GET /events/search?keyword=...&take=...&skip=...returns a list of matching events.POST /bookings/{event_id}— takes ticket IDs and paymentDetails, and returns a booking ID.
Architecture#
flowchart LR
Client["📱 Client (Web/App)"] --> LB["Load Balancer"]
LB --> APIGW["API Gateway"]
APIGW --> ES["Event Service"]
APIGW --> SS["Search Service"]
APIGW --> BS["Booking Service"]
ES --> DB[("PostgreSQL DB\n(Events, Venues, Performers,\nTickets, Bookings)")]
SS --> DB
BS --> DB
BS <--> Stripe["Payment Processor\n(Stripe)"]
Event service#
- This will be our first service to handle fetching event details.
- Returning details such as event, ticket map, venue, performer, etc.
Search service#
- Since the searching is very important for us and searching queries can get complicated in the future, we will create it as a separate service.
- We will add more search features, which will have their own dependencies.
- But you can start, but at the start, you don’t have to create this service since, in the beginning, searching will be simpler.
Booking service#
- Interfaces with External payment providers (like Stripe) and runs a database transaction to check ticket availability, mark tickets as “booked,” and create a new record in the Bookings table.
- To prevent Two users from booking the same ticket, ee have to use databases that support transaction.
When a user tries to book a ticket
- User is directed to the payment provider to make a payment.
- If the payment is successful
- Then the booking service will check if the
ticketis available (status isavailable, and notbooked). - Set the ticket status to
booked. - Create a new record in the
bookingtable.
- Then the booking service will check if the
- If the transaction fails Because the ticket was booked by someone else in between.
- The first step in the above fail, which is checking if the
ticketis still available . - And we will send an error to the user.
- The first step in the above fail, which is checking if the
The main issue with this approach is that even after payment, the user might get the error that the ticket is no longer available. The refund can take a week. The user experience is not good.
Improving user experience#
The main problem here is that the user performs the payment before even ensuring that if payment is successful, the ticket will be booked successfully.
To tackle this, what we do before performing the payment is lock the ticket for the user.
There are many ways to perform this locking. Let’s see them one by one.
Locking DB row#
- When a user clicks a seat, the Booking Service opens a
PostgreSQLdatabase transaction and places a row level lock on that ticket (for example,using SELECT ... FOR UPDATE). - That database transaction, and the connection holding it, stays open for up to 10 minutes while the user enters their credit card details.
- Once payment succeeds, the service updates the ticket status to
boockedand commits the transaction, releasing the lock.
Because a database only has a limited number of concurrent connections (often a few hundred to a few thousand), what happens to our PostgreSQL database during a popular ticket drop if 50,000 users all hold open transactions for 10 minutes at the same time?
The database connection pool fills up, new requests pile up in the queue, and eventually the whole site times out or crashes.
So, this is not an ideal solution.
Cron job for unlocking#
- Instead of holding a database lock open for 10 minutes, we add status (
available,reserved,booked) andexpiration_timecolumns to the Tickets table. - When a user selects a seat, a quick transaction sets
status = 'reserved'andexpiration_time = now + 10mins, then immediately closes the connection. - A scheduled
cronjob runs periodically (say, every minute) to find any rows wherestatus = 'reserved'andexpiration_time < now, and resets them back to available.
This completely solves the connection exhaustion problem, which is why it’s a solid step up. However, relying on a periodic cron job introduces a couple of drawbacks.
- If our cron job runs every n minutes, There can be n minutes of delay for the for the
reservedticket to be seen asavailablefor other users.- which is, again, not an ideal solution for famous events.
- The cron job can crash.
Use filtering#
- We keep the statuses and
expiration_timecolumn used in above solution. - Instead of waiting for a job to reset expired rows, our database queries treat a ticket as
availablewheneverstatus = 'available' OR (status = 'reserved' AND expiration_time < NOW()). - The exact millisecond a 10-minute hold expires, the seat is immediately up for grabs by the next user, zero lag, and no background worker to crash.
But, during a massive flash sale, millions of users are rapidly clicking seats and triggering temporary holds, even if most of them never finish paying.
The problem here is
- Writing every temporary reservation directly to PostgreSQL creates heavy write contention on the database.
- Our read queries have gotten a little expensive.
- Logic for checking available tickets has gotten complex, it has to be replicated/copied everywhere.
Distributed TTL Lock#
- When a user selects a seat, the
Booking Service- Acquires lock on that
ticket_idinRedis(or other in memory stores) with a 10-minuteTTL. - This step will fail if that ticket ID is already locked, and the user will get an error.
- Acquires lock on that
- If the user abandons checkout, Redis automatically deletes the lock after 10 minutes, no cron job required, and no cleanup load on PostgreSQL.
- While the lock is active, the
Booking Servicecreates anin-progressbooking inPostgreSQLBookingtable, and the user performs payment (which tokenizes card details so our servers never touch raw credit card numbers). - Once payment succeeds,
Stripenotifies our backend via a webhook, and our server updates the ticket toBookedand theBookingtoconfirmed.
While a user is on the payment page, PostgreSQL still lists the ticket as available, because the temporary hold only lives in Redis. To show those locked seats as unavailable on the seat map, the Event Service merges both sources of truth when serving GET /events/{event_id}
- Query the Tickets table for the event to see which seats are permanently sold vs. available.
- Query
Redisin a single round trip (for example, usingMGETon theticket_idkeys, or reading an event specific set of locked tickets) to find which tickets currently have an active 10-minute lock. - Any ticket that is available in PostgreSQL and present in
Redisgets flipped to unavailable in the JSON payload sent to the client.
Scaling Reads#
As we noted down in the non-functional requirement, availability and fast, low latency reading of events is important to us.
- Aggressively caching static or slow changing data like event details, venue info, and seating charts.
- Spreading incoming read traffic evenly across servers.
- pinning up more stateless Event Service instances to absorb the spike.
Using Server-Sent Events (SSE) works fine for smaller events, but it breaks down during a 10-million-user flash sale for three main reasons:
- Massive Connection Overhead: SSE requires keeping a persistent, long-lived HTTP connection open for every user viewing the page. Holding 10 million open connections simultaneously consumes huge amounts of server memory and resources.
- The Fan-Out Storm: Every time one seat is locked or sold, the server has to broadcast that update to every connected user. If 1,000 seats change in a single second, pushing those updates to 10 million listeners means blasting out 10 billion messages per second, which crushes CPU and network bandwidth.
- Still a Frustrating UX: Even if SSE updates arrived with zero lag, seats disappear faster than human reaction time. By the time you see a green seat, move your mouse, and click, someone else already grabbed it, so you still hit constant “seat unavailable” errors.
Using virtual queues for better UX#
To fix problem we have with SSE, instead of letting all 10 million people onto the seat map at once, users are placed in a lightweight waiting room and let onto the booking page in small, controlled batches.
Users land on a lightweight waiting-room page that tracks their spot in line (often using an in-memory queue like Redis). As people finish buying or leave the seat map, the system lets the next small batch through.
The idea is, snstead of frantically clicking disappearing seats for 30 minutes and hitting error screens, users see their queue position right away and get a clean “Sold Out” update if tickets run out.
The users at the front of the line get a fast, crash free seat map instead of everyone fighting a frozen server.
In practice, when a user reaches the front of the queue, the system issues them a short-lived, signed queue pass (token). If someone pastes /events/123 directly into their browser without a valid pass, the API Gateway or Event Service redirects them straight back to the waiting room.
When a user is in the queue, we create a persistent SSE connection. When the given user is dequeued to book an available ticket, we send an message “you can book now” via that SSE connection.
flowchart LR
Client["📱 Client (Web/App)"] --> LB["Load Balancer"]
LB --> APIGW["API Gateway"]
APIGW -- "Popular event spike" --> VWQ["Virtual Waiting Queue\n(Issues Queue Pass)"]
VWQ -. "Admits in batches" .-> APIGW
APIGW --> ES["Event Service"]
APIGW --> SS["Search Service"]
APIGW --> BS["Booking Service"]
ES --> Cache[("⚡ Event Cache\n(Details & Seat Map)")]
ES --> RedisLock[("Redis Distributed Lock\n(10-min TTL)")]
ES --> DB[("PostgreSQL DB\n(Events, Venues, Performers,\nTickets, Bookings)")]
SS --> DB
BS --> RedisLock
BS --> DB
BS <--> Stripe["Stripe\n(Payments & Webhooks)"]
Improving search#
Notice that the Search Service is the last piece still hitting PostgreSQL directly.
If the Search Service runs WHERE name LIKE '%foo%', why does that leading % wildcard prevent PostgreSQL from using a standard index on name, forcing a slow full table scan instead?
So, to improve searching, we can use solutions which are created just for that, like Elasticsearch.
Offloading search to a dedicated full-text search engine that uses an inverted index (like the index at the back of a textbook, mapping every word like “foo” directly to the list of matching event IDs).
Adding Elasticsearch makes search blazingly fast, but it introduces a new architectural challenge: our primary source of truth for events is still PostgreSQL.
Apart from fast searching operations, Elasticsearch provides other features as well, like fuzzy search, stemming, etc.
To keep Elasticsearch in sync with our Postgres, we have to use things like CDC, which can capture things like update inserts in Postgres and reflect them in Elasticsearch.
Caching frequently repeated searches, in Redis or at the CDN edge so the search cluster doesn’t even get hit for popular queries.
flowchart LR
Client["📱 Client (Web/App)"] --> LB["Load Balancer"]
LB --> APIGW["API Gateway"]
APIGW -- "Popular event spike" --> VWQ["Virtual Waiting Queue\n(Issues Queue Pass)"]
VWQ -. "Admits in batches" .-> APIGW
APIGW --> SS["Search Service"]
APIGW --> ES["Event Service"]
APIGW --> BS["Booking Service"]
subgraph SearchLayer["Search Layer"]
SearchCache[("⚡ Search & Edge Cache\n(Popular Queries)")]
Elastic[("Elasticsearch\n(Full-Text Index)")]
end
SS --> SearchCache
SS --> Elastic
ES --> EventCache[("⚡ Event Cache\n(Details & Seat Map)")]
ES --> RedisLock[("Redis Distributed Lock\n(10-min TTL)")]
ES --> DB[("PostgreSQL DB\n(Events, Venues, Performers,\nTickets, Bookings)")]
BS --> RedisLock
BS --> DB
BS <--> Stripe["Stripe\n(Payments & Webhooks)"]
DB --> CDC["CDC\n(Debezium / Kafka)"] --> Elastic