Optimistic vs Pessimistic Locking in MySQL
๐ Introduction
When multiple users try to update the same data in a database, it can lead to data inconsistency and conflicts. This is where locking mechanisms in MySQL come into play.
Two of the most important techniques are:
- Optimistic Locking
- Pessimistic Locking
In this guide, youโll learn how they work, when to use them, and real-world examples using MySQL + PHP.
๐ What is Locking in MySQL?
Locking is a mechanism used to control concurrent access to data.
๐ Goal:
- Prevent data conflicts
- Maintain consistency
- Handle multiple users safely
๐ 1. Optimistic Locking in MySQL
๐ Definition
Optimistic locking assumes:
๐ Conflicts are rare
Instead of locking the row, it checks before updating whether the data has changed.
โ๏ธ How It Works
- Read data with a version/timestamp
- Update data with a condition
- If version matches โ update success
- If not โ conflict detected
๐งพ Example Table
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2),
version INT
);๐ป MySQL Query Example
UPDATE products
SET price = 200, version = version + 1
WHERE id = 1 AND version = 2;๐ If version changed โ update fails
๐งโ๐ป PHP Example
$id = 1;
$newPrice = 200;
$version = 2;$sql = "UPDATE products
SET price = ?, version = version + 1
WHERE id = ? AND version = ?";$stmt = $conn->prepare($sql);
$stmt->bind_param("dii", $newPrice, $id, $version);
$stmt->execute();if ($stmt->affected_rows > 0) {
echo "Update successful";
} else {
echo "Conflict detected! Data was modified by another user.";
}โ Advantages
- No locks โ better performance
- High scalability
- Ideal for read-heavy systems
โ Disadvantages
- Conflict handling required
- Retry logic needed
๐ Real-World Use Case
- E-commerce product updates
- Profile editing systems
- Booking systems (low conflict)
๐ 2. Pessimistic Locking in MySQL
๐ Definition
Pessimistic locking assumes:
๐ Conflicts are likely
So it locks the data before updating.
โ๏ธ How It Works
- Lock row using
SELECT ... FOR UPDATE - Other transactions must wait
๐ป MySQL Example
START TRANSACTION;SELECT * FROM products WHERE id = 1 FOR UPDATE;UPDATE products SET price = 200 WHERE id = 1;COMMIT;
๐งโ๐ป PHP Example
$conn->begin_transaction();
$result = $conn->query("SELECT * FROM products WHERE id = 1 FOR UPDATE");
$conn->query("UPDATE products SET price = 200 WHERE id = 1");
$conn->commit();โ Advantages
- Strong data consistency
- No conflicts
- Safe for critical operations
โ Disadvantages
- Slower performance
- Can cause deadlocks
- Reduces concurrency
๐ Real-World Use Case
- Banking systems ๐ฐ
- Inventory deduction
- Ticket booking (high traffic)
โ๏ธ Optimistic vs Pessimistic Locking (Comparison Table)
| Feature | Optimistic Locking | Pessimistic Locking |
|---|---|---|
| Approach | No lock | Lock before update |
| Performance | Fast | Slower |
| Conflict Handling | Detect & retry | Prevent |
| Use Case | Low conflict | High conflict |
| Scalability | High | Low |
๐ง When to Use What?
๐ Use Optimistic Locking When:
- Read-heavy applications
- Low chances of conflict
- High scalability needed
๐ Use Pessimistic Locking When:
- High contention systems
- Critical transactions
- Financial or inventory systems
โ ๏ธ Common Mistakes
โ Not handling retries in optimistic locking
โ Forgetting transactions in pessimistic locking
โ Ignoring deadlocks
๐ฏ Pro Tips (Important for Interviews)
- Optimistic locking = version-based control
- Pessimistic locking = row-level locking
SELECT FOR UPDATEis key in pessimistic locking- Always use transactions
๐ Conclusion
Both locking strategies are important in MySQL.
๐ Use Optimistic Locking for performance
๐ Use Pessimistic Locking for safety
Choosing the right one depends on your application needs and traffic patterns.
