SyntaxPilot
Courses/System Design/Lesson 35
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

System Design · Lesson 35 of 40

Design IRCTC Tatkal booking

queued

These are the notes for System Design episode 35. Priya studies in Pune. Her mother calls: come home tomorrow. There's no time for a normal booking, so Priya needs a Tatkal ticket, and at exactly 10:00 she and lakhs of other people click Book on the same few berths. Today you design the system behind that moment: you'll write the requirements, measure the 10 am spike (75 tickets a minute on average vs 6,716 a minute from 10:00 to 10:10, 90x), watch two people both get the last berth (seats left: -1) and fix it with an atomic conditional update (seats left: 0), unblock a berth stuck forever by an unpaid hold (minute 60: Rahul: B1-23 is held by Priya) with a hold that expires, stop 2,00,000 time-outs and a refresh storm with a virtual waiting room (the last of 4 lakh people waits about 19 s), stop bots taking every berth (humans 0 → 45 of 50) with one try per verified ID, build a waitlist for a sold-out train, and turn Railways' numbers into 533 tickets a second today, 2,500 in the new system, and 66,667 enquiries a second. Every demo is plain Python and runs as-is; outputs are real (Python 3.13). Priya, Rahul, Asha, Neha, Vikram and the berth numbers are fictional; the 4 lakh requests in the first second, the 20,000-a-second capacity, the 10-minute hold and the 60 humans / 5 bots demo are our own assumptions; the real-world facts come only from the sources at the end.

IRCTC (Indian Railway Catering and Tourism Corporation, general knowledge) runs Indian Railways' online ticket booking. Tatkal is its last-minute quota of tickets, booked in a short window the day before the journey (general knowledge). Example: Priya books a Tatkal berth today for tomorrow's train home.

The problems

Problem What it teaches
Priya needs to go home tomorrow Requirements: search, book, pay, waitlist; survive 10:00; never sell a berth twice; be fair
The 10 am spike Design for the peak, not the average: 75 → 6,716 tickets a minute (90x)
Two people, one berth Race conditions; one atomic conditional update in the database; rowcount
The berth stuck forever Holds (leases) with an expiry; hold → pay → confirm, or expire
Four lakh in one second Time-outs and refresh storms; a virtual waiting room that admits N a second
Bots take every berth Limit per ID, and the ID must be verified (Aadhaar; agents wait 30 minutes)
Sold out A waitlist: a first-come-first-served queue, promoted atomically on cancellation
The scale 32,000 → 1.5 lakh tickets a minute; 40 lakh enquiries a minute; reads ≫ writes
Put it all together Waiting room → booking service → inventory database → payment, plus caches and a waitlist

Problem 0: Priya needs to go home tomorrow (requirements)

Tatkal booking for AC classes opens at 10 am, and for non-AC classes at 11 am (the News On AIR report gives the agents' blocked windows as "AC classes from 10 AM to 10:30 AM and ... non-AC classes from 11 AM to 11:30 AM"). At exactly 10:00, Priya and lakhs of other people click Book: the same trains, the same coaches, the same few berths.

A few words first:

  • A berth is one sleeping place (one seat) on a train. Example: berth 23 in coach B1, written B1-23.
  • A coach is one carriage of the train. Example: coach B1.
  • AC / non-AC classes are air-conditioned and ordinary sleeper/seating classes; their Tatkal windows open at different times (10:00 and 11:00).
  • A functional requirement says what the system must do. Example: "book a berth".
  • A non-functional requirement says how well it must do it. Example: "survive a giant spike at 10:00".

Functional requirements:

  • Search trains and see how many seats are left.
  • Book a berth, pay, and get a confirmed ticket.
  • Sold out? Join the waitlist.

Non-functional requirements:

  • Survive a huge spike at exactly 10:00.
  • Never sell one berth to two people.
  • Fair: real people first, not bots.

Correct, then fast: a slow booking page is annoying, but one berth sold to two passengers is a disaster on the platform.

Problem 1: the 10 am spike

How bad is the spike? Railways data from June 2025 (Free Press Journal): "an average of 67,159 tickets were booked online within the first 10 minutes of the window opening", "representing 62.5% of all tickets booked online" for AC Tatkal. Let's compare that with a calm day.

first_10_min = 67_159        # AC Tatkal tickets online, first 10 minutes
share = 0.625                # = 62.5% of the day's AC Tatkal online
per_day = first_10_min / share

calm = per_day / (24 * 60)   # if bookings were spread over the day
rush = first_10_min / 10     # what really happens at 10:00
print(f"AC Tatkal online per day: {per_day:,.0f}")
print(f"spread evenly: {calm:,.0f} tickets a minute")
print(f"10:00 to 10:10: {rush:,.0f} tickets a minute")
print(f"the rush is {rush / calm:,.0f}x the average")

Output:

AC Tatkal online per day: 107,454
spread evenly: 75 tickets a minute
10:00 to 10:10: 6,716 tickets a minute
the rush is 90x the average
  • 67,159 is 62.5% of the day, so the whole day is 67,159 ÷ 0.625 = 1,07,454 AC Tatkal tickets online.
  • Spread evenly over 24 × 60 = 1,440 minutes, that's just 75 a minute. But from 10:00 to 10:10 it's 67,159 ÷ 10 = 6,716 a minute: 90 times the average, all in ten minutes.
  • Non-AC is the same story: "Approximately 66.4% of tickets were sold within the first 10 minutes" (same report).
  • A system sized for the average would collapse at 10 am.

The words:

  • The average load is the total spread evenly over time; the peak is the busiest period's load. Example: 75 vs 6,716 tickets a minute.
  • A flash crowd is a huge number of users arriving at the same moment for the same thing. Example: everyone clicking Book at 10:00:00. Rule: design for the peak, not the average.

Problem 2: two people, one berth (race conditions and atomic updates)

Real life: the last samosa

At the canteen In the booking system
Two friends see one samosa left: "it's mine" Check: seats_left > 0, and both see 1
Both reach for it at the same moment Book: seats_left - 1, and both subtract
Both get billed: one samosa, two bills Double booking: seats left: -1

In booking, that's the worst bug there is: two passengers, one berth. Let's see if our code does this.

  • A thread is a separate line of work running at the same time inside one program, like a separate worker. Example: one thread books for Priya while another books for Rahul, the way two servers would handle them.
  • time.sleep(0.01) pauses for 10 milliseconds; here it pretends the server is busy for a moment between the check and the booking. Real servers pause like this all the time (waiting for the network, the disk, other requests).
  • global seats_left lets the function change the variable defined outside it; join() waits for a thread to finish.
import threading, time
seats_left = 1                 # the last berth in coach B1

def book(name):
    global seats_left
    if seats_left > 0:         # 1. check
        time.sleep(0.01)       #    (the server is busy for a moment)
        seats_left -= 1        # 2. then book
        print(name, "got the berth!")

people = [threading.Thread(target=book, args=(n,))
          for n in ["Priya", "Rahul"]]
for p in people: p.start()
for p in people: p.join()
print("seats left:", seats_left)

Output:

Priya got the berth!
Rahul got the berth!
seats left: -1
  • Both got the berth, and seats left is −1. We sold one berth to two people.
  • Why? Both threads checked while the count was still 1. Then both subtracted.
  • A race condition is a bug where the result depends on who runs first, and two workers interleave in a bad order. Example: both check "1 left" before either books.
  • This pattern, read a value, decide, then write, is called check-then-act. Check, then act = a race.
  • A lock (a rule that only one thread at a time may run a piece of code) inside one Python program wouldn't help here, because the real system runs on many servers: a lock in one server's memory means nothing to the others.

The fix: one atomic step in the database

Let the database do the check and the booking in one single step. Every server talks to the same database.

  • SQLite is a small SQL database that lives in a single file and comes built into Python (import sqlite3). Example: train.db holds a table coach with one row ('B1', 1).
  • A commit makes a change permanent and visible to everyone else.
  • A conditional update is an UPDATE that changes a row only WHERE a condition still holds. Example: subtract one only where seats_left > 0.
  • rowcount is the number of rows a statement changed. Example: 1 = you got the berth, 0 = sold out.
  • timeout=5 tells SQLite to wait up to 5 seconds if another connection is writing, instead of failing at once.
import sqlite3, threading
db = sqlite3.connect("train.db")
db.execute("DROP TABLE IF EXISTS coach")
db.execute("CREATE TABLE coach (name TEXT, seats_left INT)")
db.execute("INSERT INTO coach VALUES ('B1', 1)")
db.commit()

def book(name):
    con = sqlite3.connect("train.db", timeout=5)
    cur = con.execute(          # check + book in ONE step
        "UPDATE coach SET seats_left = seats_left - 1 "
        "WHERE name = 'B1' AND seats_left > 0")
    con.commit()
    ok = cur.rowcount == 1      # 1 row changed = you got it
    print(name, "got the berth!" if ok else "sorry, sold out")

people = [threading.Thread(target=book, args=(n,))
          for n in ["Priya", "Rahul"]]
for p in people: p.start()
for p in people: p.join()
left = db.execute("SELECT seats_left FROM coach").fetchone()[0]
print("seats left:", left)

Output (it creates train.db in the current folder; which of the two wins can change from run to run, but exactly one always does):

Priya got the berth!
Rahul sorry, sold out
seats left: 0
  • Priya got the berth. Rahul: sorry, sold out. Seats left: 0. Exactly right.
  • The database runs the UPDATE as one indivisible step: while it checks seats_left > 0 and subtracts, nobody can sneak in between. The second update then finds seats_left = 0, changes 0 rows, and rowcount tells Rahul the truth.
  • An operation is atomic when it happens completely or not at all, with nothing in between. Example: this conditional update. You just invented atomic booking: check + book in one step.

Two traps that look like the fix

Trap 1: read in SQL, decide in Python, write back. The database is there, but the check and the write are still two steps:

import sqlite3, threading, time
db = sqlite3.connect("train.db")
db.execute("DROP TABLE IF EXISTS coach")
db.execute("CREATE TABLE coach (name TEXT, seats_left INT)")
db.execute("INSERT INTO coach VALUES ('B1', 1)")
db.commit()

def book(name):
    con = sqlite3.connect("train.db", timeout=5)
    left = con.execute("SELECT seats_left FROM coach").fetchone()[0]
    if left > 0:                       # check in Python...
        time.sleep(0.01)
        con.execute("UPDATE coach SET seats_left = ?", (left - 1,))
        con.commit()                   # ...then write: two steps
        print(name, "got the berth!")

people = [threading.Thread(target=book, args=(n,))
          for n in ["Priya", "Rahul"]]
for p in people: p.start()
for p in people: p.join()
left = db.execute("SELECT seats_left FROM coach").fetchone()[0]
print("seats left:", left)

Output:

Priya got the berth!
Rahul got the berth!
seats left: 0

This one is sneakier: the count says 0, which looks right, but two people were told they got the berth. Both read 1, both wrote 1 − 1 = 0. (Overwriting someone else's change like this is called a lost update.)

Trap 2: the right UPDATE, but never looking at rowcount.

import sqlite3, threading
db = sqlite3.connect("train.db")
db.execute("DROP TABLE IF EXISTS coach")
db.execute("CREATE TABLE coach (name TEXT, seats_left INT)")
db.execute("INSERT INTO coach VALUES ('B1', 1)")
db.commit()

def book(name):
    con = sqlite3.connect("train.db", timeout=5)
    con.execute("UPDATE coach SET seats_left = seats_left - 1 "
                "WHERE name = 'B1' AND seats_left > 0")
    con.commit()
    print(name, "got the berth!")      # rowcount never checked

people = [threading.Thread(target=book, args=(n,))
          for n in ["Priya", "Rahul"]]
for p in people: p.start()
for p in people: p.join()
left = db.execute("SELECT seats_left FROM coach").fetchone()[0]
print("seats left:", left)

Output:

Priya got the berth!
Rahul got the berth!
seats left: 0

The database did the right thing (Rahul's update changed 0 rows), but the app ignored the answer and told Rahul he has a ticket. The update and the rowcount check go together.

And one error you will meet: if a connection writes but never commits, it keeps the database locked, and other writers wait for timeout seconds and then fail:

import sqlite3
db = sqlite3.connect("train.db")
db.execute("DROP TABLE IF EXISTS coach")
db.execute("CREATE TABLE coach (name TEXT, seats_left INT)")
db.execute("INSERT INTO coach VALUES ('B1', 2)")
db.commit()

priya = sqlite3.connect("train.db", timeout=0.1)
priya.execute("UPDATE coach SET seats_left = seats_left - 1 "
              "WHERE seats_left > 0")          # ...but never commits
rahul = sqlite3.connect("train.db", timeout=0.1)
rahul.execute("UPDATE coach SET seats_left = seats_left - 1 "
              "WHERE seats_left > 0")

Output (file path in the traceback shortened to main.py):

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    rahul.execute("UPDATE coach SET seats_left = seats_left - 1 "
    ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                  "WHERE seats_left > 0")
                  ^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: database is locked

A transaction (a group of changes that become permanent together at the commit, episode 9) holds its locks until it commits. Keep booking transactions short, and always commit (or roll back).

Problem 3: the berth stuck forever (holds that expire)

Booking has a payment step, and payment takes time. So we hold the berth for Priya while she pays. But what if her payment hangs, and she closes the app?

  • A hold is a temporary reservation of a berth for one person while they pay. Example: B1-23 is held for Priya.
seats = {"B1-23": None}          # berth -> who holds it

def hold(berth, name):
    if seats[berth] is None:
        seats[berth] = name      # held... until she pays
        return f"{name} holds {berth}"
    return f"{name}: {berth} is held by {seats[berth]}"

print(hold("B1-23", "Priya"))    # Priya goes to pay... then quits
for minute in [5, 30, 60]:
    print(f"minute {minute}:", hold("B1-23", "Rahul"))

Output:

Priya holds B1-23
minute 5: Rahul: B1-23 is held by Priya
minute 30: Rahul: B1-23 is held by Priya
minute 60: Rahul: B1-23 is held by Priya
  • Held by Priya. Held by Priya. Still held by Priya after an hour. The train leaves tomorrow, and a berth sits empty that someone else wanted.
  • Why? The hold has no end. Nobody ever lets the berth go. A hold needs an end.

Real life: keeping a seat in the cinema

In a cinema In booking
"Keep my seat, I'll be back": a bag on the seat Hold: berth reserved for Priya
Not back when the film starts? The usher gives it away Expiry: the hold ends after 10 minutes (our demo's number)
Back in time and paid: the seat is yours Confirm: payment done → ticket; the hold becomes a booking
  • An expiry is the time at which a hold ends on its own. Example: "until minute 10".
  • A lease is the general name for a hold that expires on its own unless it's confirmed or renewed. Example: a 10-minute lease on B1-23.

The fix: store "who" and "until"

Each hold now stores who holds the berth and until when. A berth is free if nobody holds it, or if the old hold has run out. Ten minutes is just our own number for this demo.

HOLD_MINUTES = 10                # our own number for this demo
seats = {"B1-23": None}          # berth -> (who holds it, until)

def hold(berth, name, now):
    h = seats[berth]
    if h is None or h[1] <= now: # free, or the old hold expired
        seats[berth] = (name, now + HOLD_MINUTES)
        return f"{name} holds {berth} until minute {now + HOLD_MINUTES}"
    return f"{name}: {berth} is held by {h[0]}"

print(hold("B1-23", "Priya", now=0))   # her UPI app hangs...
print(hold("B1-23", "Rahul", now=4))   # inside Priya's hold
print(hold("B1-23", "Rahul", now=11))  # expired: free again

Output:

Priya holds B1-23 until minute 10
Rahul: B1-23 is held by Priya
Rahul holds B1-23 until minute 21
  • Priya holds it until minute 10. At minute 4, Rahul is told it's held. At minute 11, the hold has expired, and Rahul gets the berth.
  • The flow is: hold → pay → confirm, or expire. In a real system the hold itself is also one atomic conditional update in the database (... WHERE status = 'free' OR until <= now), like Problem 2; the mini project below does exactly that.
  • And if the payment fails after the money left Priya's account, the refund flow (money sent back, the reversal from the UPI episode, 34) takes over.

You just invented seat holds with an expiry.

Problem 4: four lakh in one second (a virtual waiting room)

Now the crowd itself. Say 4 lakh requests arrive in the first second (our own guess). Say the booking servers can handle 20,000 a second, and a browser gives up after 10 seconds (both our guesses).

  • Capacity is the most work a system can do per second. Example: 20,000 requests a second.
  • A timeout is when the caller stops waiting after a fixed time and shows an error. Example: the browser gives up after 10 s.
  • A lakh is 1,00,000 (one hundred thousand) and a crore is 1,00,00,000 (ten million), Indian number words. Example: 4 lakh = 400,000.
arrive = 400_000      # requests in the first second (our guess)
capacity = 20_000     # requests served per second (our guess)
timeout = 10          # seconds before a browser gives up

served = capacity * timeout    # the most served before time-outs
print(f"served in time: {served:,}")
print(f"timed out: {arrive - served:,}")
print("...and each one presses refresh: the next second is worse")

Output:

served in time: 200,000
timed out: 200,000
...and each one presses refresh: the next second is worse
  • In 10 seconds the servers finish 20,000 × 10 = 2 lakh; the other 2 lakh time out. Half the people see an error page.
  • And what does everyone do after an error? Press refresh. Each refresh is a brand-new request, so the next second is even worse, and the servers spend their time on requests that will time out anyway. This is a refresh storm (also called a retry storm): failures causing more load, causing more failures. Refresh = more load.

Real life: the token at the bank

At a bank branch On the website
Take a token: your number is kept Place in line: "you are number 1,23,457"; fair order
The screen calls a few numbers at a time Admit N a second: only what the servers can handle; steady load
Sit and wait calmly, no pushing at the counter Waiting-room page: cheap to serve; no refresh storm

A virtual waiting room is a simple, cheap web page that gives each arriving user a place in a line and lets them through to the real booking servers at a fixed rate. Example: number 1,23,457 waits about 6 seconds, then reaches the booking page. (This is a common design for flash crowds and our design choice here; the episode's sources don't describe how IRCTC handles it.)

capacity = 20_000      # let into booking per second (our guess)
line = [f"user{i}" for i in range(400_000)]  # a place each, in order

def status(position):  # what the waiting-room page shows
    wait = position // capacity
    return f"number {position + 1:,} in line, about {wait} s"

for who in [0, 123_456, 399_999]:
    print(line[who] + ":", status(who))
print("refresh keeps your place; servers see 20,000 a second")

Output:

user0: number 1 in line, about 0 s
user123456: number 123,457 in line, about 6 s
user399999: number 400,000 in line, about 19 s
refresh keeps your place; servers see 20,000 a second
  • Number 1: no wait. Number 1,23,457: 123,456 ÷ 20,000 → about 6 s. The very last person, number 4 lakh: about 19 s.
  • // is whole-number division (it drops the remainder): 123_456 // 20_000 is 6.
  • Nobody gets an error page, and refreshing doesn't lose your place (the place is tied to a token, a small ticket the waiting room gives your browser, not to the request). The booking servers only see a steady 20,000 a second.
  • Letting through only N requests a second is a form of rate limiting (episode 19): limiting how many requests are accepted per unit of time.

A short wait beats a crash. You just invented a virtual waiting room.

Problem 5: bots take every berth (one try per verified ID)

A bot is a program that logs in and books automatically, far faster than any human. Railways said in June 2025 (DeshGujarat) that "Bot traffic accounts for up to 50% of overall login attempts" in the first five minutes of Tatkal booking.

Our demo (our own numbers): 60 humans try once each. 5 bot accounts try 20 times each, and they're faster, so they arrive first. There are 50 berths. First with no limit, then with one try per ID.

  • A user ID is the account a person logs in with. Example: human7, bot3.
  • A limit per ID is the most tries one account may make. Example: limit_per_id=1.
  • requests.sort(key=lambda r: r.startswith("human")) sorts by False (bots) before True (humans), so the bots arrive first.
humans = [f"human{i}" for i in range(60)]  # 60 people, 1 try each
bots = [f"bot{i}" for i in range(5)]       # 5 bots, 20 tries each
requests = humans + bots * 20
requests.sort(key=lambda r: r.startswith("human"))  # bots: first

def admit(reqs, limit_per_id=None):
    seen, admitted = {}, []
    for r in reqs:
        seen[r] = seen.get(r, 0) + 1
        if limit_per_id is None or seen[r] <= limit_per_id:
            admitted.append(r)
    return admitted[:50]                   # 50 berths

for limit in [None, 1]:
    got = admit(requests, limit)
    people = sum(r.startswith("human") for r in got)
    print(f"limit per ID {limit}: humans got {people} of 50")

Output:

limit per ID None: humans got 0 of 50
limit per ID 1: humans got 45 of 50
  • No limit: humans got 0 of 50. The bots' 100 fast tries fill all 50 berths.
  • One try per ID: humans got 45 of 50. Each bot account gets 1 try (5 berths), and the other 45 go to people.

The catch: fake IDs

A bot owner can simply make many accounts. Same 60 humans, but now the 5 bots use 20 fake IDs each:

humans = [f"human{i}" for i in range(60)]        # 60 people, 1 try each
bots = [f"bot{b}-id{k}" for b in range(5) for k in range(20)]  # 100 fake IDs
requests = bots + humans                         # bots: first

def admit(reqs, limit_per_id=None):
    seen, admitted = {}, []
    for r in reqs:
        seen[r] = seen.get(r, 0) + 1
        if limit_per_id is None or seen[r] <= limit_per_id:
            admitted.append(r)
    return admitted[:50]                         # 50 berths

got = admit(requests, 1)
people = sum(r.startswith("human") for r in got)
print(f"limit per ID 1, 100 fake IDs: humans got {people} of 50")

Output:

limit per ID 1, 100 fake IDs: humans got 0 of 50

Back to 0. A limit per ID only works if each ID belongs to one real person. So the ID itself must be verified. What Railways did (sources at the end):

  • "2.5 crore suspected user IDs have been deactivated" (DeshGujarat, June 2025).
  • Aadhaar-based authentication became mandatory for online Tatkal bookings from 1 July 2025, with Aadhaar OTP from 15 July 2025 (News On AIR).
  • Authorised agents "will not be permitted to book opening-day Tatkal tickets during the first 30 minutes" (News On AIR).

The words:

  • Aadhaar is India's 12-digit identity number for residents (general knowledge). Aadhaar authentication means proving that an account belongs to the real person with that Aadhaar number. Example: the account is linked to Priya's Aadhaar and checked before she can book Tatkal.
  • An OTP (one-time password) is a short code sent to your phone that works only once. Example: a 6-digit code Priya types to prove it's her.
  • An authorised agent is a registered travel agent who books tickets for customers; they may not book in the first 30 minutes of the window.
  • To deactivate an account means switching it off so it can't log in.

Limit per verified ID. You just invented fair access: one verified person, one try.

Problem 6: sold out (the waitlist)

The berths are gone. Asha, Neha and Vikram still want to travel. Instead of just saying "sold out", we put them on a waitlist: numbers one, two and three. When someone cancels, the first person on the waitlist gets that berth, and everyone moves up one place.

  • A waitlist is an ordered list of people waiting for a berth to free up. Example: Asha WL1, Neha WL2, Vikram WL3 (WL = waitlist number).
  • FIFO (first in, first out) means the one who joined first is served first. Example: WL1 gets the next berth.
  • A queue is a FIFO line of items. A deque ("deck", double-ended queue, from collections) is Python's fast queue: popleft() removes the first item in one quick step.
  • Cancel means giving up a confirmed berth; promote means moving the first waitlisted person onto it.
from collections import deque
confirmed = {"B1-23": "Priya", "B1-24": "Rahul"}  # coach full
waitlist = deque(["Asha", "Neha", "Vikram"])      # WL1, WL2, WL3

def cancel(berth):
    print(confirmed[berth], "cancels", berth)
    confirmed[berth] = waitlist.popleft()         # WL1 gets it
    print(confirmed[berth], "is now confirmed on", berth)
    for i, name in enumerate(waitlist, 1):
        print(f"  {name}: WL{i}")

cancel("B1-24")

Output:

Rahul cancels B1-24
Asha is now confirmed on B1-24
  Neha: WL1
  Vikram: WL2
  • Rahul cancels B1-24. Asha (WL1) is now confirmed. Neha moves up to WL1, Vikram to WL2.
  • A common slip is using a plain list with pop(), which takes the last item (LIFO, last in, first out):
confirmed = {"B1-23": "Priya", "B1-24": "Rahul"}
waitlist = ["Asha", "Neha", "Vikram"]          # WL1, WL2, WL3

print(confirmed["B1-24"], "cancels B1-24")
confirmed["B1-24"] = waitlist.pop()            # pop() takes the LAST one
print(confirmed["B1-24"], "is now confirmed on B1-24")

Output:

Rahul cancels B1-24
Vikram is now confirmed on B1-24

Vikram, the last to join, jumped the line. Use deque.popleft() (or list.pop(0)).

And the cancel and the promotion must also be one atomic step, or the berth could go to two people again: between "free the berth" and "give it to WL1", another booking could grab it (Practice 4 shows it). Cancel + promote, atomically. You just invented the waitlist.

Problem 7: the scale

The real numbers. In June 2025 Railways said the reservation system could book about 32,000 tickets a minute; the new PRS is being built for "over 1.5 lakh rail tickets per minute", and enquiries go from 4 lakh to "over 40 lakh enquiries per minute" (PIB, 29 June 2025).

  • PRS (Passenger Reservation System, general knowledge for the expansion) is Indian Railways' core system that holds every train's seats and books tickets.
  • An enquiry here is a request to see seat availability, without booking. Example: "how many berths are left in B1 tomorrow?"
now_tickets = 32_000     # tickets a minute (Railways, June 2025)
new_tickets = 150_000    # the new system's target, per minute
new_enquiry = 4_000_000  # availability enquiries a minute (target)

print(f"tickets today: {now_tickets / 60:,.0f} a second")
print(f"tickets, new system: {new_tickets / 60:,.0f} a second")
print(f"enquiries, new system: {new_enquiry / 60:,.0f} a second")
print(f"enquiries per ticket: about {new_enquiry / new_tickets:.0f}")

Output:

tickets today: 533 a second
tickets, new system: 2,500 a second
enquiries, new system: 66,667 a second
enquiries per ticket: about 27
  • 533 tickets a second today (32,000 ÷ 60); 2,500 a second in the new system (1,50,000 ÷ 60); 66,667 enquiries every second (40,00,000 ÷ 60).
  • About 27 enquiries for every ticket. For comparison, "the highest-ever per-minute booking of 31,814 tickets" was on 22 May 2025 (DeshGujarat), close to that 32,000-a-minute figure. And "Every day, around 2,25,000 passengers book Tatkal tickets through the online platform" (Free Press Journal).
  • Lots of reads, far fewer writes. So, in our design, availability is served from caches and read replicas, while bookings go to the database that does the atomic update.
  • A cache is a fast copy of data kept close to where it's needed (episode 7). Example: "B1: 12 berths left", refreshed every second, shown on the search page.
  • A read replica is a copy of the database that serves reads, kept up to date from the main one (episode 11). Example: search pages read from a replica; bookings write to the main database.
  • A cache or replica can be a moment out of date, which is fine for "about 12 left" on a search page, but never for deciding who gets a berth.

Reads ≫ writes: cache the reads.

The full design

  browser            waiting room          booking service         inventory DB        payment
  ───────            ────────────          ───────────────         ────────────        ───────
  10:00, Book ─────▶ token, place in line
  "number 1,23,457"◀─ admit N a second ──▶ verified ID? one try?
                                           (agents: not before 10:30)
                                           hold a berth ──────────▶ UPDATE ... WHERE free
                                                         ◀──────── rowcount 1: held until +10 min
                                           pay ─────────────────────────────────────────────▶ UPI / card
                                                         ◀──────────────────────────────────── paid
                                           confirm ──────────────▶ UPDATE ... WHERE held, not expired
  ticket ◀──────────────────────────────── confirmed
  search page ◀──── availability from caches and read replicas (a moment old is fine)
  sold out → waitlist queue; cancellation or expired hold → free + promote WL1 in ONE transaction
  1. At 10:00, users enter the waiting room, get a token and a place in line, and are let through at a rate the booking service can handle.
  2. The booking service lets in only verified IDs (Aadhaar authentication), one try each; agents wait 30 minutes.
  3. It holds a berth with one atomic conditional update in the inventory database (the database that holds every berth and its state), and the hold has an expiry (10 minutes in our design).
  4. The user pays (UPI or card); the booking service confirms with another conditional update that only succeeds if the hold is still alive.
  5. Holds expire: a failed or abandoned payment gives back both the berth and the money (refund).
  6. Seat availability for search comes from caches and read replicas.
  7. When it's sold out, users join a waitlist queue, promoted on every cancellation, with the cancel and the promotion in one transaction.

One rule above everything: the database, with one atomic step, decides who gets the berth. Never the app, never a cache. (These components are our design; the episode's sources don't describe IRCTC's internal architecture.)

The whole chain

  1. 75 → 6,716 tickets a minute: design for the peak, not the average.
  2. Seats left: −1 → an atomic conditional update, and check rowcount.
  3. A berth stuck forever → holds that expire.
  4. 2 lakh timed out, then a refresh storm → a virtual waiting room.
  5. Bots got 50 of 50 → one try per verified ID.
  6. Sold out → a waitlist queue, promoted atomically.
  7. 533 → 2,500 tickets a second, 66,667 enquiries a second → cache the reads; the database decides the writes.

Common mistakes (and the real outputs)

Mistake What you see Why Fix
if seats_left > 0: seats_left -= 1 seats left: -1 Two servers checked before either booked One atomic UPDATE ... WHERE seats_left > 0
SELECT the count, decide in Python, UPDATE it back Priya got the berth! Rahul got the berth! seats left: 0 Still check-then-act: a lost update Put the condition inside the UPDATE
The right UPDATE, but ignoring rowcount Rahul got the berth! and seats left: 0 The app ignored "0 rows changed" ok = cur.rowcount == 1
Write but never commit sqlite3.OperationalError: database is locked The open transaction keeps its lock Short transactions; always commit or roll back
A hold with no expiry minute 60: Rahul: B1-23 is held by Priya Abandoned payments never release Store an expiry time with every hold
Let everyone hit the servers at 10:00 timed out: 200,000 Load far above capacity, then refreshes A waiting room that admits N a second
Limit per ID, but IDs are free to create limit per ID 1, 100 fake IDs: humans got 0 of 50 One bot, many accounts Verified IDs (Aadhaar), deactivate suspected IDs
Waitlist as a list with pop() Vikram is now confirmed on B1-24 pop() takes the last one (LIFO) deque.popleft(): FIFO
Cancel, then promote, as two steps Karan paid for B1-24 too: two tickets, one berth (Practice 4) Another booking slipped in between Free + promote in one transaction

Mini project: a tiny Tatkal booking service

Berths in SQLite, held with one conditional UPDATE (and rowcount); holds that expire and a sweeper that frees them; a waiting room that admits 3 people a minute; verified IDs only, one try each, agents wait 30 minutes; a waitlist promoted in one transaction on cancellation or expiry; and a stress test with 20 threads racing for 3 berths. All numbers are our own, tiny on purpose:

# Mini project: a tiny Tatkal booking service. Berths live in SQLite and are
# held with ONE conditional UPDATE; holds expire; a waiting room admits a few
# people a minute; only verified IDs, one try each, agents wait 30 minutes;
# sold out -> a waitlist, promoted atomically. One process, a fake clock.
import sqlite3, threading
from collections import deque

HOLD_MINUTES = 10       # our own number
ADMIT_PER_MINUTE = 3    # waiting room rate (our own, tiny number)
AGENT_WAIT = 30         # agents may not book in the first 30 minutes

def setup(path):
    db = sqlite3.connect(path)
    db.executescript("""
        DROP TABLE IF EXISTS berths; DROP TABLE IF EXISTS waitlist;
        CREATE TABLE berths (berth TEXT PRIMARY KEY, status TEXT,
                             who TEXT, until INT);
        CREATE TABLE waitlist (pos INTEGER PRIMARY KEY AUTOINCREMENT,
                               name TEXT);
        INSERT INTO berths VALUES ('B1-21','free',NULL,NULL),
            ('B1-22','free',NULL,NULL), ('B1-23','free',NULL,NULL);""")
    return db

def hold(con, name, now):    # check + hold the first free berth, ONE step
    cur = con.execute("""
        UPDATE berths SET status = 'held', who = ?, until = ?
        WHERE berth = (SELECT berth FROM berths WHERE status = 'free'
                       ORDER BY berth LIMIT 1)
          AND status = 'free'""", (name, now + HOLD_MINUTES))
    con.commit()
    if cur.rowcount == 0:
        return None
    return con.execute("SELECT berth FROM berths WHERE who = ? AND "
                       "status = 'held'", (name,)).fetchone()[0]

def pay(con, name, now):     # confirm only if the hold is still alive
    cur = con.execute("""UPDATE berths SET status = 'booked'
        WHERE who = ? AND status = 'held' AND until > ?""", (name, now))
    con.commit()
    return "confirmed" if cur.rowcount == 1 else "hold expired, no ticket"

def free_and_promote(con, berth, guard, args, why):
    with con:                # free the berth AND give it to WL1: ONE transaction
        cur = con.execute("UPDATE berths SET status = 'free', who = NULL, "
                          "until = NULL WHERE berth = ? AND " + guard,
                          (berth, *args))
        if cur.rowcount == 0:
            return           # someone changed it first: do nothing
        row = con.execute("SELECT pos, name FROM waitlist "
                          "ORDER BY pos LIMIT 1").fetchone()
        if row:
            con.execute("DELETE FROM waitlist WHERE pos = ?", (row[0],))
            con.execute("UPDATE berths SET status = 'booked', who = ? "
                        "WHERE berth = ?", (row[1], berth))
    print(f"  {why}" + (f"; {row[1]} promoted from the waitlist" if row else ""))

def expire(con, now):        # the sweeper: free every hold past its end
    for (berth, who) in con.execute("SELECT berth, who FROM berths WHERE "
            "status = 'held' AND until <= ?", (now,)).fetchall():
        free_and_promote(con, berth, "status = 'held' AND until <= ?",
                         (now,), f"{who}'s hold on {berth} expired")

def cancel(con, name):
    berth = con.execute("SELECT berth FROM berths WHERE who = ? AND "
                        "status = 'booked'", (name,)).fetchone()[0]
    free_and_promote(con, berth, "status = 'booked' AND who = ?",
                     (name,), f"{name} cancels {berth}")

db = setup(":memory:")
verified = {"Priya", "Rahul", "Asha", "Neha", "Vikram", "Mehta"}  # Aadhaar done
agents = {"Mehta"}
tried = set()                 # IDs that already had their one try
room = deque(["Priya", "bot7", "Rahul", "Mehta", "Asha", "Neha",
              "Rahul", "Vikram"])            # arrivals at 10:00, in order
pays = {"Rahul": True, "Asha": True}         # Priya's UPI app hangs

for now in range(0, 25):
    if now in (0, 1, 2):
        print(f"minute {now}: waiting room has {len(room)}, "
              f"admitting {min(len(room), ADMIT_PER_MINUTE)}")
    for _ in range(min(len(room), ADMIT_PER_MINUTE)):
        name = room.popleft()
        if name not in verified:
            print(f"  {name}: ID not verified, rejected"); continue
        if name in agents and now < AGENT_WAIT:
            print(f"  {name}: agents wait until minute {AGENT_WAIT}"); continue
        if name in tried:
            print(f"  {name}: already had a try, rejected"); continue
        tried.add(name)
        berth = hold(db, name, now)
        if berth is None:
            db.execute("INSERT INTO waitlist (name) VALUES (?)", (name,))
            db.commit()
            n = db.execute("SELECT COUNT(*) FROM waitlist").fetchone()[0]
            print(f"  {name}: sold out, waitlisted WL{n}")
        else:
            print(f"  {name} holds {berth} until minute {now + HOLD_MINUTES}")
            if pays.get(name):
                print(f"  {name} pays: {pay(db, name, now)}")
    if now == 10:
        print("minute 10:")
    expire(db, now)
    if now == 12:
        print("minute 12: Priya's payment finally arrives:",
              pay(db, "Priya", now))
    if now == 20:
        print("minute 20:"); cancel(db, "Rahul")

print("berths:", db.execute("SELECT berth, status, who FROM berths").fetchall())
print("waitlist:", db.execute("SELECT name FROM waitlist").fetchall())

# stress test: 20 people press Book at the same moment, 3 berths
setup("tatkal.db").close()
def rush(name):
    con = sqlite3.connect("tatkal.db", timeout=5)
    hold(con, name, 0)
people = [threading.Thread(target=rush, args=(f"p{i}",)) for i in range(20)]
for p in people: p.start()
for p in people: p.join()
check = sqlite3.connect("tatkal.db")
held = check.execute("SELECT COUNT(DISTINCT who), COUNT(*) FROM berths "
                     "WHERE status = 'held'").fetchone()
print(f"stress: 20 people, 3 berths -> {held[1]} holds, {held[0]} different people")

Output (it creates tatkal.db in the current folder for the stress test):

minute 0: waiting room has 8, admitting 3
  Priya holds B1-21 until minute 10
  bot7: ID not verified, rejected
  Rahul holds B1-22 until minute 10
  Rahul pays: confirmed
minute 1: waiting room has 5, admitting 3
  Mehta: agents wait until minute 30
  Asha holds B1-23 until minute 11
  Asha pays: confirmed
  Neha: sold out, waitlisted WL1
minute 2: waiting room has 2, admitting 2
  Rahul: already had a try, rejected
  Vikram: sold out, waitlisted WL2
minute 10:
  Priya's hold on B1-21 expired; Neha promoted from the waitlist
minute 12: Priya's payment finally arrives: hold expired, no ticket
minute 20:
  Rahul cancels B1-22; Vikram promoted from the waitlist
berths: [('B1-21', 'booked', 'Neha'), ('B1-22', 'booked', 'Vikram'), ('B1-23', 'booked', 'Asha')]
waitlist: []
stress: 20 people, 3 berths -> 3 holds, 3 different people
  • The waiting room let in 3 people a minute, in arrival order: nobody got an error, and the booking code never saw more than 3 at once.
  • The gate rejected the unverified bot7, made the agent Mehta wait until minute 30, and turned away Rahul's second try.
  • Priya's hold expired at minute 10, and in the same transaction the berth went to Neha (WL1). When Priya's payment arrived at minute 12, the conditional UPDATE ... AND until > ? changed 0 rows, so she was told "hold expired, no ticket" (in a real system, the refund flow returns her money).
  • Rahul cancelled at minute 20 and Vikram was promoted in one transaction. Every berth ends up with exactly one passenger.
  • The stress test: 20 threads pressed Book at once on 3 berths and got exactly 3 holds for 3 different people, because each hold is one conditional UPDATE with rowcount.
  • In our design a waitlisted passenger has already paid, so promotion goes straight to booked (our simplification).

Try extending it: send the agent Mehta back into the waiting room and let him book after minute 30; give the waitlist a payment step too; and add a cancel() for a berth that's only held (what should the guard be?).

Practice

  1. Homework: in the RACE demo, try 5 people and 2 seats. What happens?
  2. Homework: in the HOLD demo, add a confirm() that runs after payment.
  3. Homework: in the ROOM demo, what if capacity doubles?
  4. Homework (comment): why must cancel + promote be atomic?
  5. In the ATOMIC demo, try 5 people and 2 seats. How many get a berth?
  6. In the CROWD demo, how many time out if capacity is 40,000 a second?
  7. In the BOTS demo, try limits of 2 and 5 per ID. What do humans get?
  8. Why must the booking decision never come from the cache, even though the cache is much faster?
Solution

1. Change seats_left = 1 to seats_left = 2 (comment: two berths left) and the names to ["Priya", "Rahul", "Asha", "Neha", "Vikram"]. Output (the order of names can change from run to run):

Priya got the berth!
Rahul got the berth!
Neha got the berth!
Asha got the berth!
Vikram got the berth!
seats left: -3

All five got a berth from two seats, and seats left is −3: every thread checked while the count was still 2. More people make the race worse, not better.

2.

HOLD_MINUTES = 10                # our own number for this demo
seats = {"B1-23": None}          # berth -> (who holds it, until)
booked = {}                      # berth -> who has a confirmed ticket

def hold(berth, name, now):
    if berth in booked:
        return f"{name}: {berth} is booked by {booked[berth]}"
    h = seats[berth]
    if h is None or h[1] <= now: # free, or the old hold expired
        seats[berth] = (name, now + HOLD_MINUTES)
        return f"{name} holds {berth} until minute {now + HOLD_MINUTES}"
    return f"{name}: {berth} is held by {h[0]}"

def confirm(berth, name, now):   # called after the payment succeeds
    h = seats[berth]
    if h is None or h[0] != name or h[1] <= now:
        return f"{name}: hold on {berth} expired, payment refunded"
    booked[berth] = name
    seats[berth] = None
    return f"{name} confirmed on {berth}"

print(hold("B1-23", "Priya", now=0))
print(confirm("B1-23", "Priya", now=3))    # paid in time
print(hold("B1-23", "Rahul", now=11))      # booked: not free any more

booked.clear(); seats["B1-23"] = None
print(hold("B1-23", "Priya", now=0))
print(hold("B1-23", "Rahul", now=11))      # Priya's hold expired
print(confirm("B1-23", "Priya", now=12))   # too late

Output:

Priya holds B1-23 until minute 10
Priya confirmed on B1-23
Rahul: B1-23 is booked by Priya
Priya holds B1-23 until minute 10
Rahul holds B1-23 until minute 21
Priya: hold on B1-23 expired, payment refunded

confirm() must check three things: the hold exists, it's hers, and it hasn't expired. In the second story Rahul already holds the berth at minute 11, so Priya's late payment must be refunded, not confirmed. In a database this is one conditional update: UPDATE ... SET status = 'booked' WHERE who = ? AND status = 'held' AND until > now (the mini project's pay()).

3. Change capacity = 20_000 to 40_000 (and the last line's text). Output:

user0: number 1 in line, about 0 s
user123456: number 123,457 in line, about 3 s
user399999: number 400,000 in line, about 9 s
refresh keeps your place; servers see 40,000 a second

Every wait halves: the last person waits about 9 s instead of 19 s. The waiting room's job doesn't change; it simply drains faster.

4. Because in between the two steps the berth is free, and any other server can sell it. Here is the bad order, step by step:

from collections import deque
confirmed = {"B1-23": "Priya", "B1-24": "Rahul"}
waitlist = deque(["Asha", "Neha", "Vikram"])

# NOT atomic: cancel and promote are two separate steps
print(confirmed["B1-24"], "cancels B1-24")
confirmed["B1-24"] = None                      # step 1: berth is free...
# ...another server sees a free berth in between and sells it:
confirmed["B1-24"] = "Karan"
print("in between, Karan books B1-24")
confirmed["B1-24"] = waitlist.popleft()        # step 2: promote WL1
print("then", confirmed["B1-24"], "is put on B1-24")
print("Karan paid for B1-24 too: two tickets, one berth")

Output:

Rahul cancels B1-24
in between, Karan books B1-24
then Asha is put on B1-24
Karan paid for B1-24 too: two tickets, one berth

Two people paid for one berth again. The fix is one transaction that frees the berth and gives it to WL1, so nobody can ever see it free in between (the mini project's free_and_promote(), with with con:).

5. Change ('B1', 1) to ('B1', 2) and the names to the same five. Output (which two win can change from run to run):

Priya got the berth!
Vikram got the berth!
Neha sorry, sold out
Asha sorry, sold out
Rahul sorry, sold out
seats left: 0

Exactly 2 got berths and 3 were told "sold out"; seats left is 0, never negative. Compare with Practice 1's −3.

6. Change capacity = 20_000 to 40_000. Output:

served in time: 400,000
timed out: 0
...and each one presses refresh: the next second is worse

0 time out (the last line is fixed text in the demo; with no time-outs there's nothing to refresh). But doubling the servers only for 10 minutes a day is expensive, and if the crowd also doubles (8 lakh) you're back to 4 lakh time-outs. A waiting room protects you whatever the crowd size.

7. Change the loop to for limit in [None, 1, 2, 5]:. Output:

limit per ID None: humans got 0 of 50
limit per ID 1: humans got 45 of 50
limit per ID 2: humans got 40 of 50
limit per ID 5: humans got 25 of 50

Each extra try per ID gives every bot account one more berth (5 bots × the limit). The tighter the limit, the fairer, as long as each ID is one verified person.

8. A cache is a copy, and a copy can be a moment out of date. If two servers read "1 left" from a cache and both book, you're back to seats left: -1. The cache is perfect for the search page ("about 12 left"), where being a second old does no harm; but who gets the berth is decided only by the atomic UPDATE ... WHERE seats_left > 0 in the database, and its rowcount.

Quick quiz

seats_left = 1, two servers book at once

A) read seats_left, then write seats_left - 1
B) UPDATE coach SET seats_left = seats_left - 1
   WHERE seats_left > 0

Which booking is safe?

    1. A, if the server is fast
    1. B, then check rowcount
    1. Both are safe
    1. Neither: use a bigger server
Answer

2. B, then check rowcount. B checks and books in one atomic step: rowcount 1 = you got it, 0 = sold out. A is check-then-act: a race, however fast the server is (our RACE demo: seats left: -1; even with a database, Trap 1 told two people they got the berth).

Interview questions: "Design a ticket booking system / IRCTC Tatkal / a flash sale"

1. Clarify requirements. What's being sold (berths, seats, items), and how many? When does sale open, and how big is the crowd at that moment? Is there a payment step, and how long may it take? What happens when it's sold out (waitlist)? Any fairness rules (one per person, agents)? Then state: search and see availability, hold, pay, confirm, waitlist; survive the peak; never sell one berth twice; real people first.

2. Estimate. "67,159 AC Tatkal tickets in the first 10 minutes is about 6,700 a minute, 90x the daily average of 75 (Railways data, June 2025). The new PRS targets 1.5 lakh tickets and 40 lakh enquiries a minute: 2,500 writes and about 66,700 reads a second, 27 reads per booking. I'll assume the arriving crowd is far bigger than what booking servers can take at once (our guess: 4 lakh requests in the first second vs 20,000 a second)."

3. Components.

  • Waiting room: tokens, a place in line, admit N a second.
  • Login / gate: verified IDs only (Aadhaar authentication), one try per ID, agents blocked in the first 30 minutes.
  • Booking service: stateless servers; hold → pay → confirm.
  • Inventory database: every berth's state; holds and confirms as atomic conditional updates; a sweeper for expired holds.
  • Payment: UPI or cards; refunds when a hold has expired.
  • Availability: caches and read replicas for search.
  • Waitlist: a FIFO queue per train and class; free + promote in one transaction.

4. The hard parts. Never double-sell: one atomic UPDATE ... WHERE plus rowcount, not check-then-act in app code, and no in-memory locks across servers. Holds with expiry, and a confirm that re-checks the hold. Payment success arriving after expiry (refund). Flash crowd: waiting room and rate limits instead of time-outs and refresh storms. Bots: per-ID limits only work with verified IDs.

5. Scale and reliability (general knowledge). Partition the inventory by train (each train's berths in one place, so one atomic update covers them); keep hot trains on their own servers; replicate the database so a crash loses no bookings; keep booking transactions short; serve every read you can from caches and replicas; monitor the waiting-room admit rate and lower it if the database slows down.

Common follow-ups:

  • Why not a lock in the app? (Many servers, each with its own memory; the shared database is the only place all of them see.)
  • What if the payment succeeds just after the hold expired? (The confirm's conditional update changes 0 rows, so refund; never confirm a berth someone else may now hold.)
  • How long should a hold be? (Long enough for most payments, short enough that abandoned holds come back quickly; our demo uses 10 minutes as our own number.)
  • What if one train is far more popular than others? (Its row is a hot spot: partition by train and coach, keep the transaction tiny, and let the waiting room control how many reach it.)
  • How do you keep the waiting room fair? (Place by arrival order, tied to a token so refresh doesn't lose it; one place per verified ID.)

Glossary

Term Meaning
IRCTC Indian Railway Catering and Tourism Corporation, which runs Indian Railways' online booking
Tatkal A last-minute ticket quota, booked in a short window the day before the journey
Berth / coach One sleeping place on a train (B1-23) / one carriage (B1)
AC / non-AC classes Air-conditioned and ordinary classes; Tatkal opens at 10:00 and 11:00 respectively
Functional requirement What the system must do, e.g. "book a berth"
Non-functional requirement How well it must do it, e.g. "survive the 10 am spike"
Average / peak Load spread evenly over time / the busiest period's load (75 vs 6,716 a minute)
Flash crowd A huge number of users arriving at the same moment for the same thing
Thread A separate line of work running at the same time inside one program
Race condition A bug where the result depends on who runs first, e.g. both see "1 left"
Check-then-act Reading a value, deciding, then writing in a separate step: a race
Lock A rule that only one worker at a time may run some code; works only inside one program's memory
SQLite A small SQL database stored in one file, built into Python (sqlite3)
Commit Making a change permanent and visible to others
Transaction A group of database changes that become permanent together at the commit
Atomic Happens completely or not at all, with nothing in between
Conditional update An UPDATE that changes a row only WHERE a condition still holds
rowcount How many rows a statement changed: 1 = you got it, 0 = sold out
Lost update Two writers both read an old value and one overwrites the other's change
database is locked SQLite's OperationalError when another connection holds an uncommitted write too long
Hold A temporary reservation of a berth for one person while they pay
Expiry The time a hold ends on its own, e.g. "until minute 10"
Lease A hold that expires on its own unless confirmed or renewed
Confirm Turning a live hold into a booking after payment
Sweeper A job that regularly frees holds past their expiry
Refund Sending a payment back, e.g. when it arrives after the hold expired
Capacity The most work a system can do per second (our guess: 20,000)
Timeout Giving up waiting after a fixed time (our guess: 10 s in the browser)
Refresh storm Errors make users refresh, which adds load and causes more errors
Virtual waiting room A cheap page that gives each user a place in line and admits N a second
Token A small ticket the waiting room gives your browser to keep your place
Rate limit A cap on how many requests are accepted per unit of time
Bot A program that logs in and books automatically, faster than any human
User ID The account a person logs in with
Limit per ID The most tries one account may make
Aadhaar authentication Proving an account belongs to the real person with that Aadhaar number
OTP One-time password: a short code sent to your phone that works once
Authorised agent A registered travel agent; blocked in the first 30 minutes of the Tatkal window
Deactivate Switch an account off so it can't log in
Waitlist / WL1 An ordered list of people waiting for a berth / waitlist number 1
Queue A first-in-first-out line of items
FIFO / LIFO First in, first out (a queue) / last in, first out (list.pop())
deque Python's double-ended queue; popleft() takes the first item quickly
Promote Move the first waitlisted person onto a freed berth
PRS Passenger Reservation System: Indian Railways' core seat and ticket system
Enquiry A request to see seat availability without booking
Cache A fast copy of data kept close to where it's needed; can be a moment old
Read replica A copy of the database that serves reads
Inventory database The database that holds every berth and its state
Stress test Running many requests at once to check the system stays correct
Lakh / crore 1,00,000 (100,000) / 1,00,00,000 (10 million)

Summary

  • Tatkal is a flash crowd: 75 AC tickets a minute on average, 6,716 a minute from 10:00 to 10:10, 90x. Design for the peak.
  • Check-then-act is a race condition: two people, one berth, seats left: -1. Let the database check and book in one atomic conditional update and read rowcount: seats left: 0. A lock in one program can't protect many servers.
  • A hold without an end blocks a berth forever. Holds expire (10 minutes in our demo): hold → pay → confirm, or expire, with a refund if payment arrives too late.
  • 4 lakh requests against 20,000 a second means 2 lakh time-outs and a refresh storm. A virtual waiting room gives everyone a place and admits a steady rate: the last person waits about 19 s.
  • Bots took 50 of 50 berths; one try per ID gave humans 45, but only if each ID is a verified person (Aadhaar authentication; 2.5 crore suspected IDs deactivated; agents wait 30 minutes).
  • Sold out → a FIFO waitlist (deque.popleft()), with cancel + promote in one transaction.
  • 533 → 2,500 tickets a second, 66,667 enquiries a second: cache the reads; the database, atomically, decides who gets the berth.

Next episode: you type three letters into a search box, and ten suggestions appear before you type the fourth. Design search autocomplete.

Sources: Free Press Journal, 5 Jun 2025 (Railways data): "Every day, around 2,25,000 passengers book Tatkal tickets through the online platform"; AC: "an average of 67,159 tickets were booked online within the first 10 minutes of the window opening", "representing 62.5% of all tickets booked online"; non-AC: "Approximately 66.4% of tickets were sold within the first 10 minutes". DeshGujarat, 4 Jun 2025 (Railways): "2.5 crore suspected user IDs have been deactivated"; "Bot traffic accounts for up to 50% of overall login attempts" in the first five minutes of Tatkal booking; "the highest-ever per-minute booking of 31,814 tickets" on 22 May 2025. News On AIR, 11-12 Jun 2025: Aadhaar-based authentication mandatory for online Tatkal bookings (from 1 July 2025; Aadhaar OTP from 15 July 2025); authorised agents "will not be permitted to book opening-day Tatkal tickets during the first 30 minutes"; "AC classes from 10 AM to 10:30 AM and ... non-AC classes from 11 AM to 11:30 AM". PIB, 29 Jun 2025: new PRS "generating over 1.5 lakh rail tickets per minute", up from "32000 tickets in a minute"; enquiries from 4 lakh to "over 40 lakh enquiries per minute". The 4 lakh requests in the first second, the 20,000-a-second capacity, the 10-second browser timeout, the 10-minute hold, the 60 humans / 5 bots demo, the mini project's numbers and all names are our own stated assumptions; race conditions, atomic updates, leases, waiting rooms, caches and replicas are general textbook knowledge, and the full design is our design, not a description of IRCTC's internal systems.