Everything I know about distributed locks

Davide Cerbo
4 min readOct 15, 2019

Locking, often, isn’t a good idea, and trying to lock something in a distributed environment may be more dangerous. But sometimes, we need to keep this risk and try to use a distributed lock for two main reasons:

  • Efficiency: a lock can save our software from performing unuseful work more times than it is really needed, like triggering a timer twice.
  • Correctness: a lock can prevent the concurrent processes of the same data, avoiding data corruption, data loss, inconsistency and so on.

We have two kinds of locks:

  • Optimistic: instead of blocking something potentially dangerous happens, we continue anyway, in the hope that everything will be ok.
  • Pessimistic: block access to the resource before operating on it, and we release the lock at the end.

To use optimistic lock we usually use a version field on the database record we have to handle, and when we update it we check if the data we read has the same version of the data we are writing.

Optimistic lock sequence diagram

Database access libraries, like Hibernate, usually provide facilities to use an optimistic lock.

--

--