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

serpapi logo
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi

The latest

View all →
JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43 image

JSON Schema Validation Rules and a RetryFor Attribute in Laravel 13.43

Read article
Durable Workflow: Long-Running Workflows for Laravel image

Durable Workflow: Long-Running Workflows for Laravel

Read article
Session Replay for Laravel: Self-Hosted Browser Recordings image

Session Replay for Laravel: Self-Hosted Browser Recordings

Read article
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article