MYSQL

Optimistic vs Pessimistic Locking in MySQL

Optimistic vs Pessimistic Locking

๐Ÿ“Œ 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

  1. Read data with a version/timestamp
  2. Update data with a condition
  3. If version matches โ†’ update success
  4. 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)

FeatureOptimistic LockingPessimistic Locking
ApproachNo lockLock before update
PerformanceFastSlower
Conflict HandlingDetect & retryPrevent
Use CaseLow conflictHigh conflict
ScalabilityHighLow

๐Ÿง  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 UPDATE is 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.

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *