Tatkal Booking System Design: Queues, Locks, Bot Defence

Tatkal Booking System Design: Queues, Locks, Bot Defence

11 min read

At 10:00:00 AM the AC Tatkal window opens, and for about two minutes it feels like the whole country taps Book at once. Tatkal booking system design is one of my favourite interview questions, because the naive answer is a single UPDATE and the real answer is mostly about what you keep away from that UPDATE. This is how I would design a system like this. It is not a description of how IRCTC works internally.

TL;DR

  • Fix the crowd, not the row: a virtual waiting room that admits a fixed rate.

  • One inventory row per train + date + class + quota. A conditional UPDATE ... WHERE available >= n is the final word.

  • A decrement creates a hold with an expiry. Payment confirms it, expiry releases it, late payments are refunded.

  • Idempotent Book, one active hold per account.

  • Bot defence in layers, plus a fairness rule you decide up front.

The problem in numbers

Interviewers want numbers early. Illustrative, not real railway data: say the popular trains on one route and date have 2,000 Tatkal seats between them, and 2 lakh people tap Book at 10:00:00. That is 100x more demand than supply, most of it in the first two minutes.

The requirements that follow:

  1. Never oversell. Two people never get the same berth.

  2. Survive the spike. Someone checking PNR status should not suffer because of Tatkal.

  3. Be fair, and look fair. If a script always wins, people stop trusting the system.

  4. Handle money honestly. Money taken means a ticket or a refund.

  5. Resist bots without making humans miss the window.

My framing: you are building a system that serves 2,000 bookings and gives a fast, honest "no" to the other 1,98,000 people.

Why one seats row melts

The naive design is one row per train, date and class with an available column, and every Book request updates it. The SQL is atomic, so correctness is fine. Throughput is not.

  • Every request waits on the same row lock, so updates run one at a time.

  • Each waiting request holds a database connection and a thread. The pool is gone almost instantly.

  • Requests time out, users retry, and now you have the crowd plus its retries.

  • Pages unrelated to Tatkal share the same pool and slow down too.

The fix is not a cleverer UPDATE. It is controlling how many requests reach it per second.

The Tatkal booking system design, end to end

End-to-end flow of a Tatkal-style booking system from lobby to queue, admission token, Book API, inventory, hold, payment and sweeper
The whole design on one page. Only admitted users with a valid token ever reach the inventory row.

Users wait in a lobby before 10:00. At 10:00:00 it becomes a queue. An admission service lets a fixed number through per second, each with a short-lived token. Only token holders can call Book, which runs one conditional decrement on the right inventory bucket and creates a hold. Payment confirms the hold. A sweeper releases expired holds.

Layer

What it does

What breaks without it

Waiting room + admission tokens

Caps traffic to Book at a rate the database can take

Lock queues, pool exhaustion, retry storms

Inventory buckets

One counter per train + date + class + quota

One hot row for everything

Conditional decrement

Takes seats only if enough are left

Overselling from read-then-write races

Holds with expiry

Sets seats aside while the user pays

Seats stuck on abandoned payments

Idempotency key

Same Book request, same result

Double holds from double taps and retries

Bot defence

Keeps the queue for humans

Scripts take the inventory in the first second

Step 1: a virtual waiting room with admission tokens

This is the part candidates skip most often, and the one that matters most.

Positions. Keep each queue in Redis as a sorted set: ZADD with the position as the score, ZRANK to show a user where they stand, ZPOPMIN to take the front of the line. Position polling only touches Redis.

Admission rate. Load test the Book path and admit a little below what the database handles comfortably. If 300 bookings a second keeps p99 healthy, admit 250 (example numbers). When a bucket sells out, stop admitting and tell everyone waiting right away.

Admission tokens. Each admitted user gets a signed token (HMAC or JWT) with the account id, the bucket and an expiry a couple of minutes out. Book checks it before anything else, with no database call, so junk requests cost almost nothing. Mark it used when a hold is created so it can't be replayed.

Fairness. This is a product decision, so make it out loud. Strict first-come-first-served rewards the fastest connection or the best script at 09:59:59.999. My choice: everyone in the lobby before 10:00:00 gets a random position, and later arrivals join the back in order. That removes the reward for hammering the button, and most of the reason to run a bot.

Users in a lobby before 10:00 are shuffled into random queue positions, then admitted at a fixed rate with signed tokens
Randomise the lobby, then admit at a rate the database can take. Arriving at 09:59:59.999 buys nothing.

