SteelReed

Search

Search posts, questions…

4. Database & SQL

Airline booking: holding seats correctly when many people book at once

Airline case study, part 2: why check-then-act oversells, conditional updates for a counter and the throughput ceiling of a hot row, SKIP LOCKED for auto-assignment and its false sold-out trap, deadlocks when customers pick seats and how to lock in a fixed order, hold expiry, Spring Boot 3 code and MySQL 8 differences.

18 Nov 20268 min readSenior

–

1. The problem

One economy seat is left. The code reads booked = 175, checks 175 + 1 <= 176, then writes 176. Two requests at once: both pass the if, both write 176, 177 tickets are sold while the data says 176. The same week, two customers pick seats 10A and 10B in opposite order, and one gets a 500 deadlock detected.

2. Key idea

@Transactional doesn't help because a plain SELECT takes no lock. Fold the check into the write: one conditional UPDATE, 0 rows means sold out, 1 row means held. PostgreSQL at READ COMMITTED waits for the earlier writer and re-evaluates the WHERE on the new version; InnoDB always reads the latest version on UPDATE.

Every booking for the same flight and class queues on one row lock until commit, so throughput ≈ 1 / lock hold time. Call other services, compute prices and send email before the transaction.

Technique Use when Don't use when
Conditional UPDATE the default for counters and chosen seats logic too complex for a WHERE
FOR UPDATE SKIP LOCKED auto-assigned seats, job queues the customer needs "this exact seat"
Lock in one ORDER BY statement customers picking several seats a single row
Optimistic version low contention hot counters: retry storms
Redis in front, DB behind flash sales at tens of thousands per second Redis as the source of truth

3. In SQL

SQL
-- Counter: check and write in one statement
UPDATE flight_inventory SET booked = booked + :q
WHERE  flight_id = :flightId AND fare_class = :fareClass AND booked + :q <= sell_limit
RETURNING booked;                               -- 0 rows: sold out
 
-- Customer-picked seats: lock them all in the same order, then a conditional UPDATE
SELECT seat_code FROM seat_availability
WHERE  flight_id = :flightId AND seat_code = ANY(:seats)
ORDER  BY seat_code FOR UPDATE;
UPDATE seat_availability
SET    status = 'HELD', booking_id = :bookingId, held_until = now() + interval '15 minutes'
WHERE  flight_id = :flightId AND seat_code = ANY(:seats) AND status = 'AVAILABLE';
-- row count differs from seats requested: ROLLBACK, return 409 "seat just taken"

Schema layer: primary key (flight_id, seat_code), CHECK (booked <= sell_limit). Operations layer: periodic reconciliation queries. MySQL 8.4 has SKIP LOCKED but no partial indexes, and "select then UPDATE the same table" must be split into two statements.

SKIP LOCKED, hold expiry and deadlock retries
  • Auto-assigned seats: a CTE SELECT ... WHERE status = 'AVAILABLE' ORDER BY seat_code LIMIT :n FOR UPDATE SKIP LOCKED, then UPDATE the picked seats. Fewer than n rows means roll back the whole transaction: a party of 2 doesn't want one seat.
  • The trap: SKIP LOCKED also skips seats locked by transactions that may yet roll back. If you got too few, run a lock-free count (AVAILABLE plus unexpired HELD) before saying sold out.
  • Hold expiry: a per-minute job releases HELD seats with held_until < now(), in batches of 1,000 with SKIP LOCKED so pods share the work; the hold query treats expired holds as free. Never release seats while a payment is in flight.
  • Deadlock retries: keep one retry for SQLSTATE 40P01 (MySQL error 1213), and set lock_timeout to a few seconds.

4. Working with AI

Hand to AI: a 32-client concurrency test on Testcontainers, reconciliation queries, a count that distinguishes sold out from temporarily held.

Check yourself in AI-written code:

  • No read-then-if-then-write on counters; the check is in the WHERE and the row count is compared.
  • The lock-holding transaction makes no HTTP calls, price computations or emails.
  • The seat list is sorted and deduplicated before locking.
  • A short SKIP LOCKED result triggers a recount before reporting sold out.
  • Schema constraints act as the last line of defense.

5. Exercises

Exercise 1: Review a seat-holding service

The AI wrote the code below and says "it's inside @Transactional, so it's safe". Find what breaks when 200 people book at once, and fix it.

JAVA
@Transactional
public void hold(long flightId, List<String> seats, long bookingId) {
    for (String s : seats) {                                  // in the order the customer clicked
        SeatAvailability seat = repo.find(flightId, s);
        if (!seat.isAvailable()) throw new SeatTakenException(s);
        pricing.quote(flightId, s);                           // HTTP call ~150 ms
        repo.markHeld(flightId, s, bookingId);
    }
}
Solution 1
  • Check-then-act: find takes no lock; two customers both see the seat free and both markHeld. Use a conditional UPDATE with status = 'AVAILABLE' and compare the row count.
  • Deadlock: seats are locked in click order; two customers choosing 10A/10B in opposite order deadlock. Sort the list and lock in one ORDER BY seat_code statement.
  • Lock held during HTTP: 150 ms per seat inside the transaction; call pricing before opening it.
  • Half holds: if the second seat is taken, the exception does roll back, but only after waiting on the first seat's lock. The section 3 version checks the whole set in two statements.

Exercise 2: "Sold out" or "try again"

Auto-assignment with SKIP LOCKED returns 1 seat for a party of 2. The AI suggests immediately returning "This flight is sold out". How do you fix it?

Solution 2

Roll back, then count without locks:

SQL
SELECT count(*) FILTER (WHERE status = 'AVAILABLE')                 AS free_now,
       count(*) FILTER (WHERE status = 'HELD' AND held_until > now()) AS held_temporarily
FROM   seat_availability WHERE flight_id = :flightId AND fare_class = :fareClass;
  • free_now >= 2: seats are locked by unfinished transactions; retry after a few hundred ms with jitter.
  • free_now < 2 but large held_temporarily: say "seats are being held, try again in a few minutes".
  • Both small: really sold out.

Summary

  • Check-then-act oversells even inside @Transactional; fold the check into the write.
  • Hot row: throughput ≈ 1 / lock hold time; make external calls before the transaction.
  • SKIP LOCKED for "any seat"; a short result means recount without locks.
  • Customer-picked seats: lock in one ORDER BY seat_code statement and keep a deadlock retry.
  • Three layers: application, schema, reconciliation; Redis only absorbs load.

Further reading: Transactions, isolation levels and locking.

Practice interview questions on this topic

All Transactions & Locking questions →

Loading comments…