Skip to main content

Concurrent Seat Locking

Editorial

The Concurrency Problem

Our BookingService from the previous tutorial works correctly in a single-threaded environment. But movie ticket booking is inherently concurrent — on a platform like BookMyShow, hundreds of users may try to book the same show at the same time, especially for popular movies on opening day.

What happens when two users try to hold the same seat simultaneously using our current code?

The race condition:

  1. User A's thread calls create_booking(alice, show, [seat_5C])
  2. User B's thread calls create_booking(bob, show, [seat_5C])
  3. Both threads check show_seat.status == AVAILABLE — both see True
  4. Both threads call show_seat.hold(booking) — both succeed
  5. Seat 5C is now "held" by two different bookings — a double-booking bug

This is a classic Time-of-Check-to-Time-of-Use (TOCTOU) race condition. The status check (step 3) and the status update (step 4) are not atomic — another thread can interleave between them.

In this tutorial, we'll:

  1. Analyze the specific race conditions in our booking system
  2. Implement thread-safe seat locking using a mutex
  3. Explore fine-grained locking for better throughput
  4. Handle the hold timeout in a concurrent environment

Race Conditions in the Booking System

Our system has three critical race conditions:

Race 1: Double Hold — Two users hold the same seat

Thread A and Thread B both enter create_booking for overlapping seats. Both pass the availability check. Both call hold(). Result: the seat's held_by_booking reference is overwritten — one booking thinks it owns a seat it doesn't.

Race 2: Hold + Expire Interleaving

Thread A is in create_booking, holding seats one by one. Meanwhile, the timer thread runs expire_holds() on a different booking that held one of the same seats. Thread A's hold() call succeeds because the timer just released the seat — but Thread A already passed the availability check earlier when the seat was HELD (by the other booking). This can cause inconsistent state.

Race 3: Payment + Expire Race

User A starts payment (make_payment). The hold timer fires (expire_holds). Both threads access the same booking and its ShowSeats. If expire_holds releases the seats while make_payment is transitioning them from HELD to BOOKED, we get a partially-confirmed booking — some seats BOOKED, others AVAILABLE.

Why the existing hold() method isn't safe:

Our current ShowSeat.hold() does check status before updating:

if self._status != ShowSeatStatus.AVAILABLE:
    return False
self._status = ShowSeatStatus.HELD

But this check-then-act sequence is not atomic. Between the if check and the assignment, another thread can change the status.

Race Two Threads for Seat 5C

You are the scheduler below: run Thread A (Alice) and Thread B (Bob) through hold() one step at a time until both pass the check before either writes. Then run the same two threads under the per-show lock, and compare the three lock scopes — including the per-seat deadlock.

Interactive: two threads booking seat 5C, scheduled by the learner one step at a time. With no lock, Thread A (Alice) and Thread B (Bob) run ShowSeat.hold() — each thread's program a small flowchart beside the seat, the status flying to the thread that reads it — and when both read _status AVAILABLE before either writes HELD, both holds succeed: _held_by_booking ends up Bob's while Alice's booking still thinks it owns the seat, a double booking; run one after the other, the second hold() returns False. With the per-show lock, the same threads run create_booking inside with show.lock: a thread that tries while the other holds the lock waits, and the second one in reads HELD and raises "Seat 5C is not available" — exactly one success in every order. A lock-scope act runs Alice (A1 then A3) and Bob (A3 then A1) at the 7 PM show and Carol at the 3 PM show under a global lock (Carol waits too), a per-show lock (no deadlock; Carol runs in parallel) and per-seat locks (Alice holds A1 and waits for A3 while Bob holds A3 and waits for A1: deadlock), with an option to lock in seat-ID order. Under the first two acts a timeline shows every step and wait.

Approach: Per-Show Locking

We have three locking granularity options:

ApproachLock ScopeProsCons
Global LockOne lock for entire BookingServiceSimplest, no deadlocksAll users wait, even for different shows
Per-Show LockOne lock per ShowUsers in different shows proceed in parallelSlightly more complex
Per-Seat LockOne lock per ShowSeatMaximum parallelismDeadlock risk when booking multiple seats, complex lock ordering

