NOTE

1.2 How to Implement Distributed Locks

1. What Is a Distributed Lock - A lock in a distributed environment (across processes or machines). It satisfies the following conditions: atomicity, mutual exclusion, no deadlock, and locking and unlocking must be performed by the same client. 2. Why Distributed Locks Are Needed - Built-in locks in various languages, such as Java synchronized and Go mutex, can only guarantee lock properties within a single process and cannot span processes or machines.

Distributed SystemsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is a Distributed Lock?

A lock in a distributed environment (across processes or machines).

It satisfies the following conditions:

  • Atomicity

Locking and unlocking operations must be atomic.

  • Mutual exclusion

At any moment, only one client can hold the lock.

  • No deadlock

Even if a client crashes while holding the lock without actively unlocking it, other clients must still be able to acquire the lock afterward.

  • Locking and unlocking must be performed by the same client.

Locking and unlocking must be performed by the same client. A client cannot release a lock acquired by someone else.

For example, in this scenario, A acquires the lock with a lock-holding duration of 10s, but A actually runs for 15s, so the lock is automatically released. Then B successfully acquires the lock. At the 15th second, A finishes execution and releases the lock. Here, A has released the lock acquired by B.

2. Why Are Distributed Locks Needed?

Built-in locks in various languages, such as Java’s synchronized and Go’s mutex, can only guarantee lock properties within a single process and cannot span processes or machines.

3. How to Implement Distributed Locks

3.1. ZooKeeper

ZooKeeper Distributed Lock

3.2. Redis

Redis Distributed Lock

3.3. ZooKeeper vs Redis

Redis ZooKeeper
Lock acquisition fails Needs continuous active polling Register a listener and wait for a callback
Client holding the lock crashes Must wait until the timeout expires before acquiring the lock again The ephemeral node automatically releases the lock
Performance High Low

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub