Two people click 'Book' on the last seat at the exact same moment. Both requests hit your server simultaneously. Without the right code, both go through. Your database shows -1 available seats and two unhappy customers with the same booking.
This is a concurrency problem, and it happens more than you think in ticket booking, flash sales, and inventory systems.
The naive approach fails
// WRONG - race condition possible
$seat = Seat::find($id);
if ($seat->available) {
$seat->update(['available' => false, 'user_id' => $userId]);
}
Between the check and the update, another request could read the same row. Both see available = true and both book it.
Pessimistic locking
Lock the row when you read it, preventing others from reading it until you are done:
DB::transaction(function () use ($seatId, $userId) {
$seat = Seat::where('id', $seatId)
->lockForUpdate()
->first();
if (!$seat || !$seat->available) {
throw new Exception('Seat is no longer available');
}
$seat->update(['available' => false, 'user_id' => $userId]);
Booking::create(['seat_id' => $seatId, 'user_id' => $userId]);
});
lockForUpdate() uses a SELECT ... FOR UPDATE query. The second request waits until the first finishes. If the seat is taken, it sees available = false and throws an exception.
Optimistic locking
Instead of locking rows, use a version number. If someone else changed the row before you saved, your update fails:
$seat = Seat::find($seatId);
$updated = Seat::where('id', $seatId)
->where('version', $seat->version)
->where('available', true)
->update([
'available' => false,
'user_id' => $userId,
'version' => $seat->version + 1,
]);
if (!$updated) {
throw new Exception('Seat was taken by someone else');
}
Redis locks
For operations that span multiple services or require a distributed lock:
$lock = Cache::lock('seat:' . $seatId, 10);
if ($lock->get()) {
try {
// book the seat
} finally {
$lock->release();
}
} else {
throw new Exception('Could not acquire lock');
}
Use pessimistic locking for most cases. It is simple, reliable, and MySQL handles it well. Redis locks are for cases where you need to coordinate across multiple services.



