Intermediate LevelLaravel
How do pessimistic (lockForUpdate) and optimistic locking prevent data race conditions?
❓ Interview Prompt: Explain Pessimistic Locking (lockForUpdate(), sharedLock()), Optimistic Locking (version columns), and preventing concurrent updates.
When multiple concurrent HTTP requests update the same database record simultaneously, data corruption can occur:
1. Pessimistic Locking ('lockForUpdate()'):
Issues 'SELECT ... FOR UPDATE' inside a transaction. Locks database rows so competing transactions must wait until the lock releases.
2. Optimistic Locking:
Uses an integer 'version' column. Updates check 'WHERE id = :id AND version = :version'. If rows returned equals 0, a concurrent update occurred!
Code Implementation Example
php
<?php
use IlluminateSupportFacadesDB;
use AppModelsAccount;
DB::transaction(function () use ($accountId, $amount) {
// Pessimistic row lock during balance deduction
$account = Account::where('id', $accountId)->lockForUpdate()->first();
$account->balance -= $amount;
$account->save();
});💡Pessimistic row locking using lockForUpdate() inside transaction.
🎯 Interview Key Takeaway
Use lockForUpdate() inside transactions to lock database rows and defend against concurrent update race conditions.
#Locking#Pessimistic Lock#Concurrency#Intermediate
Back to all Laravel Questions→