Understanding Distributed Locks with Redis and Redisson: Concepts, Implementation, and RedLock Algorithm
This article explains what distributed locks are, their requirements, how to implement them using Redis commands and the Redisson library in Java, and introduces the RedLock algorithm for multi‑node fault‑tolerant locking, complete with code examples and practical considerations.
Introduction – Distributed lock articles are abundant, but many are either too shallow or overly academic; this guide provides a practical, middle‑ground overview, dividing the topic into three parts: definition, implementation requirements, and Redis‑based lock using Redisson.
1. What Is a Distributed Lock
A distributed lock is a lock that works across a distributed system, ensuring mutual exclusion when multiple nodes access a shared resource. It builds on concepts such as CAP theorem, distributed storage, and transactions.
Thread lock (e.g., synchronized ) – uses shared memory within a JVM.
Process lock – typically implemented via file locks to coordinate separate OS processes.
Distributed lock – needed when many servers could run the same scheduled task, preventing duplicate execution.
2. Requirements for a Distributed Lock
Mutual exclusion : only one client may hold the lock at any time.
Dead‑lock prevention : the lock must expire automatically if the holder crashes.
Ownership : the same client that acquired the lock must release it.
Fault tolerance : the external system (e.g., Redis) must remain highly available.
An analogy is renting a warehouse: only one tenant can hold the key at a time, the lease has a fixed duration, and the door must stay functional.
3. Redis‑Based Distributed Lock
Using Redis 2.6.12+ we can rely on the SET command with NX and expiration options ( EX or PX ) to achieve atomic lock acquisition:
SET key value NX PX 30000The lock value is a unique identifier (e.g., UUID + thread ID). To release the lock safely, a Lua script checks the stored value before deleting:
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
endRedisson Implementation
Redisson provides a high‑level Java API that wraps the above logic, handling re‑entrancy, lease time, and automatic renewal (watchdog). Example configuration for a single Redis node:
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379");
RedissonClient client = Redisson.create(config);
RLock lock = client.getLock("myLock");Typical lock acquisition with timeout and lease time:
boolean locked = lock.tryLock(100, 10, TimeUnit.MILLISECONDS);
if (locked) {
// business logic
Thread.sleep(10000);
}
finally {
lock.unlock();
}The RLock interface mirrors java.util.concurrent.locks.Lock and adds methods such as isLocked() , isHeldByCurrentThread() , and remainTimeToLive() . Internally Redisson uses Lua scripts for atomic operations, a subscription channel to receive unlock notifications, and a watchdog thread that periodically extends the lock’s TTL.
RedLock (Multi‑Node Algorithm)
To address single‑node failures, the RedLock algorithm acquires the same lock on N independent Redis masters (commonly N=5). The client records the start time, tries to lock each node with a short timeout, and succeeds only if it obtains locks on a majority (N/2+1) within the total elapsed time less than the lock’s TTL. Unlocking must be performed on all nodes.
Redisson implements this via RedissonRedLock (or RedissonMultiLock ) which aggregates several RLock instances:
RedissonRedLock redLock = new RedissonRedLock(lock1, lock2, lock3);
boolean ok = redLock.tryLock(100, 10, TimeUnit.SECONDS);
if (ok) {
// critical section
}
finally {
redLock.unlock();
}The implementation handles partial failures, lease‑time calculations, and automatic cleanup of acquired locks when the algorithm cannot meet the majority requirement.
Conclusion
Redis provides a simple yet powerful primitive for distributed locking, while Redisson abstracts the complexity, offering re‑entrant locks, watchdog renewal, and multi‑node RedLock support. Understanding these mechanisms helps developers choose the right trade‑offs between simplicity, performance, and fault tolerance.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.