Redis vs Zookeeper Distributed Locks: Reliability, Performance, and Pitfalls
This article analyzes the principles, advantages, and drawbacks of distributed locking with Redis and Zookeeper, comparing single‑node and cluster scenarios, discussing RedLock, EPHEMERAL znodes, and practical failure cases to help engineers choose the right solution.
正文
结论: Zookeeper’s reliability far exceeds Redis’s, but Redis offers higher efficiency; choose Zookeeper for reliability when concurrency is modest, otherwise prefer Redis for speed.
为什么使用分布式锁?
Distributed locks ensure that only one client can operate on a shared resource at a time. Martin distinguishes two use cases:
Multiple clients allowed: operations must be idempotent; the lock prevents duplicate work.
Single client allowed: operations are non‑idempotent; without a lock data inconsistency or loss may occur.
第一回合,单机情形比较
Redis
Lock acquisition uses the Redis command:
SET resource_name my_random_value NX PX 30000 my_random_value– random token generated by the client, identifies the lock owner. NX – set only if the key does not exist, allowing the first client to obtain the lock. PX 30000 – lock expires automatically after 30 seconds.
Unlocking is performed with an atomic Lua script:
if redis.call("get",KEYS[1]) == ARGV[1] then
return redis.call("del",KEYS[1])
else
return 0
endThe script checks that the stored value matches the client’s token before deleting, preventing a client from releasing a lock it does not own.
分析: The main weakness is the lock expiration time. If a client holds the lock longer than the TTL, the lock may expire while the client is still working, leading to unsafe concurrent access.
“Can we check after the operation whether the lock still belongs to the client and release it only if it does?”
Even this check only reduces the probability of conflict; it cannot eliminate it.
Zookeeper
Zookeeper implements locks using EPHEMERAL znodes. An EPHEMERAL node is automatically removed if the client session ends, eliminating the need for a TTL.
Clients attempt to create a znode (e.g., /lock). The first succeeds and holds the lock; subsequent attempts fail because the node already exists.
If the client crashes, the EPHEMERAL node disappears, releasing the lock.
分析: Although Zookeeper avoids expiration issues, it can still suffer from multiple clients holding a lock if a session timeout occurs (e.g., due to GC pauses).
第二回合,集群情形比较
Redis (Cluster with Sentinel)
Redis achieves high availability via master‑slave replication and Sentinel. Because replication is asynchronous, a master crash before slaves sync can cause data loss.
To mitigate this, the author of Redis (antirez) proposed the RedLock algorithm, which requires acquiring the lock on a majority of N independent Redis masters.
Record the current time (ms).
Attempt to lock the same key with a random value on each of the N masters, using a short per‑node timeout.
If the client obtains the lock on a majority (N/2+1) and the total elapsed time is less than the lock’s TTL, the lock is considered acquired.
Adjust the remaining TTL by subtracting the elapsed time.
If acquisition fails, release any partial locks on all masters.
分析: RedLock still suffers from several issues:
Node crash‑restart can lead to two clients holding the lock simultaneously.
Clock jumps on a node can cause premature expiration.
Lock expiration due to network delays is not fully resolved.
Zookeeper (Cluster)
Zookeeper clusters usually consist of an odd number of nodes (≥3). Write operations follow a quorum‑based protocol:
Client sends a write request to a follower.
Follower forwards the request to the leader.
Leader initiates a vote; if a majority ACKs, the write is committed.
Follower returns the result to the client.
Zookeeper enforces global serialization of operations, guaranteeing strong consistency. If a follower or leader crashes, a new leader is elected and the protocol continues, preventing split‑brain scenarios.
第三回合,锁的其他特性比较
Redis offers superior read/write performance; Zookeeper may become a bottleneck under high concurrency.
Zookeeper supports read‑write locks; Redis does not.
Zookeeper’s watch mechanism allows a client to block until a lock node is deleted, providing a local‑lock‑like experience that Redis cannot replicate.
总结
Both Redis and Zookeeper have reliability concerns, but Zookeeper’s distributed lock is generally more reliable, while Redis delivers higher performance. Choose the implementation based on the specific reliability and latency requirements of your production environment.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
