Mastering Redis Distributed Locks: From SetNX to RedLock and Redisson

This article explores the most common Redis locking mechanisms—SetNX, RedLock, and Redisson—detailing their principles, pitfalls, and implementation nuances, including code examples, Lua scripts for atomic unlocks, and best‑practice recommendations for building reliable distributed locks in backend systems.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Redis Distributed Locks: From SetNX to RedLock and Redisson

Common Redis Lock Terms

SetNX, RedLock, and Redisson are the three most frequently mentioned Redis locking concepts.

SetNX

In modern usage, “SetNX” usually refers to the SET command with the NX option rather than the legacy SETNX command. The SET command now supports many parameters:

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

For full details see the Redis SET command documentation.

The principle is that the key must not exist for the SET with NX to succeed, allowing a process to acquire a lock. A timeout (e.g., PX 30000) is used to avoid deadlocks if the holder crashes.

However, this approach cannot guarantee absolute safety. If the lock holder exceeds the timeout, other processes may acquire the lock and later be unintentionally released by the original holder.

Improved SetNX Pattern

To mitigate the risk, store a unique client identifier (e.g., a UUID) as the value and verify it before releasing the lock.

String uuid = xxxx; // generate a UUID
// pseudo code, actual API depends on the client library
set Test uuid NX PX 3000
try {
    // business logic
} finally {
    // unlock
    if (uuid.equals(redisTool.get('Test'))) {
        redisTool.del('Test');
    }
}

This pattern still suffers from a non‑atomic GET followed by DEL in the finally block.

Atomic Unlock with Lua

Using a Lua script ensures the check‑and‑delete operation is atomic:

-- Lua script to delete lock atomically
if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
else
    return 0
end

The script is executed via EVAL or EVALSHA, guaranteeing that no other client sees an intermediate state.

Historical SetNX + EXPIRE

Before Redis 2.6.12, SET did not support NX. Locking required two commands:

1. setnx Test uuid
2. expire Test 30

This two‑step process is not atomic and can fail if the process crashes after the first command.

Redisson

Redisson is a Java Redis client that provides high‑level APIs, including distributed implementations of Java concurrency utilities such as AtomicLong. Its lock implementation uses Lua scripts for atomicity and supports re‑entrancy.

RedLock

RedLock is an algorithm proposed by the Redis author for distributed locking across multiple independent Redis instances. It requires a majority (⌊N/2⌋+1) of nodes to acquire the lock within the lock’s TTL.

Send lock requests to all nodes.

Ignore nodes that do not respond within a configured timeout.

If at least three nodes grant the lock and the total elapsed time is less than the TTL, consider the lock acquired.

Release the lock on all nodes when done.

The algorithm assumes independent instances without master‑slave replication to avoid issues caused by asynchronous replication.

Conclusion

None of the discussed locking methods can guarantee 100 % reliability; therefore, proper fallback and compensation mechanisms are essential in production systems.

Relevant links:

https://redis.io/commands/set

https://github.com/redisson/redisson/wiki/Table-of-Content

https://redis.io/topics/distlock

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.

Backend Developmentredisdistributed-lockredissonRedlocksetnx
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.