Laravel Tutorials

Managing Data Races with Pessimistic Locking in Laravel

Published
Managing Data Races with Pessimistic Locking in Laravel image

Laravel provides robust pessimistic locking capabilities to prevent data races in concurrent database operations. Through sharedLock() and lockForUpdate() methods, you can maintain data consistency in high-concurrency scenarios.

The sharedLock() method prevents modifications while allowing reads:

DB::table('users')
->where('votes', '>', 100)
->sharedLock()
->get();

For more stringent control, lockForUpdate() blocks both modifications and shared locks:

DB::table('orders')
->where('status', 'pending')
->lockForUpdate()
->get();

This approach is particularly valuable in financial transactions or inventory management systems:

class PaymentController extends Controller
{
public function processPayment($orderId, $amount)
{
return DB::transaction(function () use ($orderId, $amount) {
$account = DB::table('accounts')
->where('order_id', $orderId)
->lockForUpdate()
->first();
if ($account->balance >= $amount) {
DB::table('accounts')
->where('order_id', $orderId)
->update(['balance' => $account->balance - $amount]);
return ['success' => true, 'message' => 'Payment processed'];
}
return ['success' => false, 'message' => 'Insufficient funds'];
});
}
}

These locking mechanisms are essential in applications where data accuracy is crucial and multiple processes might attempt to modify the same data simultaneously.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article