Understanding Redis Locks: setnx, RedLock, Redisson and Best Practices
This article explains how Redis locking works, covering the setnx command, the importance of using unique values, atomic unlock via Lua scripts, the Redisson client features, and the RedLock distributed algorithm, while highlighting common pitfalls and practical recommendations.
Redis locks are a common technique for ensuring mutual exclusion in distributed systems. The article starts by clarifying that the term setnx usually refers to using the SET command with the NX option, not the deprecated SETNX command, and shows the full syntax:
SET key value [EX seconds|PX milliseconds] [NX|XX] [KEEPTTL]Because a lock can be accidentally released by a process that crashes, a timeout (e.g., PX 30000 ) is set to automatically free the lock. However, simply using SETNX does not guarantee safety; the value stored with the lock should be a unique identifier (UUID or client ID) so that only the owner can release it.
The article provides pseudo‑code for acquiring and releasing a lock safely:
String uuid = xxxx;
// acquire lock
set Test uuid NX PX 3000
try {
// business logic
} finally {
// unlock only if the value matches
if (uuid.equals(redisTool.get('Test'))) {
redisTool.del('Test');
}
}Since GET and DEL are not atomic, the author recommends using a Lua script to perform the check‑and‑delete in a single Redis command, guaranteeing atomicity:
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
endRedisson, a Java Redis client, abstracts these details and offers high‑level lock APIs such as RedissonLock and RedissonRedLock . It implements lock acquisition and release via Lua scripts, supports re‑entrancy, and integrates with various Redis deployment modes (single node, master‑slave, sentinel, cluster).
The article then introduces the RedLock algorithm, an official Redis distributed lock design that requires a majority of independent Redis instances (N/2+1) to acquire the lock within a timeout. It outlines the steps: request locks sequentially, skip nodes that exceed the timeout, consider the lock successful if a majority succeed before the lock’s TTL expires, and release the lock on all nodes.
Finally, the author emphasizes that no lock implementation can guarantee 100 % reliability; developers should combine proper lock usage with fallback mechanisms and understand the trade‑offs of each approach.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.