On this page

Booking & Inventory Concurrency: Preventing Double Booking

Every booking system sells something scarce: a seat at a show, a hotel room for a night, a parking spot, a doctor's appointment, the last pair of trainers in a size. Scarcity creates contention. When a hit film opens or a flash sale starts, hundreds of requests arrive for the same few items within milliseconds, and the system must guarantee that each item goes to exactly one buyer. Selling a seat twice means an angry customer at the door. Selling stock you don't have means cancelled orders, refunds and a public apology.

That's why "how do you prevent double booking?" is the most common concurrency follow-up in LLD interviews. It appears in movie booking, hotel management, parking lot and every e-commerce prompt. It also has a satisfying structure: there's one race, and a ladder of fixes from a single in-memory lock to database constraints, each with a clear cost and a clear limit.

This page climbs that ladder:

  1. the race itself, on a timeline, with a demo that fails;
  2. in-process fixes: a lock per seat, ConcurrentHashMap claims and compare-and-set;
  3. seat holds with expiry: the hold → confirm → release state machine, and sweeping vs lazy expiry;
  4. database fixes: SELECT … FOR UPDATE, version columns, unique constraints and idempotency keys;
  5. inventory decrements for flash sales;
  6. a complete movie-seat booking service in Java, Python and TypeScript, with a concurrency test that proves exactly one winner per seat.

The general principles (check-then-act, atomicity, lock granularity) come from Thread-Safe Class Design; this page applies them to one domain in depth. Every Java, Python and TypeScript sample was compiled and run, and every SQL listing and database sample was run against PostgreSQL 16.

The double-booking race

The naive booking method is two lines of logic:

if seat.status == AVAILABLE:      # check
    seat.status = BOOKED          # act
    seat.bookedBy = user

Each line is correct. The pair isn't, because another request can run between them. Here's the interleaving that sells seat A7 twice:

sequenceDiagram
    participant A as Alice's request
    participant S as Seat A7
    participant B as Bob's request
    A->>S: read status
    S-->>A: AVAILABLE
    B->>S: read status
    S-->>B: AVAILABLE
    Note over A,B: both checks passed, the seat is still free in both views
    A->>S: write BOOKED, bookedBy = Alice
    B->>S: write BOOKED, bookedBy = Bob
    Note over S: Bob silently overwrote Alice, both were told "confirmed"

The window between check and act might be a few nanoseconds in memory, or hundreds of milliseconds if a payment call sits between them. Its width changes how often the race fires, never whether it can. In a flash sale, with hundreds of requests per item per second, even a tiny window fires constantly.

Here's the race happening. Eight threads per round race to book the same seat; the demo counts rounds in which more than one thread was told it had won.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

class DoubleBookingDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(8);
        int doubleBooked = 0;
        for (int round = 0; round < 2_000; round++) {
            NaiveSeat seat = new NaiveSeat();
            CountDownLatch go = new CountDownLatch(1);
            AtomicInteger confirmations = new AtomicInteger();
            List<Future<?>> fs = new ArrayList<>();
            for (int t = 0; t < 8; t++) {
                String user = "user" + t;
                fs.add(pool.submit(() -> {
                    go.await();
                    if (seat.book(user)) confirmations.incrementAndGet();
                    return null;
                }));
            }
            go.countDown();
            for (Future<?> f : fs) f.get();
            if (confirmations.get() > 1) doubleBooked++;
        }
        pool.shutdown();
        System.out.println("rounds where one seat was confirmed to several users: " + doubleBooked + " of 2000");
    }
}

class NaiveSeat {
    private boolean booked;          // no lock, no volatile: both bugs at once
    private String bookedBy;

    boolean book(String user) {
        if (booked) return false;    // check
        booked = true;               // act
        bookedBy = user;
        return true;
    }
}
import sys
import threading


class NaiveSeat:
    def __init__(self) -> None:
        self.booked = False
        self.booked_by: str | None = None

    def book(self, user: str) -> bool:
        if self.booked:          # check
            return False
        self._audit(user)        # any call here is a point where CPython may switch threads
        self.booked = True       # act
        self.booked_by = user
        return True

    def _audit(self, user: str) -> None:
        pass


if __name__ == "__main__":
    sys.setswitchinterval(1e-6)  # switch far more often than the 5 ms default, to expose the race
    double_booked = 0
    for _ in range(500):
        seat, wins = NaiveSeat(), []
        gate = threading.Barrier(8)

        def attempt(user: str) -> None:
            gate.wait()
            if seat.book(user):
                wins.append(user)

        threads = [threading.Thread(target=attempt, args=(f"user{t}",)) for t in range(8)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        double_booked += len(wins) > 1
    print(f"rounds where one seat was confirmed to several users: {double_booked} of 500")

Five runs of the Java demo on our machine (Java 24, 32 hardware threads) printed 4, 1, 1, 0 and 2 double-booked rounds out of 2,000: the window between the check and the write is only a few instructions wide, so the race is rare, and one run in five saw nothing at all. The Python demo, with the switch interval shrunk to one microsecond, printed between 4 and 9 out of 500. A run that prints 0 proves nothing about the code; a single non-zero run proves it's broken.

One clarification before the fixes: the race isn't only an in-memory, multi-threaded problem. Two application servers that each read a seat row from the database and then write it back have exactly the same race, with the network widening the window. And a single-threaded Node process has it too, as soon as an await sits between the check and the act. So the fixes come in two families: in-process (the state lives in one process's memory) and database (the state lives in a shared store). Most real systems need the second, and in an interview you should present both.

In-process solutions

When the seat map lives in memory, for example in a single-instance service, a cache in front of the database or a machine-coding round, there are three standard ways to make "check and claim" atomic. They differ in how they scale, how they handle several seats at once and how readable they are.

Option 1: a lock per seat (or per show)

Give each Seat its own lock and do the check and the act while holding it. Requests for different seats never contend.

The complication is multi-seat bookings. A family books A5, A6 and A7 together, and wants all three or none. Holding three seat locks at once raises the risk of deadlock: if one request locks A5 then A6, and another locks A6 then A5, each can end up waiting for the other forever. The standard fix, from deadlock prevention, is a global lock order: always lock seats sorted by ID. Then no cycle of waits can form.

An alternative is one lock per show. It's coarser (two bookings for different seats in the same show wait for each other) but makes multi-seat atomicity trivial, and a show has at most a few hundred seats and a few bookings per second outside of opening-day rushes. For an interview, the per-show lock is usually the right default, with per-seat locks as the scaling story. The complete service below uses a per-show lock for exactly this reason.

Option 2: a concurrent map claim

If the "booked" state is simply "an entry exists in a map from seat to holder", then ConcurrentHashMap.putIfAbsent(seat, user) is an atomic check-and-claim: it inserts only if absent and tells you whether it did. No explicit lock appears in your code. compute and computeIfAbsent extend this to arbitrary per-key logic, run atomically for that key.

Multi-seat bookings need more care because the map is atomic per key, not across keys. The standard technique is claim and roll back: claim each seat in turn with putIfAbsent; if any claim fails, remove the ones you already claimed and report failure. It's correct (nobody ends up double-booked) but not perfectly clean: for a moment, another user may see A5 taken by a booking that's about to roll back, and be refused a seat that becomes free microseconds later. For seat booking that's acceptable; for a bank ledger it wouldn't be.

Option 3: compare-and-set on the seat state

Store each seat's state in an AtomicReference (or one slot of an AtomicReferenceArray) holding an immutable value like Free or Held(user, expiresAt). Claiming is compareAndSet(FREE, new Held(...)): it succeeds only if the seat is still in exactly the state you read. This is the lock-free option, and it carries the most information: because the state object can hold the expiry time, the same CAS can take over an expired hold (compareAndSet(expiredHold, newHold)), which neither of the other options does as naturally.

Here are all three, with a shared stress test: 32 threads try to book each of 50 seats in a random order, and every implementation must produce exactly one winner per seat. A second test runs multi-seat bookings of overlapping pairs and checks that no seat ends up in two bookings.

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.ReentrantLock;

class InProcessSeatsDemo {
    public static void main(String[] args) throws Exception {
        List<SeatBook> impls = List.of(new LockPerSeat(50), new MapClaim(50), new CasSeats(50));
        for (SeatBook book : impls) {
            for (int round = 0; round < 20; round++) singleSeatRace(book.fresh());
            for (int round = 0; round < 20; round++) pairRace(book.fresh());
            System.out.println(book.getClass().getSimpleName() + ": exactly one winner per seat, pairs never overlap");
        }
    }

    static void singleSeatRace(SeatBook book) throws Exception {
        ConcurrentHashMap<Integer, String> winners = new ConcurrentHashMap<>();
        AtomicInteger duplicates = new AtomicInteger();
        race(32, t -> {
            List<Integer> order = new ArrayList<>();
            for (int s = 0; s < 50; s++) order.add(s);
            Collections.shuffle(order, new Random(t));
            for (int s : order) {
                if (book.bookAll(List.of(s), "u" + t) && winners.putIfAbsent(s, "u" + t) != null) duplicates.incrementAndGet();
            }
        });
        if (duplicates.get() != 0 || winners.size() != 50) throw new AssertionError(duplicates + " / " + winners.size());
    }

    static void pairRace(SeatBook book) throws Exception {
        Map<String, List<Integer>> won = new ConcurrentHashMap<>();
        race(32, t -> {
            Random r = new Random(t);
            for (int i = 0; i < 20; i++) {
                int first = r.nextInt(49);
                List<Integer> pair = r.nextBoolean() ? List.of(first, first + 1) : List.of(first + 1, first); // mixed order
                if (book.bookAll(pair, "u" + t + "-" + i)) won.put("u" + t + "-" + i, pair);
            }
        });
        Set<Integer> seen = new HashSet<>();
        for (List<Integer> pair : won.values()) for (int s : pair) if (!seen.add(s)) throw new AssertionError("seat " + s + " sold twice");
        for (int s = 0; s < 50; s++) if (seen.contains(s) != book.isTaken(s)) throw new AssertionError("map disagrees on seat " + s);
    }

