Understanding Redis Distributed Locks: setnx, Redisson, and RedLock
This article explains how Redis setnx, the Redisson client, and the RedLock algorithm work together to implement distributed locks, discusses common pitfalls such as non‑atomic unlocks, and provides Lua scripts and Java pseudocode for safe lock acquisition and release.
Redis distributed locking commonly involves three terms: setnx , RedLock , and Redisson . The setnx concept actually refers to using the SET command with the NX option, e.g.:
SET key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]
To avoid deadlocks, a timeout (e.g., PX 30000 ) is set so that a crashed process does not hold the lock indefinitely.
When releasing a lock, the value stored (often a UUID or client ID) should be checked before deletion. A typical Java‑style pseudocode is:
String uuid = xxxx; set Test uuid NX PX 3000 try { // business logic } finally { if (uuid.equals(redisTool.get('Test'))) { redisTool.del('Test'); } }
However, GET and DEL are not atomic, which can still cause race conditions. An atomic solution uses a Lua script executed via EVAL :
-- lua delete lock -- KEYS[1] = lock key, ARGV[1] = expected UUID if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end
Before Redis 2.6.12, locks were implemented with two commands ( SETNX + EXPIRE ), which was not atomic. Modern Redis supports the combined SET with NX and expiration, simplifying lock code.
Redisson, a Java Redis client, provides high‑level lock APIs (e.g., RedissonLock ) that internally use Lua scripts for atomic lock/unlock operations, supporting re‑entrancy and distributed lock features.
RedLock is a Redis‑official distributed lock algorithm that requires a majority of independent Redis instances to acquire the lock. The algorithm succeeds if at least (N/2)+1 nodes grant the lock within the lock’s TTL.
Despite these mechanisms, no solution guarantees 100 % safety; developers should still implement compensating actions for edge cases.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow 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.