Implementing Distributed Locks with Redis, Zookeeper, and etcd
The article explains how to build reliable distributed locks using Redis, Zookeeper, and etcd, describing the essential concepts of mutual exclusion, safety, and liveness, showing code examples, highlighting common issues, and comparing each solution's advantages and drawbacks.
A senior architect introduces the concept of distributed locks, emphasizing the two core requirements: mutual exclusion and safety, and the need for liveness to avoid deadlocks when clients crash or network partitions occur.
Redis‑based Distributed Lock
The lock is created by using the SET key value EX 10 NX command, which sets the key with a 10‑second TTL only if it does not already exist. Deleting the lock is done with DEL key .
# 对资源key加锁,key不存在时创建,并且设置,10秒自动过期
SET key value EX 10 NX
# 删除key
DEL keyThe NX option guarantees that only one client can acquire the lock when it does not exist. Setting an expiration time prevents deadlocks caused by client crashes.
However, a simple SETNX+EX approach may still lead to overselling because the lock acquisition and the critical section are not atomic; using a Lua script can make the check‑and‑set operation atomic.
Redis is popular for distributed locks because it is fast, simple, and easy to deploy, but it has drawbacks such as single‑point‑of‑failure (mitigated by the RedLock algorithm) and the inability to block when lock acquisition fails (addressed by frameworks like Redisson).
Zookeeper‑based Distributed Lock
Zookeeper implements locks using temporary sequential nodes. A temporary node is automatically removed when the client session ends, providing automatic cleanup. The watch mechanism can notify clients of node deletions, allowing them to attempt lock acquisition promptly.
etcd‑based Distributed Lock
etcd offers transactional operations (IF/THEN/ELSE) that can compare a key's version or creation revision to ensure atomicity. Leases provide a TTL for keys, automatically releasing the lock if the lease expires, which solves liveness issues caused by crashes or network partitions.
Watches in etcd enable efficient detection of lock release events, reducing lock unavailability time.
References
Redis Lua scripts for distributed locks, SETNX+Lua implementations, and discussions of RedLock and Redisson.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.