    interface Body { void run(int threadIndex) throws Exception; }

    static void race(int threads, Body body) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(threads);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<?>> fs = new ArrayList<>();
        for (int t = 0; t < threads; t++) {
            int index = t;
            fs.add(pool.submit(() -> { go.await(); body.run(index); return null; }));
        }
        go.countDown();
        for (Future<?> f : fs) f.get();
        pool.shutdown();
    }
}

interface SeatBook {
    /** All seats or none. */
    boolean bookAll(List<Integer> seats, String user);
    boolean isTaken(int seat);
    SeatBook fresh();
}

/** Option 1: one lock per seat, always acquired in ascending seat order. */
final class LockPerSeat implements SeatBook {
    private final ReentrantLock[] locks;
    private final String[] holder;                  // holder[i] guarded by locks[i]

    LockPerSeat(int n) {
        locks = new ReentrantLock[n];
        holder = new String[n];
        for (int i = 0; i < n; i++) locks[i] = new ReentrantLock();
    }

    public boolean bookAll(List<Integer> seats, String user) {
        List<Integer> ordered = seats.stream().distinct().sorted().toList(); // global order: no deadlock
        int locked = 0;
        try {
            for (int s : ordered) { locks[s].lock(); locked++; }
            for (int s : ordered) if (holder[s] != null) return false;
            for (int s : ordered) holder[s] = user;
            return true;
        } finally {
            for (int i = locked - 1; i >= 0; i--) locks[ordered.get(i)].unlock();
        }
    }

    public boolean isTaken(int seat) {
        locks[seat].lock();
        try { return holder[seat] != null; } finally { locks[seat].unlock(); }
    }

    public SeatBook fresh() { return new LockPerSeat(holder.length); }
}

/** Option 2: putIfAbsent per seat; roll back earlier claims if a later one fails. */
final class MapClaim implements SeatBook {
    private final int size;
    private final ConcurrentHashMap<Integer, String> holder = new ConcurrentHashMap<>();

    MapClaim(int size) { this.size = size; }

    public boolean bookAll(List<Integer> seats, String user) {
        List<Integer> claimed = new ArrayList<>();
        for (int s : seats.stream().distinct().toList()) {
            if (holder.putIfAbsent(s, user) != null) {
                for (int c : claimed) holder.remove(c, user);   // remove only if still ours
                return false;
            }
            claimed.add(s);
        }
        return true;
    }

    public boolean isTaken(int seat) { return holder.containsKey(seat); }
    public SeatBook fresh() { return new MapClaim(size); }
}

/** Option 3: CAS each seat slot from null to the holder; undo on failure. */
final class CasSeats implements SeatBook {
    private final AtomicReferenceArray<String> holder;

    CasSeats(int n) { holder = new AtomicReferenceArray<>(n); }

    public boolean bookAll(List<Integer> seats, String user) {
        List<Integer> claimed = new ArrayList<>();
        for (int s : seats.stream().distinct().toList()) {
            if (!holder.compareAndSet(s, null, user)) {
                for (int c : claimed) holder.compareAndSet(c, user, null);
                return false;
            }
            claimed.add(s);
        }
        return true;
    }

    public boolean isTaken(int seat) { return holder.get(seat) != null; }
    public SeatBook fresh() { return new CasSeats(holder.length()); }
}

MapClaim and CasSeats don't need an ordering rule because they never wait for a seat: a failed claim returns immediately and rolls back, so no cycle of waiting can form. That's the general trade-off between the families. Locks wait (and therefore need ordering and timeouts); claims fail fast (and therefore need rollback and, sometimes, retry).

Lock per seatLock per showMap claimCAS
Single-seat bookingSimpleSimpleOne callOne call
Multi-seat, all-or-nothingNeeds sorted lock orderTrivialClaim and roll backClaim and roll back
Contention between different seatsNoneWhole show serialisesNoneNone
Expiry of holdsCheck under lockCheck under lockAwkward (needs compute)Natural (CAS from the expired state)
ReadabilityMediumHighHighMedium
Works across several app servers?NoNoNoNo

The last row is the one to say out loud in an interview. Every in-process option protects one JVM's memory. The moment there are two instances of the booking service, each with its own lock or map, they can each grant the same seat. Then the database has to enforce it, which is the next section but one.

In Python the same three shapes exist: a threading.Lock per seat or per show (with sorted acquisition), dict.setdefault as a single-key claim (atomic in CPython, though that relies on the GIL), and no user-level CAS, so a lock stands in. In Node, a claim is atomic as long as it's synchronous: check and set in the same tick, before any await. The complete service shows both.

Seat holds with expiry

Real booking flows don't go straight from "available" to "booked". Between choosing seats and paying, the user spends a minute or more on a payment page, and the system must keep the seats from being sold to someone else in the meantime, without keeping them forever if the user wanders off. That's a hold (also called a reservation or a soft lock): a claim with a deadline.

stateDiagram-v2
    [*] --> AVAILABLE
    AVAILABLE --> HELD: hold(user, seats) — all or nothing
    HELD --> BOOKED: confirm(holdId) — before expiry, after payment
    HELD --> AVAILABLE: release(holdId) — user cancels
    HELD --> AVAILABLE: expiry — sweep or lazy check
    BOOKED --> AVAILABLE: cancel booking — refund policy applies
    BOOKED --> [*]

The transitions carry the rules:

  • hold succeeds only if every requested seat is AVAILABLE (or HELD by a hold that has already expired). It records the holder, a hold ID and an expiry time, typically 5–10 minutes.
  • confirm succeeds only if the hold still exists, has not expired and still owns every one of its seats. Payment happens before confirm, outside any lock, because it's slow.
  • release returns the seats early when the user cancels.
  • expiry returns the seats when the deadline passes without a confirm.

Two subtleties catch most candidates.

The payment/expiry race. The user pays at 9:59:58 for a hold that expires at 10:00:00, and the confirm arrives at 10:00:01. Meanwhile someone else has held the seat. Now you've taken money for a seat you can't give. There's no way to make this impossible, only to make it rare and handle it: put a grace period on confirm (the hold is visible to new holders as expired a little later than it really expires, or confirm accepts a small lateness), authorise payment rather than capturing it until confirm succeeds, and when confirm fails after payment, refund automatically. Say this in an interview; it shows you've thought past the happy path.

Expiry is a timing problem, so the clock must be injectable. A Clock in Java, a now() function in Python or TypeScript. Then tests can advance time by five minutes instantly instead of sleeping, as the tests below do.

Sweeping vs lazy expiry

There are two ways to make an expired hold release its seats, and good designs use both:

Scheduled sweepLazy expiry
HowA scheduled task (every few seconds) scans for holds with expiresAt <= now and releases themWhenever a seat is checked, a hold that has expired counts as available
CorrectnessSeats stay "held" until the next sweep, up to one sweep interval too longExact: an expired hold never blocks anybody
VisibilityThe seat map shows the true state after each sweepThe stored state lies (it says HELD) until something touches the seat
CostPeriodic scan; needs an index on expires_at in a databaseNothing extra; one comparison per check
Failure modeIf the sweeper dies, seats stay held foreverNone for correctness; stale data accumulates without a sweep

Lazy expiry is the correctness mechanism; the sweep is housekeeping. With lazy expiry, it doesn't matter if the sweeper is late or down: an expired hold never blocks a booking. The sweep exists to keep the stored state tidy, to make seat-map displays accurate and to trigger side effects such as "your hold expired" emails. A delay queue, as built in Concurrency Patterns in LLD, can replace the periodic scan with one timer per hold, which gives exact release times at the cost of memory per hold. Redis users get lazy expiry for free: SET seat:show1:A7 alice NX PX 300000 is an atomic claim with a TTL, and the key disappears on its own.

Database solutions

Once the service runs on more than one instance, the seat map's source of truth is the database, and the database must make the claim atomic. There are four tools, and they layer rather than compete.

The schema used below:

CREATE TABLE seats (
    show_id     int         NOT NULL,
    seat_no     text        NOT NULL,
    status      text        NOT NULL DEFAULT 'AVAILABLE'
                CHECK (status IN ('AVAILABLE', 'HELD', 'BOOKED')),
    hold_id     text,
    held_until  timestamptz,
    version     int         NOT NULL DEFAULT 0,          -- for optimistic locking
    PRIMARY KEY (show_id, seat_no)
);

CREATE TABLE bookings (
    booking_id  bigserial   PRIMARY KEY,
    show_id     int         NOT NULL,
    seat_no     text        NOT NULL,
    user_id     text        NOT NULL,
    status      text        NOT NULL DEFAULT 'CONFIRMED'
);

-- The last line of defence: at most one CONFIRMED booking per seat, whatever the code does.
-- Partial, so a cancelled booking doesn't block re-selling the seat.
CREATE UNIQUE INDEX one_confirmed_booking_per_seat
    ON bookings (show_id, seat_no) WHERE status = 'CONFIRMED';

CREATE INDEX seats_expiring ON seats (held_until) WHERE status = 'HELD';  -- for the sweep

INSERT INTO seats (show_id, seat_no) SELECT 1, 'A' || g FROM generate_series(1, 10) g;
SELECT count(*) AS seats FROM seats;

Pessimistic locking: SELECT … FOR UPDATE

Pessimistic locking assumes conflicts are likely and prevents them up front: lock the row, then check, then write, then commit. In SQL that's SELECT … FOR UPDATE inside a transaction. The row lock is held until commit or rollback, and any other transaction that tries to lock the same row waits.

-- A minimal table so this listing runs on its own.
CREATE TABLE seats (show_id int, seat_no text, status text NOT NULL DEFAULT 'AVAILABLE',
                    hold_id text, held_until timestamptz, PRIMARY KEY (show_id, seat_no));
INSERT INTO seats (show_id, seat_no) SELECT 1, 'A' || g FROM generate_series(1, 10) g;

