Mastering Redis Distributed Locks: setnx, RedLock, and Redisson Explained

This article explains how Redis implements distributed locks using the SET command with NX and PX options, compares plain setnx, Lua‑based atomic unlock scripts, and Redisson’s high‑level APIs including the RedLock algorithm, and provides practical code examples and pitfalls to avoid.

IT Architects Alliance
IT Architects Alliance
IT Architects Alliance
Mastering Redis Distributed Locks: setnx, RedLock, and Redisson Explained

setnx and the SET command

In Redis, the term setnx usually refers to using the SET command with the NX flag, not the legacy SETNX command. The full syntax is:

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

The lock works because the command succeeds only when the key does not already exist. When a process acquires the lock, it sets a key with a short expiration (e.g., PX 30000) to avoid deadlocks if the process crashes.

If the holder crashes before releasing the lock, the expiration automatically frees the lock for other processes.

Ensuring safe unlock

To prevent a process from accidentally deleting a lock owned by another, store a unique identifier (e.g., UUID) as the value. When releasing, first read the value and compare it with the stored identifier.

String uuid = ...; // generate UUID
// acquire lock
set Test uuid NX PX 3000;
try {
    // business logic
} finally {
    if (uuid.equals(redisTool.get('Test'))) {
        redisTool.del('Test');
    }
}

This approach still suffers from a race condition because GET and DEL are not atomic.

Atomic unlock with Lua

Redis allows executing a Lua script atomically via EVAL or EVALSHA. The following script deletes the key only when the stored value matches the provided 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, no other client can intervene between the check and the delete.

Redisson client

Redisson is a Java Redis client that wraps the low‑level commands with high‑level constructs such as RedissonLock, RedissonAtomicLong, etc. Its lock implementation also uses Lua scripts internally, providing a re‑entrant distributed lock out of the box.

Redisson’s lock API abstracts away the Lua details, but it still relies on the same principles: set the key with NX and an expiration, and release it atomically.

RedLock algorithm

RedLock is a distributed lock algorithm proposed by the Redis authors. It requires multiple independent Redis instances (no master‑slave relationship). The algorithm acquires the lock on a majority of nodes (⌊N/2⌋+1) and considers the lock successful only if the total time spent is less than the lock’s TTL.

Attempt to acquire the lock on each node sequentially.

Skip nodes that do not respond within a short timeout.

If at least three out of five nodes grant the lock and the elapsed time is below the TTL, the lock is considered acquired.

Otherwise, the lock acquisition fails.

When releasing, the client deletes the lock key on all nodes.

Conclusion

Redis‑based distributed locks are powerful but cannot guarantee 100 % safety; edge cases such as process crashes or network delays can still cause lock loss. Combining proper expiration, unique identifiers, atomic Lua scripts, or using a mature client like Redisson reduces risk, while application‑level compensation remains essential.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendredisdistributed-lockLuaredissonRedlocksetnx
IT Architects Alliance
Written by

IT Architects Alliance

Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.

0 followers
Reader feedback

How this landed with the community

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.