BookMyShow clone: movie seat booking
Browse movies and showtimes, pick seats on a real seat map, hold them for 8 minutes while paying, and get a QR ticket. Two people can never book the same seat.
Educational project inspired by BookMyShow. Skills101 is not affiliated with BookMyShow. Give your app its own name and logo, and do not copy their branding or content.
What you’ll learn
- ◆Temporary seat holds with Redis expiry and Lua scripts
- ◆Database unique constraints as the final guarantee
- ◆Payment edge cases (paid after the hold expired)
- ◆Signed QR tickets and one-time check-in
What you’ll build
- ✓Cities, movies, theatres and showtimes
- ✓Seat map with categories, prices and live availability
- ✓8-minute hold with countdown, then payment
- ✓QR ticket by email and a scanner page
Before you start
What you need
- •React/Next.js and SQL basics.
- •Node.js 20+, PostgreSQL and Redis (Docker).
- •Razorpay TEST keys for the payment step.
How it fits together
- 1Next.js pages for listings, seat map and checkout; Prisma with PostgreSQL for movies, shows and bookings.
- 2Seat holds live in Redis with an 8-minute expiry, created all-or-nothing by a Lua script.
- 3Confirmed seats are rows in PostgreSQL with UNIQUE (showId, seatId), so the database itself refuses double booking.
- 4Tickets carry an HMAC-signed code in a QR; the scanner page checks it and marks it used once.
Project structure
showtime/
├─ prisma/schema.prisma, seed.ts
├─ src/app/
│ ├─ [city]/page.tsx # movies in city
│ ├─ movie/[slug]/page.tsx # showtimes by theatre
│ ├─ show/[id]/seats/page.tsx # seat map
│ ├─ checkout/[holdId]/page.tsx
│ ├─ tickets/[id]/page.tsx # QR
│ └─ scan/page.tsx # staff only
└─ src/lib/ (holds.lua, holds.ts, payments.ts, tickets.ts)Step-by-step guide
Step 1
Plan the booking flow
Goal: The screens from city to ticket and the rules for holds.
Flow: choose city → movie → date and showtime → seats → hold for 8 minutes → pay → ticket. Rules: max 10 seats per booking; holds expire automatically; a seat is unavailable if confirmed or held by someone else.
The core challenge: a hit movie's first-day show opens and hundreds of people tap the same middle seats. Your design must give each seat to exactly one person.
Name it (“ShowTime”) and add “Educational project inspired by BookMyShow. Not affiliated.” Use posters you made or with a free licence, not studio artwork.
✅ Check it works
You can explain what happens when two people tap seat F7 at the same moment.
Step 2
Design the schema with a unique seat constraint
Goal: Theatres, screens with seat layouts, shows, bookings and booked seats.
A Screen has a
layoutJSON: rows of seat codes, gaps for aisles, and a category per row (Recliner, Prime, Classic). A Show links a movie and a screen at a time, with prices per category in paise.BookedSeat(showId, seatId, bookingId)with UNIQUE (showId, seatId) is the final guarantee: even if every other part had a bug, the database cannot store two bookings for one seat.Booking status: PENDING_PAYMENT, CONFIRMED, FAILED. Store the amount, the Razorpay order id and the seat list.
prisma/schema.prisma (core)model Screen { id String @id @default(cuid()) theatreId String name String layout Json // { rows: [{ label: "A", category: "CLASSIC", seats: ["A1","A2",null,"A3"] }] } shows Show[] } model Show { id String @id @default(cuid()) movieId String screenId String screen Screen @relation(fields: [screenId], references: [id]) startsAt DateTime prices Json // { "CLASSIC": 20000, "PRIME": 28000, "RECLINER": 50000 } in paise bookings Booking[] @@index([movieId, startsAt]) } model Booking { id String @id @default(cuid()) showId String show Show @relation(fields: [showId], references: [id]) userId String seats String[] amountPaise Int status String // PENDING_PAYMENT | CONFIRMED | FAILED razorpayId String? @unique checkedInAt DateTime? booked BookedSeat[] createdAt DateTime @default(now()) } model BookedSeat { showId String seatId String bookingId String booking Booking @relation(fields: [bookingId], references: [id]) @@id([showId, seatId]) // one booking per seat per show, enforced by the database }✅ Check it works
Inserting the same (showId, seatId) twice by hand fails with a unique-constraint error.
Step 3
Listings: movies, theatres and showtimes
Goal: Fast pages for “movies in Jaipur” and “showtimes for this movie on Saturday”.
City page: movies with at least one show in the next 7 days in that city. Movie page: a date strip (today + 6 days), then theatres with their showtimes as buttons, coloured by availability (green = plenty, amber = filling fast, grey = full).
These pages change slowly; cache them for 60 seconds (Next.js
revalidate). Seat availability, which changes every second, is loaded separately on the seat page.Hide shows that have started (or start within 15 minutes).
✅ Check it works
The movie page lists only future shows for the selected city and date.
Step 4
Draw the seat map
Goal: An accurate, accessible seat grid with categories, prices, and booked/held/selected states.
Render the layout JSON: each row is a line of buttons,
nullentries are aisle gaps, row labels on both sides, “SCREEN THIS WAY” at the bottom. Group rows by category with the price above each group.States: available (outline), selected (filled), unavailable (grey and disabled: booked or held by someone else). Each seat is a
<button>with anaria-labellike “Seat F7, Prime, ₹280, available”, so it works with screen readers and keyboards.Load availability from
GET /api/shows/<id>/seats(booked from the database + held from Redis) and refresh it every 5 seconds while the page is open.src/app/show/[id]/seats/SeatMap.tsxtype Row = { label: string; category: string; seats: (string | null)[] } export function SeatMap({ rows, prices, taken, selected, onToggle }: { rows: Row[]; prices: Record<string, number>; taken: Set<string>; selected: Set<string>; onToggle: (seat: string) => void }) { return ( <div className="overflow-x-auto pb-4"> <div className="inline-block min-w-full space-y-1.5 px-2"> {rows.map((row) => ( <div key={row.label} className="flex items-center gap-1.5"> <span className="w-5 text-xs text-gray-500">{row.label}</span> {row.seats.map((seat, i) => seat === null ? <span key={row.label + i} className="w-7" aria-hidden /> // aisle gap : ( <button key={seat} type="button" disabled={taken.has(seat)} onClick={() => onToggle(seat)} aria-pressed={selected.has(seat)} aria-label={'Seat ' + seat + ', ' + row.category + ', ₹' + prices[row.category] / 100 + (taken.has(seat) ? ', unavailable' : '')} className={'h-7 w-7 rounded-t-md border text-[10px] ' + (taken.has(seat) ? 'cursor-not-allowed border-gray-200 bg-gray-200 text-gray-400' : selected.has(seat) ? 'border-green-600 bg-green-600 text-white' : 'border-green-600 text-green-700 hover:bg-green-50')}> {seat.slice(row.label.length)} </button> ))} </div> ))} <p className="mt-6 text-center text-xs tracking-widest text-gray-500">SCREEN THIS WAY</p> </div> </div> ) }✅ Check it works
On a phone, the map scrolls sideways inside its box (not the whole page) and seats are big enough to tap.
Step 5
Hold seats atomically with a Lua script
Goal: Selecting seats and pressing “Continue” holds all of them for 8 minutes, or none if any is taken.
If you check seats one by one and then set them, two users can both see F7 free. A Lua script runs inside Redis without interruption: first check every requested seat key is free (or already yours), then set them all with an 8-minute expiry. All-or-nothing.
Keys look like
hold:{show123}:F7. The{show123}part is a Redis Cluster hash tag: it keeps all seats of a show on the same server, which multi-key scripts require if you ever use a cluster.Also check the seats exist in the layout and are not already in BookedSeat before calling the script. The value stored is a hold id, so later steps can prove who owns the hold.
src/lib/holds.lua (+ call)-- KEYS = seat keys like hold:{show123}:F7 ; ARGV[1] = hold id ; ARGV[2] = ttl in ms for i, key in ipairs(KEYS) do local owner = redis.call('GET', key) if owner and owner ~= ARGV[1] then return 0 end end for i, key in ipairs(KEYS) do redis.call('SET', key, ARGV[1], 'PX', ARGV[2]) end return 1 -- Node: -- const keys = seats.map((s) => 'hold:{' + showId + '}:' + s) -- const ok = await redis.eval(HOLD_LUA, { keys, arguments: [holdId, String(8 * 60 * 1000)] })✅ Check it works
Two browsers select overlapping seats and press Continue at the same time: one gets all its seats, the other gets “Some seats were just taken” and keeps none.
Step 6
Countdown and releasing holds
Goal: The checkout shows “Complete payment in 07:42”, and cancelling frees the seats immediately.
Return the hold's expiry time from the server and count down from it. When it reaches 0, show “Time's up” and send the user back to the seat map.
If the user presses Back or Cancel, release the seats, but only the ones they own: a compare-and-delete script deletes a key only if its value equals their hold id. Otherwise a late cancel could free seats that someone else has held since.
If the user does nothing, Redis expiry frees the seats automatically; no cleanup job is needed.
src/lib/release.lua-- KEYS = seat keys ; ARGV[1] = hold id local freed = 0 for i, key in ipairs(KEYS) do if redis.call('GET', key) == ARGV[1] then redis.call('DEL', key) freed = freed + 1 end end return freed✅ Check it works
Cancel on the checkout page: the seats turn available for another user within 5 seconds.
Step 7
Pay and confirm, including the tricky edge case
Goal: Paid bookings become CONFIRMED exactly once, and late payments are handled correctly.
Create a PENDING_PAYMENT booking and a Razorpay order for the total. After payment, verify the signature on the server (see the Amazon guide). Then, in one database transaction, insert a BookedSeat row for every seat and set CONFIRMED. The unique constraint is the final check.
The edge case: the user pays at 7:59, the bank is slow, and the confirmation arrives after the 8-minute hold expired. If nobody took the seats, confirm anyway (the inserts succeed). If someone did, the insert fails on the unique constraint; mark the booking FAILED and refund in test mode, and tell the user clearly.
Handle the Razorpay webhook too, and make confirmation idempotent (only PENDING_PAYMENT → CONFIRMED), so the browser callback and the webhook arriving together do not cause errors.
src/lib/payments.ts (confirm)import { Prisma } from '@prisma/client' export async function confirmBooking(bookingId: string) { const booking = await db.booking.findUniqueOrThrow({ where: { id: bookingId } }) if (booking.status !== 'PENDING_PAYMENT') return booking.status // idempotent try { await db.$transaction([ db.bookedSeat.createMany({ data: booking.seats.map((seatId) => ({ showId: booking.showId, seatId, bookingId })) }), db.booking.update({ where: { id: bookingId, status: 'PENDING_PAYMENT' }, data: { status: 'CONFIRMED' } }), ]) await releaseHold(booking.showId, booking.seats, bookingId) // tidy up Redis await sendTicketEmail(bookingId) return 'CONFIRMED' } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') { await db.booking.update({ where: { id: bookingId }, data: { status: 'FAILED' } }) await refundInTestMode(booking) // seats went to someone else return 'FAILED' } throw e } }✅ Check it works
Simulate a late payment for seats someone else booked meanwhile: the booking becomes FAILED with a refund, and the other person keeps the seats.
Step 8
QR tickets and one-time check-in
Goal: A ticket page and email with a QR code that staff scan once at the entrance.
The QR contains
bookingId.signature, where the signature is an HMAC of the booking id with a server secret. Without the secret, nobody can create a valid code for another booking. Generate the image with theqrcodepackage (QRCode.toDataURL(text)).The staff scanner page uses the camera to read QR codes (for example with the
html5-qrcodelibrary), sends the text to the server, which checks the signature and then runsUPDATE … SET checkedInAt = now() WHERE id = $1 AND checkedInAt IS NULL. If no row changed, show “Already used at 6:42 pm” in red.Only staff accounts for that theatre can use the scanner.
src/lib/tickets.tsimport { createHmac, timingSafeEqual } from 'node:crypto' import QRCode from 'qrcode' const sig = (bookingId: string) => createHmac('sha256', process.env.TICKET_SECRET!).update(bookingId).digest('base64url').slice(0, 22) export const ticketQr = (bookingId: string) => QRCode.toDataURL(bookingId + '.' + sig(bookingId), { width: 280, margin: 1 }) export async function checkIn(code: string, staffTheatreId: string) { const [bookingId, given] = code.split('.') const good = Buffer.from(sig(bookingId ?? '')) if (!bookingId || !given || given.length !== good.length || !timingSafeEqual(good, Buffer.from(given))) { return { ok: false, reason: 'Not a valid ticket' } } const booking = await db.booking.findUnique({ where: { id: bookingId }, include: { show: { include: { screen: true } } } }) if (!booking || booking.status !== 'CONFIRMED') return { ok: false, reason: 'Booking not confirmed' } if (booking.show.screen.theatreId !== staffTheatreId) return { ok: false, reason: 'Ticket is for another theatre' } const res = await db.booking.updateMany({ where: { id: bookingId, checkedInAt: null }, data: { checkedInAt: new Date() } }) return res.count ? { ok: true, seats: booking.seats } : { ok: false, reason: 'Already used' } }✅ Check it works
Scanning a ticket twice shows green the first time and “Already used” the second; a hand-edited code is rejected.
Step 9
Load-test the seat hold and deploy
Goal: Proof that no seat is ever double booked, and a live demo.
Write a k6 test: 300 virtual users all try to hold the same 4 seats at once. Exactly one should succeed. Then 300 users each try random seats in a 200-seat show: count holds and confirm no seat appears twice.
Deploy the app, PostgreSQL and Redis; add the Razorpay TEST keys and webhook secret. Seed 2 cities, 4 theatres, 6 movies and a week of shows.
README: the flow diagram, the Lua hold script and why it is atomic, the unique-constraint safety net, the late-payment case, test results, and the not-affiliated note.
✅ Check it works
Your k6 run shows exactly 1 winner for the same seats, every time.
🚀 Make it stand out
- +Food and beverage add-ons at checkout
- +Seat suggestions: best available block of N seats in the middle
- +Waitlist that offers released seats
- +Theatre admin panel to create screens by drawing the layout