Why Distributed Locks Matter: Redis vs Zookeeper Explained
This article examines the stock‑oversell problem in high‑concurrency e‑commerce systems, explains why native JVM locks fail in multi‑machine deployments, and compares practical distributed‑lock solutions using Redis (including RedLock and Redisson) and Zookeeper (with Curator), highlighting their advantages, drawbacks, and selection guidelines.
Why Use Distributed Locks?
Before discussing the need for distributed locks, consider an e‑commerce system (System A) that checks inventory in Redis before allowing an order. When two requests arrive simultaneously and the inventory count is 1, both may read the same value and both decrement, resulting in overselling.
This classic stock‑oversell problem occurs because a lock that protects the critical section (steps 2‑4) works only on a single JVM. Adding more machines makes the lock ineffective across nodes.
Distributed Lock Concept
A distributed lock provides a global, unique lock object that all instances can acquire, ensuring only one node executes the critical section at a time. The lock can be backed by Redis, Zookeeper, or a database.
Redis‑Based Distributed Lock
The simplest approach uses Redis SET key value NX PX ttl to acquire a lock and a Lua script to release it atomically.
// Acquire lock
// NX – set only if key does not exist, PX – expiration in ms
SET anyLock unique_value NX PX 30000
// Release lock (Lua script ensures atomicity)
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
endKey points:
Use SET … NX PX to guarantee atomic creation and expiration; otherwise a crash before setting the TTL can cause deadlocks.
Value must be unique so that only the lock owner can release it, preventing accidental deletion of another node’s lock.
Redis deployment modes:
Standalone
Master‑slave with Sentinel
Cluster
Drawbacks include single‑point failure in standalone mode and possible lock loss during master failover. To mitigate this, Redis’ creator proposed the RedLock algorithm, which acquires the lock on a majority of nodes in a Redis cluster (e.g., 3 out of 5 masters) and validates the acquisition time against a timeout.
Redisson Framework
Redisson is an enterprise‑grade Redis client that implements distributed locks with additional safety features such as a watchdog that automatically extends the lock’s TTL while the client holds it.
Config config = new Config();
config.useClusterServers()
.addNodeAddress("redis://192.168.31.101:7001")
.addNodeAddress("redis://192.168.31.101:7002")
.addNodeAddress("redis://192.168.31.101:7003")
.addNodeAddress("redis://192.168.31.102:7001")
.addNodeAddress("redis://192.168.31.102:7002")
.addNodeAddress("redis://192.168.31.102:7003");
RedissonClient redisson = Redisson.create(config);
RLock lock = redisson.getLock("anyLock");
lock.lock();
lock.unlock();The watchdog renews the lock’s expiration every 10 seconds, preventing accidental expiration while the lock is still held.
Zookeeper‑Based Distributed Lock
Zookeeper provides ordered, ephemeral nodes and event watches, making it well‑suited for lock coordination.
Create an ephemeral sequential node under a lock directory (e.g., /lock).
List all children of the directory and determine if the created node has the smallest sequence number.
If it is the smallest, the lock is acquired.
If not, set a watch on the immediate predecessor node; when that node is deleted, repeat the check.
When the lock holder releases the lock, it deletes its node, triggering the watch on the next node, which then acquires the lock.
Curator Client Example
InterProcessMutex lock = new InterProcessMutex(client, "/anyLock");
lock.acquire();
lock.release();Curator’s internal implementation follows the same ordered‑node algorithm, handling retries and session expiration automatically.
Comparison of Redis and Zookeeper Locks
Redis advantages: extremely high performance, simple API, widely deployed in many enterprises.
Redis disadvantages: lack of strong consistency, potential lock loss during master failover, and the need for continuous retry loops.
Zookeeper advantages: strong consistency, built‑in coordination primitives, low contention thanks to watch‑based notifications.
Zookeeper disadvantages: higher load on the ensemble when many clients frequently acquire/release locks.
Recommendation
If a Zookeeper cluster is available, it is generally preferred for its robustness and consistency. When only Redis is present, using Redis (or Redisson) is a practical alternative, especially when performance is critical and the risk of edge‑case failures is acceptable.
Source: ITPUB技术小栈
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
