Optimistic v/s Pessimistic Locks

Photo by Jude Al-Safadi on Unsplash

Why do we need locks ?

To put this in the most simplistic terms — Locks are mechanism used to ensure data integrity.

A database lock is used to “lock” some record in a database so that only one database user or session can update that particular data. So, database locks exist to prevent two or more database users from updating the same exact piece of data at the same exact time.

There are different levels of locks that can be acquired:-

  1. A single row
  2. A single page
  3. A table as a whole
  4. An entire database

Pessimistic Lock

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

The disadvantage is that resource is locked from when you start the transaction until you finished the transaction. During that time the record is not available to other transactions.

Optimistic Lock

Optimistic Locking is a when you read a record, take note of a version number and check that the version hasn’t changed before you write the record back. When you write the record back you filter the update on the version to make sure it’s atomic.

Other transactions are able to concurrently access to the resource and the possibility of conflicting changes is possible. At commit time, when the resource is about to be updated in persistent storage, the state of the resource is read from storage again and compared to the state that was saved when the resource was first accessed in the transaction. If the two states differ, a conflicting update was made, and the transaction will be rolled back.

Thanks for reading

Happy Coding!!




Software Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

FIVE: a dictionary for the Browser tab

Balpy is about to be improved with this new grant!

Connect Apache Spark to your HBase database (Spark-HBase Connector)

Python async/await From the Ground Up

Webflow Getting Started, Part 1 — The Cockpit Layout

Webflow navigator panel

The last day of the last sprint

100% Unit Test Coverage — Is that a Myth?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Software Developer

More from Medium

Intro to Event-Driven Architecture

Microservices did you know this ?

PostgreSQL and typeorm — Storing single table data

MongoDB: Avoid using unbounded arrays in documents