We choose Per-Show Locking because:

  1. Sufficient parallelism: Users booking different shows (which is the common case) never contend. Only users booking the same show are serialized — and there are typically only a few concurrent bookings per show.

  2. No deadlock risk: Each operation acquires exactly one lock (the show's lock). Deadlocks require holding lock A while waiting for lock B — impossible with single-lock operations.

  3. Simplicity: The lock lives on the Show object. Every method in BookingService acquires it at the start and releases at the end. No lock ordering, no tryLock, no timeout.

Why NOT per-seat locking:

When a user books multiple seats (e.g., A1, A3, B2), we'd need to acquire locks on all three ShowSeats. If Alice locks A1 then tries to lock A3, while Bob locks A3 then tries to lock A1 — deadlock. Solving this requires lock ordering (always lock in seat ID order), which is fragile and error-prone. Per-show locking avoids this entirely.

Implementation — Thread-Safe Show and BookingService

We add a lock to the Show class and modify BookingService to acquire it for all operations that touch a show's seats. The ShowSeat, Booking, and other classes remain unchanged — the lock at the Show level serializes all access.

The key pattern: acquire the show's lock before any check-then-act sequence on its ShowSeats.

import threading
from datetime import datetime, timedelta


class ThreadSafeShow:
    """Show with a per-show lock for concurrent booking safety."""

    def __init__(self, movie: Movie, screen: Screen,
                 start_time: datetime):
        self._show_id: str = str(uuid.uuid4())
        self._movie: Movie = movie
        self._screen: Screen = screen
        self._start_time: datetime = start_time
        self._show_seats: list[ShowSeat] = [
            ShowSeat(seat, self) for seat in screen.seats
        ]
        self._lock = threading.Lock()  # Per-show lock

    @property
    def lock(self) -> threading.Lock:
        return self._lock

    @property
    def show_id(self) -> str:
        return self._show_id

    @property
    def movie(self) -> Movie:
        return self._movie

    @property
    def screen(self) -> Screen:
        return self._screen

    @property
    def start_time(self) -> datetime:
        return self._start_time

    @property
    def show_seats(self) -> list[ShowSeat]:
        return list(self._show_seats)

    def get_available_seats(self) -> list[ShowSeat]:
        return [
            ss for ss in self._show_seats
            if ss.status == ShowSeatStatus.AVAILABLE
        ]

    def get_show_seat_by_seat_id(self, seat_id: str) -> ShowSeat | None:
        for ss in self._show_seats:
            if ss.seat.seat_id == seat_id:
                return ss
        return None


class ConcurrentBookingService:
    """Thread-safe BookingService using per-show locking."""

    def __init__(self, pricing_strategy: PricingStrategy,
                 notification_service: NotificationService):
        self._pricing_strategy = pricing_strategy
        self._notification_service = notification_service
        self._bookings: dict[str, Booking] = {}
        self._bookings_lock = threading.Lock()  # Protects the bookings dict

    def create_booking(self, user: User, show: ThreadSafeShow,
                       seat_ids: list[str]) -> Booking:
        """Thread-safe Phase 1: Hold seats and create PENDING booking.
        Acquires the show lock to make check-and-hold atomic.
        """
        with show.lock:  # <-- per-show lock
            show_seats: list[ShowSeat] = []
            for seat_id in seat_ids:
                show_seat = show.get_show_seat_by_seat_id(seat_id)
                if show_seat is None:
                    raise ValueError(f"Seat {seat_id} not found")
                if show_seat.status != ShowSeatStatus.AVAILABLE:
                    raise ValueError(
                        f"Seat {show_seat.seat.row}"
                        f"{show_seat.seat.number} is not available"
                    )
                show_seats.append(show_seat)

            booking = Booking(user, show, show_seats)

            # Hold all seats — safe because we hold the show lock
            for ss in show_seats:
                ss.hold(booking)

        # Outside the show lock — update bookings dict
        with self._bookings_lock:
            self._bookings[booking.booking_id] = booking

        print(f"Booking {booking.booking_id[:8]} created — "
              f"{len(show_seats)} seat(s) held for {user.name}")
        return booking

    def make_payment(self, booking_id: str,
                     method: PaymentMethod) -> Payment:
        """Thread-safe Phase 2: Confirm booking under show lock."""
        with self._bookings_lock:
            booking = self._bookings.get(booking_id)
        if booking is None:
            raise ValueError(f"Booking {booking_id} not found")

        show = booking.show
        with show.lock:  # <-- per-show lock
            if booking.status != BookingStatus.PENDING:
                raise ValueError(
                    f"Booking is {booking.status.value}, cannot pay"
                )
            if booking.is_hold_expired():
                self._expire_booking(booking)
                raise ValueError("Hold expired")

            amount = self._pricing_strategy.calculate_price(
                booking.show_seats, booking.show
            )
            payment = Payment(amount, method)
            payment.complete()

            for ss in booking.show_seats:
                ss.book()
            booking.confirm(payment)

        self._notification_service.notify_booking_confirmed(booking)
        return payment

    def cancel_booking(self, booking_id: str) -> None:
        """Thread-safe cancellation under show lock."""
        with self._bookings_lock:
            booking = self._bookings.get(booking_id)
        if booking is None:
            raise ValueError(f"Booking {booking_id} not found")

        show = booking.show
        with show.lock:
            if booking.status == BookingStatus.CONFIRMED:
                if datetime.now() >= show.start_time:
                    raise ValueError(
                        "Cannot cancel after show started"
                    )
                if booking.payment:
                    booking.payment.refund()
            if booking.status not in (
                BookingStatus.PENDING, BookingStatus.CONFIRMED
            ):
                raise ValueError(
                    f"Cannot cancel in {booking.status.value} state"
                )
            for ss in booking.show_seats:
                ss.release()
            booking.cancel()

        self._notification_service.notify_booking_cancelled(booking)

    def expire_holds(self) -> list[Booking]:
        """System timer: expire bookings with elapsed holds.
        Groups bookings by show to minimize lock acquisitions.
        """
        with self._bookings_lock:
            pending = [
                b for b in self._bookings.values()
                if b.status == BookingStatus.PENDING
            ]

        # Group by show to batch lock acquisitions
        by_show: dict[str, list[Booking]] = {}
        for b in pending:
            sid = b.show.show_id
            by_show.setdefault(sid, []).append(b)

        expired: list[Booking] = []
        for bookings in by_show.values():
            show = bookings[0].show
            with show.lock:
                for booking in bookings:
                    if booking.is_hold_expired():
                        self._expire_booking(booking)
                        expired.append(booking)
        return expired

    def _expire_booking(self, booking: Booking) -> None:
        """Must be called while holding the show lock."""
        for ss in booking.show_seats:
            ss.release()
        booking.expire()
        self._notification_service.notify_booking_expired(booking)
import java.util.concurrent.locks.ReentrantLock;

public class ThreadSafeShow {
    private final String showId;
    private final Movie movie;
    private final Screen screen;
    private final LocalDateTime startTime;
    private final List<ShowSeat> showSeats;
    private final ReentrantLock lock; // Per-show lock

    public ThreadSafeShow(Movie movie, Screen screen,
                          LocalDateTime startTime) {
        this.showId = UUID.randomUUID().toString();
        this.movie = movie;
        this.screen = screen;
        this.startTime = startTime;
        this.showSeats = new ArrayList<>();
        for (Seat seat : screen.getSeats()) {
            showSeats.add(new ShowSeat(seat, this));
        }
        this.lock = new ReentrantLock();
    }

    public ReentrantLock getLock() { return lock; }
    public String getShowId() { return showId; }
    public Movie getMovie() { return movie; }
    public Screen getScreen() { return screen; }
    public LocalDateTime getStartTime() { return startTime; }
    public List<ShowSeat> getShowSeats() {
        return Collections.unmodifiableList(showSeats);
    }

    public List<ShowSeat> getAvailableSeats() {
        return showSeats.stream()
                .filter(ss -> ss.getStatus() == ShowSeatStatus.AVAILABLE)
                .collect(Collectors.toList());
    }

    public ShowSeat getShowSeatBySeatId(String seatId) {
        return showSeats.stream()
                .filter(ss -> ss.getSeat().getSeatId().equals(seatId))
                .findFirst().orElse(null);
    }
}

public class ConcurrentBookingService {
    private final PricingStrategy pricingStrategy;
    private final NotificationService notificationService;
    private final Map<String, Booking> bookings;
    private final ReentrantLock bookingsLock;

    public ConcurrentBookingService(
            PricingStrategy pricingStrategy,
            NotificationService notificationService) {
        this.pricingStrategy = pricingStrategy;
        this.notificationService = notificationService;
        this.bookings = new HashMap<>();
        this.bookingsLock = new ReentrantLock();
    }

    /** Thread-safe Phase 1: Hold seats under show lock. */
    public Booking createBooking(User user, ThreadSafeShow show,
                                 List<String> seatIds) {
        ReentrantLock showLock = show.getLock();
        showLock.lock();
        Booking booking;
        try {
            List<ShowSeat> showSeats = new ArrayList<>();
            for (String seatId : seatIds) {
                ShowSeat ss = show.getShowSeatBySeatId(seatId);
                if (ss == null) {
                    throw new IllegalArgumentException(
                            "Seat " + seatId + " not found");
                }
                if (ss.getStatus() != ShowSeatStatus.AVAILABLE) {
                    throw new IllegalStateException(
                            "Seat " + ss.getSeat().getRow() +
                            ss.getSeat().getNumber() +
                            " is not available");
                }
                showSeats.add(ss);
            }

            booking = new Booking(user, show, showSeats);
            for (ShowSeat ss : showSeats) {
                ss.hold(booking);
            }
        } finally {
            showLock.unlock();
        }

        bookingsLock.lock();
        try {
            bookings.put(booking.getBookingId(), booking);
        } finally {
            bookingsLock.unlock();
        }

        System.out.println("Booking " +
                booking.getBookingId().substring(0, 8) +
                " created — " + booking.getShowSeats().size() +
                " seat(s) held for " + user.getName());
        return booking;
    }

    /** Thread-safe Phase 2: Confirm booking under show lock. */
    public Payment makePayment(String bookingId,
                               PaymentMethod method) {
        Booking booking;
        bookingsLock.lock();
        try {
            booking = bookings.get(bookingId);
        } finally {
            bookingsLock.unlock();
        }
        if (booking == null) {
            throw new IllegalArgumentException(
                    "Booking " + bookingId + " not found");
        }

        ThreadSafeShow show = (ThreadSafeShow) booking.getShow();
        show.getLock().lock();
        Payment payment;
        try {
            if (booking.getStatus() != BookingStatus.PENDING) {
                throw new IllegalStateException(
                        "Booking is " + booking.getStatus());
            }
            if (booking.isHoldExpired()) {
                expireBooking(booking);
                throw new IllegalStateException("Hold expired");
            }

            double amount = pricingStrategy.calculatePrice(
                    booking.getShowSeats(), booking.getShow());
            payment = new Payment(amount, method);
            payment.complete();

            for (ShowSeat ss : booking.getShowSeats()) {
                ss.book();
            }
            booking.confirm(payment);
        } finally {
            show.getLock().unlock();
        }

        notificationService.notifyBookingConfirmed(booking);
        return payment;
    }

    /** Thread-safe cancellation under show lock. */
    public void cancelBooking(String bookingId) {
        Booking booking;
        bookingsLock.lock();
        try {
            booking = bookings.get(bookingId);
        } finally {
            bookingsLock.unlock();
        }
        if (booking == null) {
            throw new IllegalArgumentException(
                    "Booking " + bookingId + " not found");
        }

        ThreadSafeShow show = (ThreadSafeShow) booking.getShow();
        show.getLock().lock();
        try {
            if (booking.getStatus() == BookingStatus.CONFIRMED) {
                if (LocalDateTime.now().isAfter(show.getStartTime())) {
                    throw new IllegalStateException(
                            "Cannot cancel after show started");
                }
                if (booking.getPayment() != null) {
                    booking.getPayment().refund();
                }
            }
            if (booking.getStatus() != BookingStatus.PENDING &&
                booking.getStatus() != BookingStatus.CONFIRMED) {
                throw new IllegalStateException(
                        "Cannot cancel in " + booking.getStatus());
            }
            for (ShowSeat ss : booking.getShowSeats()) {
                ss.release();
            }
            booking.cancel();
        } finally {
            show.getLock().unlock();
        }
        notificationService.notifyBookingCancelled(booking);
    }

    /** System timer: expire holds, grouped by show. */
    public List<Booking> expireHolds() {
        List<Booking> pending;
        bookingsLock.lock();
        try {
            pending = bookings.values().stream()
                    .filter(b -> b.getStatus() == BookingStatus.PENDING)
                    .collect(Collectors.toList());
        } finally {
            bookingsLock.unlock();
        }

        Map<String, List<Booking>> byShow = new HashMap<>();
        for (Booking b : pending) {
            byShow.computeIfAbsent(
                    ((ThreadSafeShow) b.getShow()).getShowId(),
                    k -> new ArrayList<>()
            ).add(b);
        }

        List<Booking> expired = new ArrayList<>();
        for (List<Booking> group : byShow.values()) {
            ThreadSafeShow show =
                    (ThreadSafeShow) group.get(0).getShow();
            show.getLock().lock();
            try {
                for (Booking b : group) {
                    if (b.isHoldExpired()) {
                        expireBooking(b);
                        expired.add(b);
                    }
                }
            } finally {
                show.getLock().unlock();
            }
        }
        return expired;
    }

    private void expireBooking(Booking booking) {
        for (ShowSeat ss : booking.getShowSeats()) {
            ss.release();
        }
        booking.expire();
        notificationService.notifyBookingExpired(booking);
    }
}

Concurrent Usage Example

Let's verify correctness by launching multiple threads that try to book the same seat simultaneously. Exactly one should succeed; all others should get an error.

import threading


def attempt_booking(
    service: ConcurrentBookingService,
    user: User,
    show: ThreadSafeShow,
    seat_ids: list[str],
    results: dict[str, str],
):
    """Try to book seats. Record success or failure."""
    try:
        booking = service.create_booking(user, show, seat_ids)
        results[user.name] = f"SUCCESS — booking {booking.booking_id[:8]}"
    except ValueError as e:
        results[user.name] = f"FAILED — {e}"


def main():
    # Setup
    seats = [
        Seat("A", 1, SeatType.STANDARD),
        Seat("A", 2, SeatType.STANDARD),
        Seat("A", 3, SeatType.PREMIUM),
    ]
    screen = Screen("Screen 1", seats)
    movie = Movie("Inception", Genre.SCI_FI, Language.ENGLISH, 148)
    show = ThreadSafeShow(movie, screen, datetime(2025, 3, 15, 19, 0))

    pricing = StandardPricing()
    notifications = ConsoleNotificationService()
    service = ConcurrentBookingService(pricing, notifications)

    # 5 users all try to book seat A1 at the same time
    target_seat = [seats[0].seat_id]
    users = [User(f"User_{i}", f"user{i}@test.com") for i in range(5)]
    results: dict[str, str] = {}

    threads = [
        threading.Thread(
            target=attempt_booking,
            args=(service, user, show, target_seat, results)
        )
        for user in users
    ]

    for t in threads:
        t.start()
    for t in threads:
        t.join()

    # Exactly 1 success, 4 failures
    print("\n=== Results ===")
    successes = 0
    for name, result in sorted(results.items()):
        print(f"  {name}: {result}")
        if "SUCCESS" in result:
            successes += 1

    print(f"\nSuccessful bookings: {successes}")
    print(f"Available seats: {len(show.get_available_seats())}")
    # Output: Exactly 1 successful booking, 2 available seats


if __name__ == "__main__":
    main()
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentBookingDemo {
    public static void main(String[] args) throws InterruptedException {
        List<Seat> seats = List.of(
                new Seat("A", 1, SeatType.STANDARD),
                new Seat("A", 2, SeatType.STANDARD),
                new Seat("A", 3, SeatType.PREMIUM));
        Screen screen = new Screen("Screen 1", seats);
        Movie movie = new Movie("Inception", Genre.SCI_FI,
                Language.ENGLISH, 148);
        ThreadSafeShow show = new ThreadSafeShow(movie, screen,
                LocalDateTime.of(2025, 3, 15, 19, 0));

        PricingStrategy pricing = new StandardPricing();
        NotificationService notifications =
                new ConsoleNotificationService();
        ConcurrentBookingService service =
                new ConcurrentBookingService(pricing, notifications);

        // 5 users all try to book seat A1
        String targetSeatId = seats.get(0).getSeatId();
        ConcurrentHashMap<String, String> results =
                new ConcurrentHashMap<>();

        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            User user = new User("User_" + i,
                    "user" + i + "@test.com");
            threads[i] = new Thread(() -> {
                try {
                    Booking b = service.createBooking(
                            user, show, List.of(targetSeatId));
                    results.put(user.getName(),
                            "SUCCESS — booking " +
                            b.getBookingId().substring(0, 8));
                } catch (Exception e) {
                    results.put(user.getName(),
                            "FAILED — " + e.getMessage());
                }
            });
        }

        for (Thread t : threads) t.start();
        for (Thread t : threads) t.join();

        System.out.println("\n=== Results ===");
        int successes = 0;
        for (var entry : results.entrySet()) {
            System.out.println("  " + entry.getKey() +
                    ": " + entry.getValue());
            if (entry.getValue().contains("SUCCESS")) successes++;
        }
        System.out.println("\nSuccessful bookings: " + successes);
        System.out.println("Available seats: " +
                show.getAvailableSeats().size());
        // Output: Exactly 1 successful booking, 2 available seats
    }
}

