We use cookies to enhance your experience. By continuing to visit this site you agree to our use of cookies. Learn More
contact@techquestworld.com
+919547614783
Premium Article
Published 3 months ago

Pessimistic vs Optimistic Locking in Laravel: A Developers Deep‑Dive

5 min read
512 views
Pessimistic vs Optimistic Locking in Laravel: A Developers Deep‑Dive
Photo by Techquestworld

Learn how to safeguard your Laravel applications from race conditions by applying the right concurrency strategy—pessimistic or optimistic locking, complete with real‑world code examples.

1. Why Concurrency Control Matters

Two people try to grab the last ticket for an event at the same moment. If the system doesn't handle this carefully, it might accidentally sell that one ticket to both users, causing confusion and overselling. That's where concurrency control steps in. By using techniques like pessimistic or optimistic locking, systems can manage simultaneous access and make sure only one of those transactions goes through, keeping the inventory accurate and the users happy.

2. What Is Pessimistic Locking?

Definition: Lock the record(s) early so other transactions must wait.

• Pros: Guarantees no conflict.

• Cons: Can slow down throughput and cause deadlocks under high load.

3. What Is Optimistic Locking?

Definition: Allow concurrent reads on update, verify the record hasn't changed with a version/timestamp.


• Pros: High throughput, less locking.

• Cons: May require retry logic if conflicts are detected.

4. Performance & Scalability Comparison

Factor Pessimistic Optimistic
Write Contention Handles safely but slower Retries needed
Read Scalability Readers may block Near‑linear scaling
Deadlock Risk Higher None
Implementation Effort Simple (built‑in SQL) Needs version column

5. Implementing Pessimistic Locking in Laravel

Laravel exposes MySQL/Postgres SELECT … FOR UPDATE via Eloquent:

DB::transaction(function () {
$ticket = Ticket::where('status', 'available')
->lockForUpdate() // 🔒 Pessimistic lock
->firstOrFail();

$ticket->update(['status' => 'sold']);
});

Handling Deadlocks Gracefully

try {
DB::transaction(function () { /* … */ }, attempts: 5);
} catch (Throwable $e) {
// log and show friendly error
}

6. Implementing Optimistic Locking in Laravel

Laravel doesn't come with built-in optimistic locking, but implementing it yourself is pretty straightforward. You can simply use a version field or rely on the updated_at timestamp to detect conflicting updates before saving.

Migration

Schema::table('tickets', function (Blueprint $table) {
$table->unsignedInteger('version')->default(0);
});

Model Trait

trait OptimisticLocking
{
public static function bootOptimisticLocking()
{
static::updating(function ($model) {
$originalVersion = $model->getOriginal('version');
$model->version++;

$affected = $model->newModelQuery()
->whereKey($model->getKey())
->where('version', $originalVersion)
->update($model->getDirty());

if ($affected === 0) {
throw new \RuntimeException('Optimistic lock conflict. Please retry.');
}

return false; // stop default save
});
}
}

Usage

class Ticket extends Model
{
use OptimisticLocking;
}

try {
$ticket->status = 'sold';
$ticket->save();
} catch (RuntimeException $e) {
// Retry or inform the user
}

7. Testing Race Conditions

Use Laravel's parallel testing or php artisan tinker in two shells to simulate concurrent updates.

// Session 1
DB::beginTransaction();
Ticket::find(1)->lockForUpdate();

// Session 2 (will wait or fail depending on DB)
Ticket::find(1);

8. Best‑Practice Checklist

🔐 Use pessimistic locking for critical financial rows.

🚀 Prefer optimistic locking on high‑read tables.

🕒 Always set reasonable query timeouts.

🧪 Add integration tests for concurrency.

Picking the right locking strategy is context‑dependent. Pessimistic locking is bulletproof but can reduce throughput. Optimistic locking scales well but needs conflict‑handling code.

Author
TAPAS SAHOO

Developer by Profession, Techie by Heart

A curious mind with a love for writing and technology, dedicated to simplifying web development and programming topics while keeping up with the ever-changing tech landscape.

Discussion (0)

Replying to
Previous Article
10 Essential Array Methods Every Node.js Deve...

Learn the 10 most important array methods in Node.js with clear explanations, code samples and best‑...

Next Article
Top 10 Laravel Tricks Every Developer Regrets...

Boost your Laravel development speed and efficiency with these 10 must know hacks. Perfect for Larav...

Related Articles

Simple Contact Form in PHP with Email Functionality – Step-by-Step Guide
PHP
Simple Contact Form in PHP with Email Functionalit...

Build a working contact form using PHP that sends form data via email. A great beginner PHP project...

Modern PHP Newsletter Subscription Form with Stylish Design
PHP
Modern PHP Newsletter Subscription Form with Styli...

A minimal PHP-powered newsletter form to collect email addresses, designed with a clean, modern look...

Simple Feedback Form with PHP Email Support
PHP
Simple Feedback Form with PHP Email Support

Send feedback directly to your inbox using this beautifully designed PHP form.

Build a Complete PHP CRUD App with Bootstrap – No Framework
PHP
Build a Complete PHP CRUD App with Bootstrap – No...

Looking to build a full web app in PHP without relying on Laravel or CodeIgniter? This step-by-step...

Table of Contents