Databases 12 min read

Understanding Redis Distributed Locks: setnx, Redisson, and RedLock

This article explains the fundamentals and pitfalls of using Redis for distributed locking, covering the setnx command, the SET command with NX and PX options, Lua‑based lock scripts, Redisson’s lock implementations, and the RedLock algorithm, along with practical code examples.

Top Architect
Top Architect
Top Architect
Understanding Redis Distributed Locks: setnx, Redisson, and RedLock

When talking about Redis locks, three high‑frequency terms appear most often: setnx, RedLock, and Redisson.

setnx

RedLock

Redisson

setnx

In practice, the term "setnx" usually does not refer only to the Redis command setnx key value . It generally denotes using the SET command with the NX option, which now supports many additional parameters:

SET key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]

The diagram below (drawn by the author) shows the basic principle of setnx : it succeeds only when the key does not exist, so process A obtains the lock, and process B fails while the key remains.

Why set a timeout with PX 30000 ? Because if process A crashes while holding the lock, the lock would never be released and no other process could acquire it.

Even with a timeout, the lock is not guaranteed to be safe. If process A exceeds the timeout while operating on the locked resource, it may release the lock after process B has already acquired it, causing B’s lock to be unintentionally deleted. The following diagrams illustrate such scenarios.

Therefore, when using setnx , the value should not be ignored; a unique client ID or a UUID can be stored as the value.

During unlocking, the value should be checked to ensure the lock belongs to the current process before deletion. The following pseudo‑code demonstrates this:

String uuid = xxxx; // obtain a UUID
// set the lock with NX and a 3000 ms expiration
set Test uuid NX PX 3000
try {
    // business logic ...
} finally {
    // unlock
    if (uuid.equals(redisTool.get('Test'))) {
        redisTool.del('Test');
    }
}

However, the get and del operations are not atomic, so a race condition may still exist.

To achieve atomicity, a Lua script can be used. The script checks the stored value and deletes the key only if it matches the provided UUID:

-- Lua script to delete a lock
-- KEYS[1] is the lock key, ARGV[1] is the expected UUID
if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
else
    return 0
end

Because the whole script runs as a single command ( EVAL / EVALSHA ), it guarantees atomic execution.

Now we turn to Redisson , a Java Redis client that provides convenient APIs for distributed locks and many other features. Redisson implements its locks using Lua scripts, offering out‑of‑the‑box functionality similar to JUC classes such as AtomicLong .

Redisson’s lock implementation (class RedissonLock ) uses Lua scripts for both acquiring and releasing locks, ensuring atomicity. It also supports re‑entrancy, similar to Java’s ReentrantLock .

The RedLock algorithm, proposed by Redis’s creator, is a distributed lock algorithm that requires multiple independent Redis instances. It acquires a lock if a majority (N/2 + 1) of instances grant the lock within a specified timeout.

The algorithm’s steps are:

Request the lock sequentially from five Redis nodes.

Skip nodes that exceed the configured timeout.

If three nodes grant the lock and the total time spent is less than the lock’s TTL, consider the lock acquired.

Otherwise, the lock acquisition fails.

Redisson also provides a getRedLock method that implements this algorithm.

In practice, the lock’s effective lifetime is reduced by the time spent on successful nodes and the time waiting for timed‑out nodes. Therefore, the lock cannot guarantee 100 % reliability; manual compensation mechanisms are still necessary.

In summary, Redis‑based distributed locks—whether implemented with SET NX , Lua scripts, Redisson, or the RedLock algorithm—offer powerful tools but come with inherent trade‑offs that must be understood and mitigated.

RedisDistributed LockLuaRedissonRedlockSETNX
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.