Expected output:

Booking xxxxxxxx created — 1 seat(s) held for User_2

=== Results ===
  User_0: FAILED — Seat A1 is not available
  User_1: FAILED — Seat A1 is not available
  User_2: SUCCESS — booking xxxxxxxx
  User_3: FAILED — Seat A1 is not available
  User_4: FAILED — Seat A1 is not available

Successful bookings: 1
Available seats: 2

The winning thread varies between runs (depends on OS scheduling), but the invariant always holds: exactly 1 success, exactly 1 seat held. No double bookings, no crashes, no corrupted state.

Performance Considerations

Lock contention: Under per-show locking, threads contend only when booking the same show. In a multiplex with 10 screens and 5 shows per screen, there are 50 independent locks. Even during peak hours, contention is low because the critical section (validating and holding seats) is fast — just a few status checks and assignments.

Hold timeout polling vs. scheduling: Our expire_holds() method scans all pending bookings. In production, you'd use a scheduled timer (Python threading.Timer, Java ScheduledExecutorService) to fire per-booking, avoiding the scan entirely.

Lock duration: The lock is held only during seat status mutations, not during I/O operations (payment gateway calls, notifications). We deliberately release the show lock before sending notifications — notifications might be slow (HTTP calls) and shouldn't block other bookings.

Optimistic locking alternative: In a database-backed system, you might use optimistic locking (version columns) instead of in-memory locks. The ShowSeat row would have a version column. The UPDATE statement includes WHERE version = expected_version. If another transaction already changed the row, the WHERE fails and you retry. This scales better across multiple application servers because the database becomes the synchronization point.