Why Use Distributed Locks? Implementation with Redis, Redisson, and Zookeeper
The article explains the inventory oversell problem in distributed e‑commerce systems, why native JVM locks fail across multiple machines, and presents practical implementations of distributed locks using Redis (including RedLock and Redisson) and Zookeeper (with Curator), comparing their advantages and drawbacks.
When multiple instances of an e‑commerce service check and update inventory concurrently, a race condition can cause the same stock to be sold twice, known as the inventory oversell problem. Native Java locks such as synchronized or ReentrantLock only work within a single JVM, so they become ineffective after scaling out to multiple machines.
To solve this, a globally unique lock must be used, which leads to the concept of a distributed lock. The article first introduces a Redis‑based lock, where a lock is represented by a key set with SET key value NX PX ttl. The lock is released atomically using a Lua script that checks the value before deleting the key.
// acquire lock
SET anyLock unique_value NX PX 30000
// release lock (Lua script)
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
endKey points for the Redis approach are:
Use the atomic SET ... NX PX command to avoid deadlocks caused by crashes before setting an expiration.
Make the lock value unique so that only the owner can release it.
Consider Redis deployment modes (single‑node, master‑slave with Sentinel, or cluster) and their impact on availability.
RedLock algorithm tries to acquire the lock on a majority of cluster nodes, but its correctness is debated.
Redisson, an enterprise‑grade Redis client, abstracts these details. A typical usage pattern is:
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();
// critical section
lock.unlock();Redisson handles the lock’s TTL with a watchdog that automatically extends the expiration while the lock is held, preventing accidental releases.
The article then covers Zookeeper as an alternative. Zookeeper provides ordered (sequential) and temporary (ephemeral) znodes. A lock is acquired by creating an ephemeral sequential node under a lock directory, then checking if the created node has the smallest sequence number. If not, the client watches the predecessor node and waits for its deletion.
InterProcessMutex mutex = new InterProcessMutex(client, "/anyLock");
mutex.acquire();
// critical section
mutex.release();Curator’s implementation follows the same principle, using internal loops to watch the previous node and retry until the lock is obtained.
Finally, the article compares the two solutions:
Redis: simple to use, high performance, but relies on eventual consistency and may require busy‑waiting; RedLock adds complexity and still has edge‑case concerns.
Zookeeper: provides strong consistency and event‑driven waiting, making the lock model robust; however, heavy lock churn can stress the Zookeeper ensemble.
Recommendation: if a Zookeeper cluster is available, prefer it for its correctness; otherwise, Redis (or Redisson) is a practical choice when latency and throughput are critical and the system already uses Redis.
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.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.
