Understanding Redis Distributed Locks: setnx, RedLock, and Redisson
This article explains how Redis can be used for distributed locking, covering the setnx command, the SET command with NX and PX options, common pitfalls, Lua‑based atomic unlock scripts, the Redisson client, and the RedLock algorithm for achieving reliable locks across multiple nodes.
Redis locks are a frequent interview topic; the three most common terms are setnx , redLock , and redisson .
The term setnx usually refers to using the SET command with the NX option, not the legacy SETNX command. The full syntax is:
SET key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]
Setting a timeout (e.g., PX30000 ) prevents a lock from being held indefinitely if the owning process crashes, but simple SET NX still suffers from race conditions when unlocking.
To avoid releasing another process's lock, store a unique client identifier (UUID) as the value and compare it before deletion. A typical pseudo‑code pattern is:
String uuid = xxxx;
// acquire lock
set Test uuid NX PX 3000;
try {
// business logic
} finally {
if (uuid.equals(redisTool.get('Test'))) {
redisTool.del('Test');
}
}However, the GET and DEL operations are not atomic, which can still cause safety issues. The atomic solution is to use a Lua script that checks the value and deletes the key in a single command:
-- Lua script for atomic unlock
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
endRedisson, a Java Redis client, encapsulates these Lua scripts and provides high‑level APIs such as RedissonLock , RedissonAtomicLong , and re‑entrant lock implementations, making distributed locking easier to use.
The RedLock algorithm, proposed by Redis’s creator, implements a distributed lock across multiple independent Redis instances. It requires a majority (⌊N/2⌋+1) of nodes to acquire the lock within a short timeout. If the lock’s TTL is 30 seconds but three nodes take 31 seconds, the lock acquisition fails. Proper timing (e.g., 5‑50 ms per node for a 10 s TTL) is crucial.
Debates exist between experts such as Martin Kleppmann and antirez about RedLock’s safety; reading both perspectives is recommended before adopting the algorithm.
In summary, no Redis lock can guarantee 100 % reliability; developers should combine careful lock design with compensating mechanisms to handle edge cases.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
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.