[TIL-1] Optimistic locking vs Pessimistic locking

Why Lock?

User Foo -> read soap’s stock = 15 -> buy 10 soaps -> update the soap’s stock to 5

User Bar -> read soap’s stock = 15 -> buy 8 soapss -> update the soap’s stock to 7

And finally the soap’s stock is updated to 7. This is one of the currency problems called Lost Update Problem.

Optimistic Lock

User Foo -> read the soap’s stock = 15 with version 1 -> buy 10 soap -> update the soap’s stock to 5 and version to version 2 where the version is 1

User Bar -> read the soap’s stock = 15 with version 1-> buy 8 soaps -> update the soap’s stock to 7 and version to version 2 where the version is 1 because the version already updated to version 2 the record will be failed to be updated, therefore we can try to retry the operation

User Bar -> read the soap’s stock = 5 with version 2 -> buy 8 soaps -> give the information to user that the soap’s stock is insufficient

Pessimistic Locking

User Foo -> read the soap’s stock = 15 -> buy 10 soaps -> acquire the lock -> read the soap’s stock = 15 to update -> update the soap’s stock to 5 -> release the lock

User Bar -> read the soap’s stock = 15 -> buy 8 soaps -> acquire the lock -> acquire the lock failed due to acquired by other User -> waiting until the lock is released -> acquire the lock -> read the soap’s stock = 5 to update -> update failed due to insufficient stock -> release the lock

Conclusion

--

--

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