Redis Lock
lastmod 2024-06-10created 2024-06-053 edits
In a distributed system where multiple processes or threads are accessing shared resources concurrently, it becomes crucial to maintain data consistency and avoid race conditions. Redis, a popular in-memory data store, offers a simple yet effective mechanism called “Redis Lock” or “Redlock” to address these challenges. Redis Lock, also known as Distributed Locking with Redis, is a technique used to coordinate access to shared resources in a distributed environment.
RedLock is not perfect
According to the analysis by Martin Kleppmann mentioned in the official documentation, problems can occur even with the RedLock algorithm.
The code below acquires a Lock and then saves data to a file.
// THIS CODE IS BROKEN
function writeData(filename, data) {
var lock = lockService.acquireLock(filename);
if (!lock) {
throw 'Failed to acquire lock';
}
try {
var file = storage.readFile(filename);
var updated = updateContents(file, data);
storage.writeFile(filename, updated);
} finally {
lock.release();
}
}
The diagram and steps below visualize the problem that can occur in the code above.
- Client A acquires the lock on the master.
- On client A, a Stop-the-World GC pauses the application code, and the lock expires in the meantime.
- Client B acquires the distributed lock and writes data to the file.
- After the GC finishes, client A writes data to the file, causing a concurrency problem
RedLock_-_Stop-the-World_GC.png
GC usually runs very quickly, but a Stop-the-World GC can occasionally last long enough for the lock to expire. Martin Kleppmann's article shows that besides GC, RedLock can also break due to network delays or timing issues.
Personal opinion: just use something like etcd or ZooKeeper.
See also
- Redis
- Redisson
Favorite site
- Redis Lock - Redis
- [Recommended] Let's look at RedLock provided by Redis. RedLock provides the Lock that Redis recommends in distributed environments… | by Jeongkuk Seo | sjk5766 | Medium