This is the 13th day of my participation in the August More Text Challenge.More challenges in August

A distributed lock

In distributed environment, to ensure data consistency, distributed lock technology is used to ensure that only a fixed number of processes modify data at the same time: only the client that obtains the lock can modify data, and other clients can only wait temporarily.

Implementation method:

  1. The unique index of the database
  2. Redis SETNX instruction
  3. RedLock algorithm of Redis
  4. Temporary sequence node of ZooKeeper

Blocking locks

Blocking locks are usually implemented using mutex:

A mutex value of 0 indicates that another process is using the lock and is in the locked state. A mutex value of 1 indicates that the process is not locked. 1 and 0 can be represented by an integer value, or by the presence or absence of some data.

The unique index of the database

A record is inserted into the table when the lock is acquired and deleted when the lock is released. A unique index guarantees that the record is inserted only once, so the existence of the record can be used to determine whether the record is locked.

There are several problems

  1. The lock has no expiration time. If the unlock fails, other processes cannot obtain the lock.
  2. This lock can only be a non-blocking lock. If the lock fails to be inserted, an error will be reported and the lock cannot be retried.
  3. There is no reentrant, and processes that have acquired locks must also acquire them again.

Redis SETNX instruction

  1. Insert a key-value pair using the SETNX(Set if not exist) directive, returning False if the Key already exists, and True otherwise.
  2. The SETNX instruction is similar to the unique index of the database, which guarantees the existence of only one Key value pair. Therefore, the existence of a Key value pair can be used to determine whether it is stored in the locked state.
  3. The EXPIRE directive sets an expiration time for a key-value pair, avoiding lock release failures in the database unique index implementation.

RedLock algorithm of Redis

  1. Multiple Redis instances are used to achieve distributed locking, which is to ensure that in case of a single point of failure, you can still try to obtain locks from N independent Redis instances.
  2. The lock acquisition is considered successful only if the time is less than the lock expiration time and the lock is obtained from most (N/2+1) instances
  3. If the lock fails to be acquired, the lock is released on each instance.

Temporary sequence node of ZooKeeper

See this blog post for more details – How to Implement distributed locks using ZooKeeper.