NOTE

1.2 How to Implement Distributed Locks

Requirements and failure cases for locks across processes or machines, with Redis- and ZooKeeper-style approaches and the importance of ownership and fencing.

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 distributed lock coordinates mutually exclusive work across processes or machines.

Useful properties include:

  • mutual exclusion: conflicting holders should not simultaneously act as the lock owner;
  • atomic acquisition/release semantics;
  • ownership: a client must not release another client’s lock;
  • bounded recovery: a crashed holder must not block progress forever.

A lease alone is not always enough. If client A pauses longer than its lease, client B may acquire a new lease while A later resumes and continues writing. For resources that support it, a monotonically increasing fencing token lets the resource reject stale owners.

2. Why Process Locks Are Insufficient

Java synchronized, Go sync.Mutex, and similar primitives coordinate threads inside one process. They cannot coordinate independent processes on different machines.

3. Common Implementations

3.1 ZooKeeper-Style Lock

Ephemeral nodes plus ordered watches can represent ownership and automatically disappear when the client’s session expires. The coordination service provides the ordering/consistency substrate.

ZooKeeper Distributed Lock

3.2 Redis-Style Lock

A common single-instance primitive is an atomic conditional write with an expiry and a unique owner token, followed by an atomic compare-and-delete release.

Redis Distributed Lock

4. Design Questions

Before using a distributed lock, define whether the lock protects correctness or merely reduces duplicate work. Correctness-critical locks need explicit reasoning about partitions, pauses, lease expiry, failover, and stale owners.

Loading helpful count