Skip to content

Optimistic vs. Pessimistic Locking

Optimistic and pessimistic locking are concurrency control techniques used in databases and distributed systems to manage access to shared resources and ensure data consistency.

Optimistic Locking

Optimistic locking assumes conflicts are rare and works under the expectation that most transactions can proceed without interference.

Key points

Algorithm

  1. Read the resource without acquiring a lock.
  2. When ready
    • Check if the resource has been modified by another transaction.
    • If not, commit the changes.
    • If modified, abort and retry.

When to use Optimistic Locking

Optimistic locking is well-suited for scenarios where conflicts are infrequent and the cost of acquiring and releasing locks is high.

It is commonly used in scenarios where the probability of conflicts is low, such as read-heavy workloads or scenarios where transactions are short-lived.

Real World Examples

Example of Optimistic Locking in SQL

-- Initial record
CREATE TABLE products (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    price DECIMAL(10,2),
    version INT
);

-- Reading the record
SELECT id, name, price, version 
FROM products 
WHERE id = 1;

-- Updating with version check
UPDATE products 
SET price = 29.99, version = version + 1 
WHERE id = 1 AND version = 5;

Pessimistic Locking

Pessimistic locking is a concurrency control technique that assumes conflicts between transactions are common. In pessimistic locking, a transaction acquires a lock on a resource before reading or modifying it. The lock prevents other transactions from accessing the resource until the lock is released. This ensures that only one transaction can access the resource at a time, reducing the likelihood of conflicts.

Use cases

Pessimistic locking is well-suited for scenarios where conflicts are common and the cost of acquiring and releasing locks is low.

It is commonly used in scenarios where the probability of conflicts is high, such as write-heavy workloads or scenarios where transactions are long-lived.

Real World Example

Example of Pessimistic Locking in SQL

-- Using SELECT FOR UPDATE in a transaction
BEGIN TRANSACTION;

SELECT * FROM products 
WHERE id = 1 
FOR UPDATE;  -- This locks the row

-- Make modifications
UPDATE products 
SET price = 29.99 
WHERE id = 1;

COMMIT;  -- Releases the lock

Summary