BEGIN;
-- Lock the seat row. A concurrent transaction running the same statement blocks here.
SELECT status FROM seats WHERE show_id = 1 AND seat_no = 'A1' FOR UPDATE;
-- The application checks that the status is AVAILABLE, then:
UPDATE seats SET status = 'HELD', hold_id = 'h-42', held_until = now() + interval '5 minutes'
 WHERE show_id = 1 AND seat_no = 'A1';
COMMIT;

-- Variants:
--   FOR UPDATE NOWAIT       fail immediately instead of waiting if the row is locked
--   FOR UPDATE SKIP LOCKED  skip locked rows: "give me any free seat in row A"
BEGIN;
SELECT seat_no FROM seats
 WHERE show_id = 1 AND status = 'AVAILABLE'
 ORDER BY seat_no LIMIT 1
 FOR UPDATE SKIP LOCKED;
COMMIT;

Here it is from Java, with 16 threads, each on its own connection, racing for seat A1:

import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

class PessimisticBookingDemo {
    static final String URL = System.getenv().getOrDefault("JDBC_URL", "jdbc:postgresql://localhost:5432/postgres?user=postgres");

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement()) {
            s.execute("DROP TABLE IF EXISTS p_seats");
            s.execute("CREATE TABLE p_seats (show_id int, seat_no text, status text NOT NULL DEFAULT 'AVAILABLE', "
                    + "booked_by text, PRIMARY KEY (show_id, seat_no))");
            s.execute("INSERT INTO p_seats (show_id, seat_no) SELECT 1, 'A' || g FROM generate_series(1, 10) g");
        }
        ExecutorService pool = Executors.newFixedThreadPool(16);
        CountDownLatch go = new CountDownLatch(1);
        AtomicInteger wins = new AtomicInteger();
        List<Future<?>> fs = new ArrayList<>();
        for (int t = 0; t < 16; t++) {
            String user = "user" + t;
            fs.add(pool.submit(() -> { go.await(); if (book(1, "A1", user)) wins.incrementAndGet(); return null; }));
        }
        go.countDown();
        for (Future<?> f : fs) f.get();
        pool.shutdown();
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement();
             ResultSet rs = s.executeQuery("SELECT count(*) FROM p_seats WHERE status = 'BOOKED'")) {
            rs.next();
            if (wins.get() != 1 || rs.getInt(1) != 1) throw new AssertionError(wins + " wins, " + rs.getInt(1) + " booked");
        }
        System.out.println("16 concurrent transactions, 1 winner (SELECT ... FOR UPDATE)");
    }

    static boolean book(int show, String seat, String user) throws SQLException {
        try (Connection c = DriverManager.getConnection(URL)) {
            c.setAutoCommit(false);
            try (PreparedStatement lock = c.prepareStatement(
                    "SELECT status FROM p_seats WHERE show_id = ? AND seat_no = ? FOR UPDATE")) {
                lock.setInt(1, show);
                lock.setString(2, seat);
                try (ResultSet rs = lock.executeQuery()) {
                    if (!rs.next() || !rs.getString(1).equals("AVAILABLE")) { c.rollback(); return false; }
                }
            }
            // The row is locked: no other transaction can change it until we commit. Keep this part short.
            try (PreparedStatement upd = c.prepareStatement(
                    "UPDATE p_seats SET status = 'BOOKED', booked_by = ? WHERE show_id = ? AND seat_no = ?")) {
                upd.setString(1, user);
                upd.setInt(2, show);
                upd.setString(3, seat);
                upd.executeUpdate();
            }
            c.commit();
            return true;
        }
    }
}

Pessimistic locking is the right choice when contention on a row is high (a popular seat, a single hot inventory row), because waiting is cheaper than repeatedly failing and retrying. Its costs:

  • Never hold the lock across slow work. A transaction that locks a seat, then calls the payment provider, then commits, holds that row lock (and a database connection) for seconds. Under load, the connection pool empties and the whole service stalls. That's precisely why holds exist: lock briefly to mark the seat HELD, commit, take payment outside any transaction, then lock briefly again to confirm.
  • Multi-row locks need an order, just like in-memory locks: SELECT … WHERE seat_no IN (…) ORDER BY seat_no FOR UPDATE. Postgres detects deadlocks and aborts one transaction, so the failure is an error rather than a hang, but it's still an error you must retry.
  • Set a lock timeout (SET lock_timeout = '2s' in Postgres) so a stuck transaction can't make every request for that seat wait forever.

Optimistic locking: version columns

Optimistic locking assumes conflicts are rare and detects them at write time instead of preventing them: read the row without locking (including its version), do your checks, then write with a condition that the version hasn't changed:

UPDATE seats SET status = 'HELD', hold_id = ?, version = version + 1
 WHERE show_id = ? AND seat_no = ? AND version = ?      -- the version we read

If someone else wrote the row in between, its version moved on, the WHERE matches nothing, and the update reports 0 rows affected. The application then re-reads and decides: retry if the seat is somehow still available, or report "seat taken". This is compare-and-set, executed by the database. ORMs support it directly: JPA's @Version, Django's F() expressions with filtered updates, ActiveRecord's lock_version.

import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

class OptimisticBookingDemo {
    static final String URL = System.getenv().getOrDefault("JDBC_URL", "jdbc:postgresql://localhost:5432/postgres?user=postgres");
    static final AtomicInteger conflicts = new AtomicInteger();

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement()) {
            s.execute("DROP TABLE IF EXISTS o_seats");
            s.execute("CREATE TABLE o_seats (show_id int, seat_no text, status text NOT NULL DEFAULT 'AVAILABLE', "
                    + "held_by text, version int NOT NULL DEFAULT 0, PRIMARY KEY (show_id, seat_no))");
            s.execute("INSERT INTO o_seats (show_id, seat_no) VALUES (1, 'A1')");
        }
        ExecutorService pool = Executors.newFixedThreadPool(16);
        CountDownLatch go = new CountDownLatch(1);
        AtomicInteger wins = new AtomicInteger();
        List<Future<?>> fs = new ArrayList<>();
        for (int t = 0; t < 16; t++) {
            String user = "user" + t;
            fs.add(pool.submit(() -> { go.await(); if (hold(1, "A1", user)) wins.incrementAndGet(); return null; }));
        }
        go.countDown();
        for (Future<?> f : fs) f.get();
        pool.shutdown();
        if (wins.get() != 1) throw new AssertionError(wins + " winners");
        System.out.println("16 concurrent holds, 1 winner, " + conflicts.get() + " version conflicts detected");
    }

    /** Read without locking, then write only if the version is unchanged. */
    static boolean hold(int show, String seat, String user) throws SQLException {
        try (Connection c = DriverManager.getConnection(URL)) {          // autocommit: no long transaction
            for (int attempt = 0; attempt < 3; attempt++) {
                String status;
                int version;
                try (PreparedStatement read = c.prepareStatement(
                        "SELECT status, version FROM o_seats WHERE show_id = ? AND seat_no = ?")) {
                    read.setInt(1, show);
                    read.setString(2, seat);
                    try (ResultSet rs = read.executeQuery()) {
                        if (!rs.next()) return false;
                        status = rs.getString(1);
                        version = rs.getInt(2);
                    }
                }
                if (!status.equals("AVAILABLE")) return false;           // someone else has it: no retry
                try (PreparedStatement write = c.prepareStatement(
                        "UPDATE o_seats SET status = 'HELD', held_by = ?, version = version + 1 "
                        + "WHERE show_id = ? AND seat_no = ? AND version = ?")) {
                    write.setString(1, user);
                    write.setInt(2, show);
                    write.setString(3, seat);
                    write.setInt(4, version);
                    if (write.executeUpdate() == 1) return true;         // our CAS won
                }
                conflicts.incrementAndGet();                             // lost the race: re-read and re-decide
            }
            return false;
        }
    }
}
import os
import threading

import psycopg

URL = os.environ.get("DATABASE_URL", "postgresql://postgres@localhost:5432/postgres")


def setup() -> None:
    with psycopg.connect(URL, autocommit=True) as c:
        c.execute("DROP TABLE IF EXISTS o_seats_py")
        c.execute("""CREATE TABLE o_seats_py (show_id int, seat_no text, status text NOT NULL DEFAULT 'AVAILABLE',
                     held_by text, version int NOT NULL DEFAULT 0, PRIMARY KEY (show_id, seat_no))""")
        c.execute("INSERT INTO o_seats_py (show_id, seat_no) VALUES (1, 'A1')")


def hold(show: int, seat: str, user: str) -> bool:
    with psycopg.connect(URL, autocommit=True) as c:
        for _ in range(3):
            row = c.execute("SELECT status, version FROM o_seats_py WHERE show_id = %s AND seat_no = %s",
                            (show, seat)).fetchone()
            if row is None or row[0] != "AVAILABLE":
                return False
            cur = c.execute("""UPDATE o_seats_py SET status = 'HELD', held_by = %s, version = version + 1
                               WHERE show_id = %s AND seat_no = %s AND version = %s""",
                            (user, show, seat, row[1]))
            if cur.rowcount == 1:
                return True
        return False


if __name__ == "__main__":
    setup()
    wins: list[str] = []
    gate = threading.Barrier(16)

    def attempt(user: str) -> None:
        gate.wait()
        if hold(1, "A1", user):
            wins.append(user)

    threads = [threading.Thread(target=attempt, args=(f"user{t}",)) for t in range(16)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    assert len(wins) == 1, wins
    print("16 concurrent holds, 1 winner:", wins[0])

In five runs the Java version reported between 1 and 7 version conflicts per run: most losing threads read the seat after the winner had committed and saw HELD, and only those that read in the narrow window before the commit hit the version check. Either way, there was exactly one winner every time.

For a single status column you don't strictly need a version: UPDATE seats SET status = 'HELD' … WHERE … AND status = 'AVAILABLE' is already a conditional write. Versions earn their place when the decision depends on several columns or on data from other tables, so a simple status predicate can't express "nothing I read has changed".

Pessimistic or optimistic? Choose by contention:

Pessimistic (FOR UPDATE)Optimistic (version / conditional update)
AssumesConflicts are commonConflicts are rare
On conflictWaits for the lockWrite affects 0 rows; re-read and retry or fail
Lock heldFrom the SELECT until commitNone (the UPDATE locks the row only for its own duration)
Good forHot rows, short transactions, flows that must not failMost rows most of the time; long user think-time between read and write
RisksLong transactions block others; deadlocks with multi-row locksRetry storms under high contention; starvation of unlucky writers
Spans user think-time?Never (you can't hold a row lock while a user types a card number)Yes: the version can travel through a form and come back minutes later

The last row is decisive for booking UIs: an "edit booking" form can carry the version it was rendered with, and the save is rejected if the booking changed meanwhile. A pessimistic lock can't span that gap.

Unique constraints: the last line of defence

Locks and versions are application logic, and application logic has bugs: a new endpoint forgets to take the lock, a batch job writes directly, a retry runs twice. A unique constraint is enforced by the database on every write, whatever the code path. The partial unique index in the schema above says "at most one CONFIRMED booking per seat", and no code anywhere can violate it.

import os
import threading

import psycopg
from psycopg import errors

URL = os.environ.get("DATABASE_URL", "postgresql://postgres@localhost:5432/postgres")

with psycopg.connect(URL, autocommit=True) as c:
    c.execute("DROP TABLE IF EXISTS u_bookings")
    c.execute("""CREATE TABLE u_bookings (booking_id bigserial PRIMARY KEY, show_id int NOT NULL,
                 seat_no text NOT NULL, user_id text NOT NULL, status text NOT NULL DEFAULT 'CONFIRMED')""")
    c.execute("""CREATE UNIQUE INDEX u_one_confirmed ON u_bookings (show_id, seat_no)
                 WHERE status = 'CONFIRMED'""")

results: list[str] = []
gate = threading.Barrier(16)


def buggy_book(user: str) -> None:
    """No check at all: imagine an endpoint that forgot the lock. The index still holds."""
    gate.wait()
    with psycopg.connect(URL, autocommit=True) as c:
        try:
            c.execute("INSERT INTO u_bookings (show_id, seat_no, user_id) VALUES (1, 'A1', %s)", (user,))
            results.append("ok")
        except errors.UniqueViolation:
            results.append("rejected")


threads = [threading.Thread(target=buggy_book, args=(f"user{t}",)) for t in range(16)]
for t in threads:
    t.start()
for t in threads:
    t.join()
assert results.count("ok") == 1 and results.count("rejected") == 15, results

with psycopg.connect(URL, autocommit=True) as c:
    # Cancelling frees the seat for re-sale, because the index only covers CONFIRMED rows.
    c.execute("UPDATE u_bookings SET status = 'CANCELLED' WHERE seat_no = 'A1'")
    c.execute("INSERT INTO u_bookings (show_id, seat_no, user_id) VALUES (1, 'A1', 'late-user')")
    confirmed = c.execute("SELECT count(*) FROM u_bookings WHERE status = 'CONFIRMED'").fetchone()
assert confirmed is not None and confirmed[0] == 1
print("16 unguarded inserts: 1 accepted, 15 rejected by the unique index; re-sale after cancel works")

Treat the constraint as a safety net, not the primary mechanism. It turns a double booking into an error at confirm time, after the user has paid, so the application still needs holds or locks to catch the conflict earlier, when telling the user is cheap. But when a bug does slip through, the constraint converts "two people at the door with the same ticket" into an exception in your logs, which is a far better incident. In an interview, mentioning it unprompted is one of the clearest signals of production experience.

The same thinking applies to other invariants: a CHECK (stock >= 0) constraint on inventory, an exclusion constraint on hotel room date ranges (EXCLUDE USING gist (room_id WITH =, stay WITH &&) in Postgres stops two bookings of one room for overlapping nights), and a unique index on (user_id, coupon_id) for one-use coupons.

Idempotency keys

Networks fail ambiguously. The client sends "confirm my booking and charge my card", the connection drops, and the client doesn't know whether the server did it. The client retries. Without protection, the user is charged twice, or a second booking is attempted. The fix is an idempotency key: a unique ID (usually a UUID) that the client generates once per logical operation and sends with every retry. The server records each key with the result of its operation, and a repeat of a known key returns the stored result instead of doing the work again.

The robust implementation stores the key in the same database transaction as the work, behind a unique constraint. In Postgres, a second transaction inserting the same key waits on the first one's uncommitted insert, then sees the conflict once the first commits, so even concurrent retries resolve to one execution:

import java.sql.*;
import java.util.*;
import java.util.concurrent.*;

class IdempotencyDemo {
    static final String URL = System.getenv().getOrDefault("JDBC_URL", "jdbc:postgresql://localhost:5432/postgres?user=postgres");

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement()) {
            s.execute("DROP TABLE IF EXISTS i_keys");
            s.execute("DROP TABLE IF EXISTS i_charges");
            s.execute("CREATE TABLE i_keys (idem_key text PRIMARY KEY, charge_id bigint, created_at timestamptz DEFAULT now())");
            s.execute("CREATE TABLE i_charges (charge_id bigserial PRIMARY KEY, hold_id text NOT NULL, cents int NOT NULL)");
        }
        // The client retries the same request 8 times concurrently (a flaky network plus an impatient user).
        String key = UUID.randomUUID().toString();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<Long>> fs = new ArrayList<>();
        for (int i = 0; i < 8; i++) fs.add(pool.submit(() -> { go.await(); return confirmAndCharge(key, "hold-7", 1_250); }));
        go.countDown();
        Set<Long> chargeIds = new HashSet<>();
        for (Future<Long> f : fs) chargeIds.add(f.get());
        pool.shutdown();
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement();
             ResultSet rs = s.executeQuery("SELECT count(*) FROM i_charges")) {
            rs.next();
            if (rs.getInt(1) != 1 || chargeIds.size() != 1) throw new AssertionError(rs.getInt(1) + " charges");
        }
        System.out.println("8 concurrent retries with one idempotency key: 1 charge, every caller got charge " + chargeIds);
    }

    static long confirmAndCharge(String key, String holdId, int cents) throws SQLException {
        try (Connection c = DriverManager.getConnection(URL)) {
            c.setAutoCommit(false);
            try (PreparedStatement claim = c.prepareStatement(
                    "INSERT INTO i_keys (idem_key) VALUES (?) ON CONFLICT (idem_key) DO NOTHING")) {
                claim.setString(1, key);
                if (claim.executeUpdate() == 0) {                    // seen before: return the stored result
                    c.rollback();
                    return storedResult(c, key);
                }
            }
            long chargeId;
            try (PreparedStatement charge = c.prepareStatement(
                    "INSERT INTO i_charges (hold_id, cents) VALUES (?, ?) RETURNING charge_id")) {
                charge.setString(1, holdId);
                charge.setInt(2, cents);
                try (ResultSet rs = charge.executeQuery()) { rs.next(); chargeId = rs.getLong(1); }
            }
            try (PreparedStatement save = c.prepareStatement("UPDATE i_keys SET charge_id = ? WHERE idem_key = ?")) {
                save.setLong(1, chargeId);
                save.setString(2, key);
                save.executeUpdate();
            }
            c.commit();                                              // key, work and result commit together
            return chargeId;
        }
    }

    static long storedResult(Connection c, String key) throws SQLException {
        try (PreparedStatement q = c.prepareStatement("SELECT charge_id FROM i_keys WHERE idem_key = ?")) {
            q.setString(1, key);
            try (ResultSet rs = q.executeQuery()) { rs.next(); return rs.getLong(1); }
        }
    }
}

Design notes for idempotency keys:

  • The client generates the key, once per user intent (one click of "Pay"), and reuses it for every retry of that intent. A server-generated key can't protect against a retry of a request whose response was lost.
  • Store the key and the work in one transaction. If they commit separately, a crash between them either loses the key (and the retry repeats the work) or keeps a key for work that never happened.
  • When the work includes an external call (a payment provider), the database transaction can't cover it. Pass your idempotency key through to the provider (Stripe and most payment APIs accept one), record the key as "in progress" before the call, and on a retry that finds "in progress", ask the provider what happened rather than calling again.
  • Check that the retry matches the original. A retry with the same key but a different amount is a client bug; reject it with an error rather than returning the old result.
  • Expire keys after a window (24 hours is common) so the table doesn't grow forever.

In the booking flow, the hold ID itself is a natural idempotency key for confirm: confirming the same hold twice should return the same booking, which is exactly what the complete service does in memory.

Inventory decrement for flash sales

Seats are distinct items: A7 is not A8. Much inventory is fungible: 100 identical units of one product, and the only question is whether the count is still above zero. The race is a read-modify-write on a counter, and the naive code oversells:

stock = SELECT stock FROM products WHERE id = 1     -- 1 left
if stock > 0:
    UPDATE products SET stock = :stock - 1 ...      -- two buyers both write 0, both get the item

The fix is to make the decrement and the check one atomic statement, and let the database tell you whether it applied:

CREATE TABLE products (id int PRIMARY KEY, stock int NOT NULL CHECK (stock >= 0));
INSERT INTO products VALUES (1, 2);

-- Atomic: the WHERE re-checks stock under the row lock the UPDATE takes.
-- 1 row affected (or a row returned) = you got one, 0 rows = sold out.
UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0 RETURNING stock;
UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0 RETURNING stock;
UPDATE products SET stock = stock - 1 WHERE id = 1 AND stock > 0 RETURNING stock;  -- returns nothing

-- Buying several units at once works the same way:
-- UPDATE products SET stock = stock - :qty WHERE id = :id AND stock >= :qty
SELECT stock FROM products WHERE id = 1;

Why this is safe in Postgres even under the default READ COMMITTED isolation: the UPDATE locks the row, and if another transaction changed the row while this one waited for the lock, Postgres re-evaluates the WHERE clause against the new row version before applying the update. So two concurrent decrements of the last unit can't both see stock > 0. The CHECK (stock >= 0) constraint backs it up, so even a buggy code path can't drive the count negative.

The demo below runs 50 buyers × 10 attempts against 100 units, first with the read-then-write code and then with the atomic update:

import os
import threading

import psycopg

URL = os.environ.get("DATABASE_URL", "postgresql://postgres@localhost:5432/postgres")


def reset(stock: int) -> None:
    with psycopg.connect(URL, autocommit=True) as c:
        c.execute("DROP TABLE IF EXISTS fs_products")
        c.execute("CREATE TABLE fs_products (id int PRIMARY KEY, stock int NOT NULL)")  # no CHECK, to expose the bug
        c.execute("INSERT INTO fs_products VALUES (1, %s)", (stock,))


def naive_buy(c: psycopg.Connection) -> bool:
    row = c.execute("SELECT stock FROM fs_products WHERE id = 1").fetchone()
    assert row is not None
    if row[0] <= 0:
        return False
    c.execute("UPDATE fs_products SET stock = %s WHERE id = 1", (row[0] - 1,))  # writes a stale value
    return True


def atomic_buy(c: psycopg.Connection) -> bool:
    cur = c.execute("UPDATE fs_products SET stock = stock - 1 WHERE id = 1 AND stock > 0")
    return cur.rowcount == 1


def run(buy) -> tuple[int, int]:
    reset(100)
    sold: list[int] = []
    gate = threading.Barrier(50)

    def buyer() -> None:
        with psycopg.connect(URL, autocommit=True) as c:
            gate.wait()
            for _ in range(10):
                if buy(c):
                    sold.append(1)

    threads = [threading.Thread(target=buyer) for _ in range(50)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    with psycopg.connect(URL, autocommit=True) as c:
        left = c.execute("SELECT stock FROM fs_products WHERE id = 1").fetchone()
    assert left is not None
    return len(sold), left[0]


if __name__ == "__main__":
    sold, left = run(naive_buy)
    print(f"read-then-write: sold {sold} units of 100, stock column says {left}")
    sold, left = run(atomic_buy)
    print(f"atomic update:   sold {sold} units of 100, stock column says {left}")
    assert (sold, left) == (100, 0)
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

class FlashSaleDemo {
    static final String URL = System.getenv().getOrDefault("JDBC_URL", "jdbc:postgresql://localhost:5432/postgres?user=postgres");

    public static void main(String[] args) throws Exception {
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement()) {
            s.execute("DROP TABLE IF EXISTS fs_products_j");
            s.execute("CREATE TABLE fs_products_j (id int PRIMARY KEY, stock int NOT NULL CHECK (stock >= 0))");
            s.execute("INSERT INTO fs_products_j VALUES (1, 100)");
        }
        AtomicInteger sold = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(50);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<?>> fs = new ArrayList<>();
        for (int b = 0; b < 50; b++) fs.add(pool.submit(() -> {
            try (Connection c = DriverManager.getConnection(URL);
                 PreparedStatement buy = c.prepareStatement(
                         "UPDATE fs_products_j SET stock = stock - 1 WHERE id = 1 AND stock > 0")) {
                go.await();
                for (int i = 0; i < 10; i++) if (buy.executeUpdate() == 1) sold.incrementAndGet();
            }
            return null;
        }));
        go.countDown();
        for (Future<?> f : fs) f.get();
        pool.shutdown();
        try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement();
             ResultSet rs = s.executeQuery("SELECT stock FROM fs_products_j WHERE id = 1")) {
            rs.next();
            if (sold.get() != 100 || rs.getInt(1) != 0) throw new AssertionError(sold + " sold, " + rs.getInt(1) + " left");
        }
        System.out.println("500 purchase attempts on 100 units: sold exactly " + sold.get() + ", stock 0");
    }
}

In five runs on our machine, the read-then-write version told all 500 purchase attempts that they had succeeded, every time, for 100 units of stock, and the stock column still ended between 68 and 80, because the concurrent writes kept overwriting each other with stale values. Every one of those 500 buyers expects a parcel. The atomic version sold exactly 100 and left 0 every time.

When one row is too hot

The atomic update is correct, but every buyer of one product now queues on one row lock. A single Postgres row can typically absorb a few thousand such updates per second (the exact figure depends on hardware and commit latency); a launch that draws tens of thousands of buyers per second needs a different shape. The standard options, roughly in order of complexity:

  • Shard the counter. Split 10,000 units into 20 rows of 500 (inventory_buckets(product_id, bucket, stock)), and have each buyer decrement a random bucket, trying another if it's empty. Contention drops by the number of buckets; the cost is a slightly more complex "sold out" check.
  • Move the hot counter to memory. Redis DECR (or a short Lua script that checks and decrements) is single-threaded and atomic, handles far higher rates, and the database is updated asynchronously from a queue. You trade strict durability for throughput, and need a reconciliation job.
  • Queue the buyers. Put purchase requests on a queue and let one consumer per product allocate stock in order: the producer–consumer pattern turns contention into a line. Buyers get "you're in the queue" and a result moments later. Ticketing sites with virtual waiting rooms work this way.
  • Pre-allocate tokens. Generate one row per unit ahead of time and let each buyer claim one with UPDATE … WHERE claimed_by IS NULL … LIMIT 1 FOR UPDATE SKIP LOCKED, so buyers grab different rows instead of fighting over one.

The same in-process logic, an AtomicInteger with a CAS loop that refuses to go below zero, appears in Thread-Safe Class Design.

A complete movie-seat booking service

Now everything together, in memory, as you'd write it in a machine-coding round. The requirements:

  • shows have named seats;
  • hold(show, user, seats) claims all requested seats or none, for a fixed time-to-live;
  • confirm(holdId) turns a live hold into a booking, and is idempotent: confirming the same hold twice returns the same booking;
  • release(holdId) gives the seats back early;
  • expired holds never block anyone (lazy expiry), and expireHolds() tidies them up (the sweep, run by a scheduler in production);
  • time comes from an injected clock.

The concurrency design, in the sentences you'd say aloud:

  • Shared state: each show's seat map, plus the service's maps of holds and bookings.
  • Invariants: a seat is in exactly one of AVAILABLE, HELD (by exactly one live hold) or BOOKED; a hold's seats are either all held by it or it's dead; a hold produces at most one booking.
  • Lock granularity: one lock per show. Every invariant involving seats lives within a single show, so different shows never contend, and multi-seat holds are atomic without lock ordering. If a single show became a hotspot, per-seat locks in sorted order (Option 1 above) are the upgrade.
  • What happens outside the lock: payment, notification and anything slow. Inside the lock, only map lookups and field writes.
  • Across instances: this service is the in-process layer. With several instances, the same transitions become the conditional SQL updates above, with the unique index behind them.
classDiagram
    class BookingService {
        -Clock clock
        -Duration holdTtl
        -Map~String, Show~ shows
        -Map~String, Hold~ holds
        -Map~String, Booking~ bookingsByHold
        +addShow(id, seatIds)
        +hold(showId, user, seatIds) Hold
        +confirm(holdId) Booking
        +release(holdId) boolean
        +expireHolds() int
    }
    class Show {
        -ReentrantLock lock
        -Map~String, SeatSlot~ seats
    }
    class SeatSlot {
        SeatStatus status
        String holdId
        Instant heldUntil
    }
    class Hold {
        <<record>>
        String id
        String showId
        String user
        List seats
        Instant expiresAt
    }
    class Booking {
        <<record>>
        String id
        String holdId
        String user
        List seats
    }
    BookingService "1" --> "*" Show
    Show "1" *-- "*" SeatSlot
    BookingService --> Hold
    BookingService --> Booking
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.ReentrantLock;

class MovieBookingTest {
    public static void main(String[] args) throws Exception {
        exactlyOneWinnerPerSeat();
        multiSeatHoldsNeverOverlap();
        expiredHoldsReleaseLazilyAndBySweep();
        confirmIsIdempotentUnderConcurrency();
        System.out.println("all movie-booking tests passed");
    }

    static List<String> seatIds(int n) {
        List<String> ids = new ArrayList<>();
        for (int i = 1; i <= n; i++) ids.add("A" + i);
        return ids;
    }

    /** 64 threads each try to hold-and-confirm all 20 seats in a random order, 50 rounds. */
    static void exactlyOneWinnerPerSeat() throws Exception {
        for (int round = 0; round < 50; round++) {
            BookingService svc = new BookingService(Clock.systemUTC(), Duration.ofMinutes(5));
            svc.addShow("show-1", seatIds(20));
            ConcurrentHashMap<String, String> winnerBySeat = new ConcurrentHashMap<>();
            AtomicInteger duplicates = new AtomicInteger();
            race(64, t -> {
                List<String> order = new ArrayList<>(seatIds(20));
                Collections.shuffle(order, new Random(t));
                for (String seat : order) {
                    try {
                        Hold h = svc.hold("show-1", "user" + t, List.of(seat));
                        svc.confirm(h.id());
                        if (winnerBySeat.putIfAbsent(seat, "user" + t) != null) duplicates.incrementAndGet();
                    } catch (SeatUnavailableException expected) { }
                }
            });
            if (duplicates.get() != 0 || winnerBySeat.size() != 20 || svc.bookedCount("show-1") != 20)
                throw new AssertionError("round " + round + ": " + duplicates + " duplicates, " + winnerBySeat.size() + " winners");
        }
        System.out.println("50 rounds x 64 threads x 20 seats: exactly one winner per seat");
    }

    /** Overlapping pairs held from 32 threads: no seat may end up in two bookings. */
    static void multiSeatHoldsNeverOverlap() throws Exception {
        BookingService svc = new BookingService(Clock.systemUTC(), Duration.ofMinutes(5));
        svc.addShow("show-1", seatIds(40));
        List<Booking> bookings = Collections.synchronizedList(new ArrayList<>());
        race(32, t -> {
            Random r = new Random(t);
            for (int i = 0; i < 30; i++) {
                int a = 1 + r.nextInt(39);
                try { bookings.add(svc.confirm(svc.hold("show-1", "u" + t, List.of("A" + (a + 1), "A" + a)).id())); }
                catch (SeatUnavailableException expected) { }
            }
        });
        Set<String> seen = new HashSet<>();
        for (Booking b : bookings) for (String s : b.seats()) if (!seen.add(s)) throw new AssertionError(s + " booked twice");
        if (seen.size() != svc.bookedCount("show-1")) throw new AssertionError("seat map disagrees with bookings");
        System.out.println(bookings.size() + " pair bookings from 32 threads, no seat in two bookings");
    }

    static void expiredHoldsReleaseLazilyAndBySweep() {
        MutableClock clock = new MutableClock(Instant.parse("2026-11-10T18:00:00Z"));
        BookingService svc = new BookingService(clock, Duration.ofMinutes(5));
        svc.addShow("show-1", seatIds(3));

        Hold alice = svc.hold("show-1", "alice", List.of("A1"));
        clock.advance(Duration.ofMinutes(6));
        Hold bob = svc.hold("show-1", "bob", List.of("A1"));        // lazy expiry: no sweep has run
        try { svc.confirm(alice.id()); throw new AssertionError("expired hold confirmed"); }
        catch (HoldExpiredException expected) { }
        svc.confirm(bob.id());

        svc.hold("show-1", "carol", List.of("A2", "A3"));
        clock.advance(Duration.ofMinutes(6));
        int swept = svc.expireHolds();                                // the sweep tidies up
        if (swept != 1 || svc.status("show-1", "A2") != SeatStatus.AVAILABLE) throw new AssertionError("sweep failed");
        System.out.println("expired holds: taken over lazily, then swept (" + swept + " hold released)");
    }

    static void confirmIsIdempotentUnderConcurrency() throws Exception {
        BookingService svc = new BookingService(Clock.systemUTC(), Duration.ofMinutes(5));
        svc.addShow("show-1", seatIds(5));
        Hold h = svc.hold("show-1", "dave", List.of("A4", "A5"));
        Set<String> bookingIds = ConcurrentHashMap.newKeySet();
        race(8, t -> bookingIds.add(svc.confirm(h.id()).id()));      // a client retrying confirm 8 times at once
        if (bookingIds.size() != 1 || svc.bookedCount("show-1") != 2) throw new AssertionError(bookingIds);
        System.out.println("8 concurrent confirms of one hold: one booking " + bookingIds);
    }

    interface Body { void run(int threadIndex) throws Exception; }

    static void race(int threads, Body body) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(threads);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<?>> fs = new ArrayList<>();
        for (int t = 0; t < threads; t++) {
            int index = t;
            fs.add(pool.submit(() -> { go.await(); body.run(index); return null; }));
        }
        go.countDown();
        for (Future<?> f : fs) f.get(30, TimeUnit.SECONDS);    // a deadlock fails the test instead of hanging it
        pool.shutdown();
    }
}

enum SeatStatus { AVAILABLE, HELD, BOOKED }

record Hold(String id, String showId, String user, List<String> seats, Instant expiresAt) {
    Hold { seats = List.copyOf(seats); }
}

record Booking(String id, String holdId, String showId, String user, List<String> seats) {
    Booking { seats = List.copyOf(seats); }
}

class SeatUnavailableException extends RuntimeException {
    SeatUnavailableException(String m) { super(m); }
}

class HoldExpiredException extends RuntimeException {
    HoldExpiredException(String m) { super(m); }
}

/** One show's seats. Every field of every SeatSlot is guarded by {@code lock}. */
final class Show {
    static final class SeatSlot {
        SeatStatus status = SeatStatus.AVAILABLE;
        String holdId;
        Instant heldUntil;

        boolean isFree(Instant now) {
            return status == SeatStatus.AVAILABLE
                || (status == SeatStatus.HELD && !heldUntil.isAfter(now));   // lazy expiry
        }
    }

    final String id;
    final ReentrantLock lock = new ReentrantLock();
    final Map<String, SeatSlot> seats = new HashMap<>();

    Show(String id, List<String> seatIds) {
        this.id = id;
        for (String s : seatIds) seats.put(s, new SeatSlot());
    }
}

/**
 * Thread-safe. Locking policy: each show's seat slots are guarded by that show's lock, and
 * every state transition (hold, confirm, release, expire) runs entirely under it. The holds
 * and bookings maps are concurrent maps; they are only written while the relevant show's lock is held.
 */
final class BookingService {
    private final Clock clock;
    private final Duration holdTtl;
    private final Map<String, Show> shows = new ConcurrentHashMap<>();
    private final Map<String, Hold> holds = new ConcurrentHashMap<>();
    private final Map<String, Booking> bookingsByHold = new ConcurrentHashMap<>();
    private final AtomicLong ids = new AtomicLong();

    BookingService(Clock clock, Duration holdTtl) {
        this.clock = clock;
        this.holdTtl = holdTtl;
    }

    void addShow(String showId, List<String> seatIds) {
        if (shows.putIfAbsent(showId, new Show(showId, seatIds)) != null) throw new IllegalArgumentException("duplicate show");
    }

    Hold hold(String showId, String user, List<String> seatIds) {
        Show show = show(showId);
        List<String> wanted = seatIds.stream().distinct().toList();
        if (wanted.isEmpty()) throw new IllegalArgumentException("no seats");
        show.lock.lock();
        try {
            Instant now = clock.instant();
            for (String s : wanted) {                                  // check every seat first: all or nothing
                Show.SeatSlot slot = show.seats.get(s);
                if (slot == null) throw new IllegalArgumentException("no seat " + s);
                if (!slot.isFree(now)) throw new SeatUnavailableException(s + " is " + slot.status);
            }
            Hold h = new Hold("H" + ids.incrementAndGet(), showId, user, wanted, now.plus(holdTtl));
            for (String s : wanted) {                                  // then claim them all
                Show.SeatSlot slot = show.seats.get(s);
                if (slot.status == SeatStatus.HELD) holds.remove(slot.holdId);  // displace an expired hold
                slot.status = SeatStatus.HELD;
                slot.holdId = h.id();
                slot.heldUntil = h.expiresAt();
            }
            holds.put(h.id(), h);
            return h;
        } finally {
            show.lock.unlock();
        }
    }

    /** Idempotent: confirming an already-confirmed hold returns the same booking. */
    Booking confirm(String holdId) {
        Booking existing = bookingsByHold.get(holdId);                 // fast path for retries
        if (existing != null) return existing;
        Hold h = holds.get(holdId);
        if (h == null) throw new HoldExpiredException("unknown or expired hold " + holdId);
        Show show = show(h.showId());
        show.lock.lock();
        try {
            existing = bookingsByHold.get(holdId);                     // re-check under the lock
            if (existing != null) return existing;
            Instant now = clock.instant();
            for (String s : h.seats()) {
                Show.SeatSlot slot = show.seats.get(s);
                boolean stillOurs = slot.status == SeatStatus.HELD && holdId.equals(slot.holdId)
                        && slot.heldUntil.isAfter(now);
                if (!stillOurs) throw new HoldExpiredException("hold " + holdId + " lost seat " + s);
            }
            for (String s : h.seats()) {
                Show.SeatSlot slot = show.seats.get(s);
                slot.status = SeatStatus.BOOKED;
                slot.heldUntil = null;
            }
            Booking b = new Booking("B" + ids.incrementAndGet(), holdId, h.showId(), h.user(), h.seats());
            bookingsByHold.put(holdId, b);
            holds.remove(holdId);
            return b;
        } finally {
            show.lock.unlock();
        }
    }

    boolean release(String holdId) {
        Hold h = holds.get(holdId);
        if (h == null) return false;
        Show show = show(h.showId());
        show.lock.lock();
        try {
            return freeSeatsOf(show, h);
        } finally {
            show.lock.unlock();
        }
    }

    /** The sweep: run every few seconds by a ScheduledExecutorService in production. */
    int expireHolds() {
        int released = 0;
        Instant now = clock.instant();
        for (Hold h : holds.values()) {
            if (h.expiresAt().isAfter(now)) continue;
            Show show = show(h.showId());
            show.lock.lock();
            try {
                if (freeSeatsOf(show, h)) released++;
            } finally {
                show.lock.unlock();
            }
        }
        return released;
    }

    /** Caller holds show.lock. Frees only seats this hold still owns. */
    private boolean freeSeatsOf(Show show, Hold h) {
        if (holds.remove(h.id()) == null) return false;                // already confirmed, released or displaced
        for (String s : h.seats()) {
            Show.SeatSlot slot = show.seats.get(s);
            if (slot.status == SeatStatus.HELD && h.id().equals(slot.holdId)) {
                slot.status = SeatStatus.AVAILABLE;
                slot.holdId = null;
                slot.heldUntil = null;
            }
        }
        return true;
    }

    SeatStatus status(String showId, String seat) {
        Show show = show(showId);
        show.lock.lock();
        try { return show.seats.get(seat).status; } finally { show.lock.unlock(); }
    }

    int bookedCount(String showId) {
        Show show = show(showId);
        show.lock.lock();
        try { return (int) show.seats.values().stream().filter(s -> s.status == SeatStatus.BOOKED).count(); }
        finally { show.lock.unlock(); }
    }

    private Show show(String id) {
        Show s = shows.get(id);
        if (s == null) throw new IllegalArgumentException("no show " + id);
        return s;
    }
}

/** A test clock that only moves when told to. */
final class MutableClock extends Clock {
    private volatile Instant now;
    MutableClock(Instant start) { now = start; }
    void advance(Duration d) { now = now.plus(d); }
    @Override public Instant instant() { return now; }
    @Override public ZoneId getZone() { return ZoneOffset.UTC; }
    @Override public Clock withZone(ZoneId zone) { return this; }
}
import itertools
import random
import threading
import time
from dataclasses import dataclass
from enum import Enum
from typing import Callable


class SeatStatus(Enum):
    AVAILABLE = "AVAILABLE"
    HELD = "HELD"
    BOOKED = "BOOKED"


class SeatUnavailable(Exception):
    pass