Step 2: split inventory per train, date, class and quota

A Tatkal seat in 3A is a different thing from a Sleeper seat on the same train, and from a general quota seat. Each bucket gets its own row:

inventory.sqlSQL
CREATE TABLE inventory (    id            BIGSERIAL   PRIMARY KEY,    train_no      VARCHAR(10) NOT NULL,    journey_date  DATE        NOT NULL,    travel_class  VARCHAR(4)  NOT NULL,    quota         VARCHAR(4)  NOT NULL,    available     INT         NOT NULL CHECK (available >= 0),    UNIQUE (train_no, journey_date, travel_class, quota));

What this buys you:

  1. Contention spreads out. 3A and Sleeper requests never wait on each other's lock.

  2. Counts first, berths later. In this design the user states a berth preference, not a seat, so Book only decrements a count. Berth numbers are assigned after payment, outside the hot path.

  3. A safety net. The CHECK constraint refuses a negative count even if a bug slips through.

One cheap shortcut: a sold-out flag in Redis per bucket, set when a decrement fails, cleared when the sweeper releases seats. Sold-out buckets stop costing database work.

How do you stop a Tatkal booking system from overselling?

Make the database decide in one atomic statement. Decrement the bucket only if enough seats are left, then check how many rows changed. One row means the seats are yours, zero means sold out. Never read the count, check it in Java and write it back, because two requests can read the same number at the same time.

The bug and the fix, side by side (jdbc is the JdbcClient Spring Boot 3.2+ auto-configures):

