TIL-9: Optimistic vs. Pessimistic Locking
“Today I learned the two types of locking, Optimistic and Pessimistic and the differences between them.”
TL;DR
- Optimistic Locking is when you check if the record was updated by someone else before you commit the transaction.
- Pessimistic locking is when you take an exclusive lock so that no one else can start modifying the record.
Why Lock?
We use locks to protect data integrity and atomicity in concurrent applications where a record could get read/write requests.
Imagine a case where multiple users want to purchase an item where there’s only 1 left in the stock. The company advertised that item on facebook/twitter/TV/etc. and instantly 2000 users want to purchase that item. Of course, you have to sell this item to only one user since only there’s 1 left in the stock. To manage situations like this we employ locks. If we don’t manage these situations this may cause that single item to be sold to all of those 2000 users causing you to lose 1999 x ItemPrice, so you better use locks for that.
When it comes to locking there are two options: Pessimistic and Optimistic, let’s explore them more in detail.