class HoldExpired(Exception):
    pass


@dataclass(frozen=True)
class Hold:
    id: str
    show_id: str
    user: str
    seats: tuple[str, ...]
    expires_at: float


@dataclass(frozen=True)
class Booking:
    id: str
    hold_id: str
    user: str
    seats: tuple[str, ...]


class SeatSlot:
    __slots__ = ("status", "hold_id", "held_until")

    def __init__(self) -> None:
        self.status = SeatStatus.AVAILABLE
        self.hold_id: str | None = None
        self.held_until = 0.0

    def is_free(self, now: float) -> bool:
        return self.status is SeatStatus.AVAILABLE or (
            self.status is SeatStatus.HELD and self.held_until <= now)  # lazy expiry


class Show:
    def __init__(self, seat_ids: list[str]) -> None:
        self.lock = threading.Lock()  # guards every SeatSlot in this show
        self.seats = {s: SeatSlot() for s in seat_ids}


class BookingService:
    def __init__(self, now: Callable[[], float], hold_ttl_s: float) -> None:
        self._now, self._ttl = now, hold_ttl_s
        self._shows: dict[str, Show] = {}
        self._holds: dict[str, Hold] = {}       # written only under the owning show's lock
        self._bookings: dict[str, Booking] = {}  # keyed by hold id, same rule
        self._ids = itertools.count(1)           # next() on a count is atomic in CPython

    def add_show(self, show_id: str, seat_ids: list[str]) -> None:
        self._shows[show_id] = Show(seat_ids)

    def hold(self, show_id: str, user: str, seat_ids: list[str]) -> Hold:
        show, wanted = self._shows[show_id], tuple(dict.fromkeys(seat_ids))
        with show.lock:
            now = self._now()
            for s in wanted:
                if not show.seats[s].is_free(now):
                    raise SeatUnavailable(s)
            h = Hold(f"H{next(self._ids)}", show_id, user, wanted, now + self._ttl)
            for s in wanted:
                slot = show.seats[s]
                if slot.status is SeatStatus.HELD and slot.hold_id:
                    self._holds.pop(slot.hold_id, None)  # displace an expired hold
                slot.status, slot.hold_id, slot.held_until = SeatStatus.HELD, h.id, h.expires_at
            self._holds[h.id] = h
            return h

    def confirm(self, hold_id: str) -> Booking:
        if (b := self._bookings.get(hold_id)) is not None:
            return b
        h = self._holds.get(hold_id)
        if h is None:
            raise HoldExpired(hold_id)
        show = self._shows[h.show_id]
        with show.lock:
            if (b := self._bookings.get(hold_id)) is not None:  # re-check under the lock
                return b
            now = self._now()
            for s in h.seats:
                slot = show.seats[s]
                if not (slot.status is SeatStatus.HELD and slot.hold_id == hold_id and slot.held_until > now):
                    raise HoldExpired(f"{hold_id} lost {s}")
            for s in h.seats:
                show.seats[s].status = SeatStatus.BOOKED
            b = Booking(f"B{next(self._ids)}", hold_id, h.user, h.seats)
            self._bookings[hold_id] = b
            self._holds.pop(hold_id, None)
            return b

    def expire_holds(self) -> int:
        released, now = 0, self._now()
        for h in list(self._holds.values()):  # copy: other threads may change the dict
            if h.expires_at > now:
                continue
            show = self._shows[h.show_id]
            with show.lock:
                if self._holds.pop(h.id, None) is None:
                    continue
                for s in h.seats:
                    slot = show.seats[s]
                    if slot.status is SeatStatus.HELD and slot.hold_id == h.id:
                        slot.status, slot.hold_id = SeatStatus.AVAILABLE, None
                released += 1
        return released

    def booked_count(self, show_id: str) -> int:
        show = self._shows[show_id]
        with show.lock:
            return sum(s.status is SeatStatus.BOOKED for s in show.seats.values())

    def status(self, show_id: str, seat: str) -> SeatStatus:
        show = self._shows[show_id]
        with show.lock:
            return show.seats[seat].status


def race(n: int, body: Callable[[int], None]) -> None:
    gate, errors = threading.Barrier(n), []

    def run(i: int) -> None:
        try:
            gate.wait()
            body(i)
        except BaseException as e:
            errors.append(e)

    threads = [threading.Thread(target=run, args=(i,)) for i in range(n)]
    for t in threads:
        t.start()
    for t in threads:
        t.join(timeout=30)
        assert not t.is_alive(), "deadlock or hang"
    assert not errors, errors[0]


if __name__ == "__main__":
    seats = [f"A{i}" for i in range(1, 21)]
    for _ in range(20):
        svc = BookingService(time.monotonic, 300)
        svc.add_show("show-1", seats)
        winners: dict[str, str] = {}
        duplicates: list[str] = []

        def attempt(t: int) -> None:
            order = seats[:]
            random.Random(t).shuffle(order)
            for s in order:
                try:
                    svc.confirm(svc.hold("show-1", f"user{t}", [s]).id)
                    if winners.setdefault(s, f"user{t}") != f"user{t}":
                        duplicates.append(s)
                except SeatUnavailable:
                    pass

        race(32, attempt)
        assert not duplicates and len(winners) == 20 and svc.booked_count("show-1") == 20
    print("20 rounds x 32 threads x 20 seats: exactly one winner per seat")

    fake_now = [1_000.0]
    svc = BookingService(lambda: fake_now[0], 300)
    svc.add_show("show-1", ["A1", "A2"])
    alice = svc.hold("show-1", "alice", ["A1"])
    fake_now[0] += 360
    bob = svc.hold("show-1", "bob", ["A1"])  # lazy expiry
    try:
        svc.confirm(alice.id)
        raise AssertionError("expired hold confirmed")
    except HoldExpired:
        pass
    assert svc.confirm(bob.id) == svc.confirm(bob.id)  # idempotent
    svc.hold("show-1", "carol", ["A2"])
    fake_now[0] += 360
    assert svc.expire_holds() == 1 and svc.status("show-1", "A2") is SeatStatus.AVAILABLE
    print("expiry (lazy and swept) and idempotent confirm: ok")
// Node: one thread, so each method's synchronous body is already atomic. The races live
// at the awaits between hold and confirm (payment), which the test interleaves randomly.
type SeatStatus = "AVAILABLE" | "HELD" | "BOOKED";

class SeatUnavailableError extends Error {}
class HoldExpiredError extends Error {}

interface Hold { readonly id: string; readonly showId: string; readonly user: string; readonly seats: readonly string[]; readonly expiresAt: number }
interface Booking { readonly id: string; readonly holdId: string; readonly user: string; readonly seats: readonly string[] }
interface SeatSlot { status: SeatStatus; holdId?: string; heldUntil: number }

class BookingService {
  private shows = new Map<string, Map<string, SeatSlot>>();
  private holds = new Map<string, Hold>();
  private bookings = new Map<string, Booking>(); // keyed by hold id
  private nextId = 1;

  constructor(private readonly now: () => number, private readonly holdTtlMs: number) {}

  addShow(showId: string, seatIds: string[]): void {
    this.shows.set(showId, new Map(seatIds.map((s) => [s, { status: "AVAILABLE", heldUntil: 0 }])));
  }

  /** Synchronous on purpose: no await between the check and the claim. */
  hold(showId: string, user: string, seatIds: string[]): Hold {
    const seats = this.seatsOf(showId);
    const wanted = [...new Set(seatIds)];
    const now = this.now();
    for (const s of wanted) {
      const slot = seats.get(s);
      if (!slot) throw new Error(`no seat ${s}`);
      const free = slot.status === "AVAILABLE" || (slot.status === "HELD" && slot.heldUntil <= now);
      if (!free) throw new SeatUnavailableError(s);
    }
    const hold: Hold = { id: `H${this.nextId++}`, showId, user, seats: wanted, expiresAt: now + this.holdTtlMs };
    for (const s of wanted) {
      const slot = seats.get(s)!;
      if (slot.status === "HELD" && slot.holdId) this.holds.delete(slot.holdId); // displace an expired hold
      Object.assign(slot, { status: "HELD", holdId: hold.id, heldUntil: hold.expiresAt });
    }
    this.holds.set(hold.id, hold);
    return hold;
  }

  confirm(holdId: string): Booking {
    const existing = this.bookings.get(holdId);
    if (existing) return existing; // idempotent
    const hold = this.holds.get(holdId);
    if (!hold) throw new HoldExpiredError(holdId);
    const seats = this.seatsOf(hold.showId);
    const now = this.now();
    for (const s of hold.seats) {
      const slot = seats.get(s)!;
      if (!(slot.status === "HELD" && slot.holdId === holdId && slot.heldUntil > now)) {
        throw new HoldExpiredError(`${holdId} lost ${s}`);
      }
    }
    for (const s of hold.seats) seats.get(s)!.status = "BOOKED";
    const booking: Booking = { id: `B${this.nextId++}`, holdId, user: hold.user, seats: hold.seats };
    this.bookings.set(holdId, booking);
    this.holds.delete(holdId);
    return booking;
  }

  expireHolds(): number {
    let released = 0;
    const now = this.now();
    for (const hold of [...this.holds.values()]) {
      if (hold.expiresAt > now) continue;
      this.holds.delete(hold.id);
      for (const s of hold.seats) {
        const slot = this.seatsOf(hold.showId).get(s)!;
        if (slot.status === "HELD" && slot.holdId === hold.id) Object.assign(slot, { status: "AVAILABLE", holdId: undefined });
      }
      released++;
    }
    return released;
  }

  bookedCount(showId: string): number {
    return [...this.seatsOf(showId).values()].filter((s) => s.status === "BOOKED").length;
  }

  private seatsOf(showId: string): Map<string, SeatSlot> {
    const seats = this.shows.get(showId);
    if (!seats) throw new Error(`no show ${showId}`);
    return seats;
  }
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const seatIds = Array.from({ length: 20 }, (_, i) => `A${i + 1}`);

// 32 concurrent "users", each holding a random seat, "paying" for 0-5 ms, then confirming.
for (let round = 0; round < 20; round++) {
  const svc = new BookingService(Date.now, 300_000);
  svc.addShow("show-1", seatIds);
  const winners = new Map<string, string>();
  await Promise.all(
    Array.from({ length: 32 }, async (_, t) => {
      for (const seat of [...seatIds].sort(() => Math.random() - 0.5)) {
        try {
          const hold = svc.hold("show-1", `user${t}`, [seat]);
          await sleep(Math.random() * 5); // payment: other users run here
          svc.confirm(hold.id);
          if (winners.has(seat)) throw new Error(`${seat} sold twice`);
          winners.set(seat, `user${t}`);
        } catch (e) {
          if (!(e instanceof SeatUnavailableError)) throw e;
        }
      }
    }),
  );
  if (winners.size !== 20 || svc.bookedCount("show-1") !== 20) throw new Error(`round ${round}: ${winners.size}`);
}
console.log("20 rounds x 32 async users x 20 seats: exactly one winner per seat");

let fakeNow = 1_000_000;
const svc = new BookingService(() => fakeNow, 300_000);
svc.addShow("show-1", ["A1", "A2"]);
const alice = svc.hold("show-1", "alice", ["A1"]);
fakeNow += 360_000;
const bob = svc.hold("show-1", "bob", ["A1"]); // lazy expiry
let aliceFailed = false;
try { svc.confirm(alice.id); } catch (e) { aliceFailed = e instanceof HoldExpiredError; }
if (!aliceFailed || svc.confirm(bob.id) !== svc.confirm(bob.id)) throw new Error("expiry or idempotency broken");
svc.hold("show-1", "carol", ["A2"]);
fakeNow += 360_000;
if (svc.expireHolds() !== 1) throw new Error("sweep failed");
console.log("expiry (lazy and swept) and idempotent confirm: ok");

Each language's test passed on every run on our machine. In the Java output, the pair test reports a different number of successful pair bookings each run (16 to 18 of the 960 attempts across five runs), because which pairs win depends on scheduling; the assertion that matters, that no seat appears in two bookings, held every time.

A few details in the Java code are worth calling out in an interview, because each one prevents a specific bug:

  • hold checks every seat before claiming any. That's what makes a multi-seat hold all-or-nothing under one lock, with no rollback.
  • confirm re-checks bookingsByHold under the lock. The unlocked read is a fast path for retries; the locked read is the real check-then-act, so two concurrent confirms of one hold produce one booking.
  • confirm verifies the hold still owns each seat, not just that the hold exists. After lazy expiry, a new hold may have taken a seat while the old Hold object still sat in the map.
  • freeSeatsOf frees only seats whose holdId matches. A late release or sweep of an old hold must never free a seat that now belongs to someone else. That's the in-memory version of UPDATE … WHERE hold_id = ?.
  • The tests use start gates, timeouts and invariant checks, as described in testing concurrent code, and the expiry tests use a fake clock rather than sleeping five minutes.

The movie booking case study wraps this core in the rest of the domain (theatres, screens, pricing tiers, payments), and is the place to practise presenting it end to end.

From one instance to many

To run this service on several instances, keep the same states and transitions and move them into SQL, one conditional statement each:

TransitionStatement (all in short transactions)
holdUPDATE seats SET status='HELD', hold_id=:h, held_until=now()+:ttl WHERE show_id=:s AND seat_no = ANY(:seats) AND (status='AVAILABLE' OR (status='HELD' AND held_until <= now())); succeed only if the row count equals the number of seats, otherwise roll back
confirmUPDATE seats SET status='BOOKED' WHERE hold_id=:h AND held_until > now(), then insert into bookings (the partial unique index guards it), keyed by the hold ID for idempotency
releaseUPDATE seats SET status='AVAILABLE', hold_id=NULL WHERE hold_id=:h AND status='HELD'
sweepUPDATE seats SET status='AVAILABLE', hold_id=NULL WHERE status='HELD' AND held_until <= now(), using the seats_expiring index

The multi-seat hold uses the row count as its all-or-nothing check: if four seats were requested and only three rows matched, one seat was taken, so the transaction rolls back and releases the other three. Because the UPDATE locks rows as it goes, two multi-seat holds that overlap can deadlock if they lock rows in different orders; Postgres detects this and aborts one, which your code retries, or you avoid it by locking the rows first with SELECT … ORDER BY seat_no FOR UPDATE. The in-memory service and its tests are then a precise specification of what the SQL must do.

Common mistakes

MistakeWhat goes wrongFix
Check availability, then book, in two stepsTwo users both pass the checkOne atomic step: lock, CAS, putIfAbsent or a conditional UPDATE
synchronized on the booking method with several app instancesEach instance has its own lockEnforce in the database: conditional update plus a unique constraint
Holding a row lock (or an in-memory lock) during paymentConnection pool exhaustion, all requests stallHold → commit → pay → confirm, with short transactions
Locking several seats in request orderDeadlock between overlapping multi-seat requestsSort the seats, or use one lock per show
Holds without expiryAbandoned carts lock seats foreverTTL on every hold; lazy expiry for correctness, sweep for tidiness
Expiry only by sweepSeats blocked until the sweeper runs, forever if it diesTreat expired holds as free at check time
Confirm only checks that the hold existsConfirms a hold whose seat was taken over after expiryVerify the hold still owns every seat and hasn't expired
Release frees seats by seat ID aloneA late release frees someone else's seatRelease only where hold_id matches
No idempotency on confirm or paymentRetries charge twice or book twiceClient-generated key, stored with the work in one transaction
SELECT stock then UPDATE stock = :valueOversells and loses updatesUPDATE … SET stock = stock - 1 WHERE stock > 0, check the row count
No unique constraint "because the code is correct"One buggy path double-books silentlyPartial unique index on confirmed bookings
Calling Clock/time.now() directlyExpiry tests need real sleepsInject the clock

Interview questions

  1. "Two users click 'Book' on the same seat at the same moment. Walk me through what your system does." Both requests try to hold the seat. In-process, the show's lock (or a CAS on the seat) makes the hold atomic, so one succeeds and the other gets "seat unavailable". With several instances, the hold is a conditional UPDATE … WHERE status = 'AVAILABLE', and the loser sees 0 rows affected. Behind both, a partial unique index guarantees at most one confirmed booking per seat.

  2. "Pessimistic or optimistic locking for seat booking?" For the hold step, a conditional update (optimistic in spirit) is usually best: no lock is held between statements, and contention on any one seat is low except at launch. For a single extremely hot row, such as one inventory counter, pessimistic or an atomic decrement avoids retry storms. Never hold a pessimistic lock across user think-time or payment.

  3. "Why do you need holds? Why not book directly after payment?" Because payment takes seconds to minutes, and without a hold, the seat could be sold during payment, leaving you with a paid customer and no seat. A hold reserves the seat for a bounded time, and the TTL ensures abandoned sessions release it.

  4. "How do holds expire?" Lazily for correctness: any check treats a hold past its expiresAt as free, so an expired hold never blocks anyone even if background jobs fail. Plus a periodic sweep (or a delay queue) to tidy stored state, update seat maps and send "hold expired" notifications. Confirm must check that the hold is still live and still owns its seats.

  5. "A user pays at the last second and the confirm arrives after the hold expired. What now?" The confirm fails, because the seat may already be someone else's. Mitigate with a short grace period and by authorising rather than capturing payment until confirm succeeds; if a capture already happened, refund automatically and tell the user. You can make the case rare but not impossible, so design the compensation.

  6. "How do you book four seats together, all or nothing?" Under one show-level lock, check all four, then claim all four. With per-seat locks, take them in sorted order to avoid deadlock. With claims or CAS, claim one by one and roll back on failure. In SQL, a single UPDATE … WHERE seat_no = ANY(:seats) AND <free> and compare the row count with four, rolling back if it's less.

  7. "Your booking service runs on 10 instances. Does your ReentrantLock still work?" No. Each instance has its own lock. The guarantee must come from shared state: conditional updates or SELECT … FOR UPDATE in the database, a unique constraint behind them, or an atomic operation in Redis such as SET key value NX PX ttl. Distributed locks are possible, but they need fencing tokens to be safe and are usually unnecessary when the database can do the conditional write.

  8. "What's an idempotency key and where does it go in this design?" A client-generated unique ID for one user intent, sent with every retry. The server stores it, in the same transaction as the work, behind a unique constraint, and returns the stored result when it sees the key again. In booking, the hold ID is the natural key for confirm, and a separate key is passed to the payment provider so a retried charge isn't duplicated.

  9. "How do you sell 1,000 units in a flash sale without overselling?" An atomic conditional decrement: UPDATE products SET stock = stock - 1 WHERE id = ? AND stock > 0, treating 0 rows affected as sold out, plus CHECK (stock >= 0). If one row can't take the write rate, shard the counter across buckets, move it to Redis with an atomic decrement and reconcile, or queue buyers and allocate in order.

  10. "How would you test that the booking service never double-books?" A stress test: many rounds, more threads than cores, a start gate, a timeout, worker exceptions collected, and an invariant check of exactly one winner per seat and no seat in two bookings, plus a run against a deliberately broken version to prove the test can fail. Expiry gets deterministic tests with a fake clock. In the database layer, the same race test runs against a real database with one connection per thread.

  11. "Why a partial unique index rather than a plain one on (show_id, seat_no)?" A plain index would forbid a second row for the seat ever, so a cancelled booking would block re-selling the seat. The partial index (WHERE status = 'CONFIRMED') enforces at most one active booking while keeping cancelled rows as history.

  12. "How is hotel booking different from movie seats?" The resource is a room over a date range, so conflicts are overlapping ranges, not equal keys. In-memory, check for overlap under a per-room lock. In Postgres, an exclusion constraint (EXCLUDE USING gist (room_id WITH =, stay WITH &&)) is the range equivalent of the unique index. Often the request is for "any room of type X", which is fungible inventory per night: decrement a per-night count for the room type, then assign specific rooms later.