Optimistic vs pessimistic locking

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2022-12-01

The purpose of either of these is to prevent multiple updates to one item.

Optimistic Locking

When you want to update an item, you must specify which version you want to update. Could be via a version number, date, checksum/hash.

When you write that record back to the DB, if the version you provide doesn’t match the current version of the item in the database (i.e. the record is dirty - different to yours), your update will be rejected.

Example with DyanamoDB

An item is created in version 0. Process A looks up that item (version 0). Process B also looks up that item (version 0). Now process A wants to make a change by invoking the updateItem operation on DynamoDB. Therefore process A specifies that the expected version is 0. DynamoDB will allow that modification, because the version matches; but DynamoDB will also change the item’s version to 1 because an update was performed.

Now process B (which, as I stated above, already grabbed the item earlier) wants to make a modification and sends a request to DynamoDB with the expected item version 0. DynamoDB will reject this modification because the expected version doesn’t match the version DynamoDB knows of, which is 1.

Why called "optimistic"?

Assumes nothing's going to change while you're reading it.

Pessimistic locking

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid deadlocks.

A pessimistic lock strategy can be implemented by using a semaphore. Before you change data, you need to lock the semaphore. If the semaphore is already locked, you wait until the semaphore becomes free again before allowing a write.

Why called "pessimistic"?

Assumes something is going to change while you're reading it