Open in PlaygroundOpen in Playground
Naive: read, check, writeJava
@Transactionalpublic boolean book(long inventoryId, int seats) {    int available = jdbc.sql("SELECT available FROM inventory WHERE id = :id")            .param("id", inventoryId)            .query(Integer.class)            .single();    if (available < seats) {        return false;    }    // Two requests can both read 1 here, and both write 0.    jdbc.sql("UPDATE inventory SET available = :left WHERE id = :id")            .param("left", available - seats)            .param("id", inventoryId)            .update();    return true;}
Fixed: one conditional decrementJava
public boolean tryReserve(long inventoryId, int seats) {    int rows = jdbc.sql("""            UPDATE inventory               SET available = available - :seats             WHERE id = :id               AND available >= :seats            """)            .param("seats", seats)            .param("id", inventoryId)            .update();    return rows == 1;}

In PostgreSQL's default isolation level, two updates on the same row are serialised by the row lock, and the second one re-checks its WHERE clause against the row the first one committed. That re-check is what makes the fixed version safe without SELECT ... FOR UPDATE.

Step 3: holds with expiry, then payment

A successful decrement is a hold, not a ticket: seats set aside while the user pays.

booking_hold.sqlSQL
CREATE TABLE booking_hold (    id               BIGSERIAL   PRIMARY KEY,    account_id       BIGINT      NOT NULL,    inventory_id     BIGINT      NOT NULL REFERENCES inventory (id),    seats            INT         NOT NULL CHECK (seats > 0),    status           VARCHAR(10) NOT NULL,    idempotency_key  VARCHAR(64) NOT NULL,    expires_at       TIMESTAMPTZ NOT NULL,    UNIQUE (account_id, idempotency_key));CREATE UNIQUE INDEX one_active_hold_per_account    ON booking_hold (account_id)    WHERE status = 'HELD';

status moves from HELD to CONFIRMED or EXPIRED. The decrement and the hold insert run in one transaction, so a failed insert rolls the decrement back too.

Confirm is UPDATE booking_hold SET status = 'CONFIRMED' WHERE id = :id AND status = 'HELD'. One row changed means the payment won.

Expire flips HELD to EXPIRED and returns the seats in one statement (with @EnableScheduling on):

HoldSweeper.javaJava
@Scheduled(fixedDelay = 15_000)public void releaseExpiredHolds() {    jdbc.sql("""            WITH expired AS (                UPDATE booking_hold                   SET status = 'EXPIRED'                 WHERE status = 'HELD'                   AND expires_at < now()                RETURNING inventory_id, seats            ), released AS (                SELECT inventory_id, SUM(seats) AS seats                  FROM expired                 GROUP BY inventory_id            )            UPDATE inventory i               SET available = i.available + r.seats              FROM released r             WHERE i.id = r.inventory_id            """)            .update();}

The SUM ... GROUP BY matters: if two expired holds point at the same bucket, a plain UPDATE ... FROM applies only one of them, and seats leak. Because confirm and expire both require status = 'HELD', the row lock decides who wins a race, and the sweeper is safe on every instance.

State machine for a seat hold: HELD moves to CONFIRMED on payment or to EXPIRED on timeout, and a late payment goes to refund
Confirm and expire both require status HELD, so the row lock decides who wins a race.

Two edge cases to raise early:

  • Late payment. Payment succeeds after the hold expired and the seats went to someone else. I refund automatically, keyed by payment id so the refund can't happen twice. Squeezing them back in is how overselling sneaks back.

  • Pending payment. Before expiring a hold with a pending payment, ask the gateway for the final status. A short grace period beats refunding someone who paid.

The hold length (10 minutes, as an example) trades fairness against payment reality: too short and a slow bank approval misses it, too long and abandoned carts sit on seats. More on holds under load in flash sale overselling.

Step 4: make Book idempotent

Networks drop responses, users double tap, apps retry. Without idempotency, each can become a second hold.

The client creates a key (a UUID) when the user taps Book and reuses it for every retry of that tap. The server stores it on the hold, protected by UNIQUE (account_id, idempotency_key):

  1. First request: decrement, insert the hold, return it.

  2. Retry with the same key: the insert hits the unique constraint, the whole transaction rolls back (decrement included), and the server returns the existing hold.

Catch the duplicate-key error outside the transaction and read the existing hold in a fresh query, because PostgreSQL won't run more statements in a failed transaction. Full pattern: idempotency keys in Spring Boot.

Step 5: bot defence in layers

No single control stops bots. Each layer makes the next one cheaper.

  1. Identity. Every token, hold and booking belongs to one verified account. Public rules already push this way: since July 2025, Indian Railways has required Aadhaar-authenticated accounts for online Tatkal booking.

  2. Rate limits per account, device and IP. Per account is strict, say one Book attempt every few seconds. Per IP stays loose, because many mobile users share a public IP behind carrier NAT.

  3. CAPTCHA at queue entry, not at payment. Check for a human in the lobby, when nobody is in a hurry, not at the second a human is racing a script.

  4. One active hold per account, enforced by the partial unique index above.

  5. A randomised lobby. Clicking at 09:59:59.999 buys nothing.

  6. Behaviour signals. A booking submitted in under a second, many accounts on one device, one payment instrument across dozens of accounts. Flag first, block when sure.

A per-account limit in its smallest form is one key, a cooldown and a yes or no per call. This practice problem is exactly that:

Practice problemEasy
Message Rate Limiter
DesignHash TableData Stream
Python · C++ · Java · JavaScript · TypeScript
Six stacked layers of bot defence, from verified identity at the top to behaviour signals at the bottom
No single control stops bots. Each layer makes the next one cheaper.

Interview checklist

  • Example numbers said out loud: seats, people, time window

  • A waiting room, and how the admission rate is chosen

  • Inventory keyed by train + date + class + quota

  • A conditional decrement, with rows updated checked

  • Holds, expiry, the sweeper and the late-payment rule

  • An idempotent Book

  • Layered bot defence, and the fairness rule you chose

The 60-second interview answer

The hard part is the crowd, not the decrement. I would put a virtual waiting room in front: the lobby before 10:00 gets random positions, and an admission service lets through a fixed rate, set from load tests, each user with a short-lived signed token. Inventory is one row per train, date, class and quota. Book runs a conditional decrement, available = available - n WHERE available >= n, and creates a hold with an expiry in the same transaction. Payment confirms the hold, a sweeper releases expired ones, late payments are refunded. Book is idempotent with a client key. Bot defence is layered: verified accounts, rate limits per account, device and IP, CAPTCHA at lobby entry, one active hold per account.

Try it yourself

1. A payment succeeds 40 seconds after its hold expired, and the seats are already sold to someone else. What exactly does your system do?

Reveal Approach

Confirm fails because the hold is no longer HELD. The payment goes to the refund path, keyed by payment id so a retried webhook can't refund twice, and the user is told clearly. Inventory is not touched again.

2. You admit 500 users a second, but the Book path handles 300 a second comfortably. What do you see first?

Reveal Approach

Book latency and lock waits climb. Tokens expire before users finish, so they come back and add load. Lower the admission rate, or make it adaptive: slow down when Book's p99 rises.

3. Why not SELECT ... FOR UPDATE, then check, then update?

Reveal Approach

It is correct, but it holds the row lock across two statements, the round trips and the Java code in between. The conditional decrement holds it for one statement, so more bookings get through per second.

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?