Appearance
Redlock Algorithm
Previously, we discussed the principles of distributed locks, which are quite simple to implement with a single command. However, in a cluster environment, this method has its flaws and is not absolutely safe.
For example, in a Sentinel cluster, when the master node fails, a slave node takes over, but the client may not be aware of this change. If the first client successfully acquires a lock on the master node but that lock hasn't synchronized to the slave node yet, and then the master fails, the slave becomes the new master. This new master does not have the lock, so if another client requests to acquire the lock, it will be approved immediately. This can lead to both clients holding the same lock simultaneously, creating a safety issue.
However, this insecurity arises only during the failover of the master-slave relationship and lasts for a very short duration, which most business systems can tolerate.
Redlock Algorithm
To address this issue, Antirez invented the Redlock algorithm. The process is relatively complex, but many open-source libraries, such as redlock-py
, provide good encapsulation for users.
python
import redlock
addrs = [{
"host": "localhost",
"port": 6379,
"db": 0
}, {
"host": "localhost",
"port": 6479,
"db": 0
}, {
"host": "localhost",
"port": 6579,
"db": 0
}]
dlm = redlock.Redlock(addrs)
success = dlm.lock("user-lck-laoqian", 5000)
if success:
print('lock success')
dlm.unlock('user-lck-laoqian')
else:
print('lock failed')
To use Redlock, you need to provide multiple Redis instances that operate independently without a master-slave relationship. Like many distributed algorithms, Redlock employs a "majority mechanism."
When acquiring a lock, it sends the set(key, value, nx=True, ex=xxx)
command to more than half of the nodes. If a majority of the nodes succeed in the set
operation, the lock is considered acquired. To release the lock, it sends a del
command to all nodes. However, the Redlock algorithm also needs to handle error retries, clock drift, and various other details. Additionally, because Redlock requires read and write operations to multiple nodes, its performance may decrease compared to a single Redis instance.
Redlock Use Cases
If you prioritize high availability and want your system to remain unaffected by the failure of a single Redis instance, you should consider using Redlock. However, this comes with trade-offs: you will need more Redis instances, experience reduced performance, introduce additional libraries in your code, and manage them with special care. These costs should be carefully weighed before implementation.