Two applicants, one seat: fixing an overbooking race with a row lock
From Online Admission System (OMAS)
- PHP
- MySQL
- concurrency
Symptom
An exam center with a capacity of 40 had 41 applicants assigned. Staff found it while printing seat lists, well after both applicants had received confirmation emails.
Why the UI couldn't show it
Both applicants saw a center with one seat left, both submitted, both got a success page. Each request, taken alone, did the right thing. The defect only exists between two requests, and neither request can see the other.
Diagnosis
The legacy code was the textbook check-then-act: SELECT COUNT(*) for the center, compare with capacity in PHP, INSERT if there is room. Two requests that interleave between the SELECT and the INSERT both read 39, both pass, both insert.
It had never shown up in testing because every test ran one request at a time, and it had never shown up in years of production because registration was spread across weeks. A deadline day with a batch of applicants hitting the last seats of a popular center was the first time two requests were close enough together.
Fix
Make the check and the insert one atomic step from the database's point of view. Inside a transaction, lock the center's row with SELECT … FOR UPDATE. The second transaction blocks on that lock until the first commits, then re-reads a count that now includes the first insert, and fails the check.
$db->transaction(function (Connection $db) use ($centerId, $applicantId): void {
$center = $db->selectOne(
'SELECT capacity FROM exam_centers WHERE id = :id FOR UPDATE',
['id' => $centerId],
) ?? throw HttpException::notFound('Exam center');
$taken = $db->selectOne(
'SELECT COUNT(*) AS n FROM exam_slots WHERE center_id = :id',
['id' => $centerId],
)['n'];
if ($taken >= $center['capacity']) {
throw new HttpException(409, 'This exam center is full');
}
$db->execute(
'INSERT INTO exam_slots (center_id, applicant_id) VALUES (:c, :a)',
['c' => $centerId, 'a' => $applicantId],
);
});The lock is on the parent row, not the count. Locking the rows you are counting does not stop a new row from being inserted; locking the center serialises every writer for that center, which is exactly the granularity wanted — two applicants at different centers never wait on each other.
Test
A PHPUnit test seeds a center with capacity 1, opens two database connections, starts a transaction on each, and drives them through the allocation in the interleaving that used to fail: both read, then both try to write. It asserts that exactly one INSERT succeeds and the other request gets a 409. The test is uglier than the fix, and it is the only thing that proves the fix does what the commit message says.