Redlock Algorithm
The basic steps that a Redis client will go through when using Redlock is as follows
- Client gets the current time milliseconds
- Client tries to acquire the lock in all N instances sequentially, using the same key name and random value. When trying to set the lock for each instance, a very small timeout value is set so that the client does not spend too much trying to connect to a Redis node but goes to the next Redis instance
- Client computes the elapsed time between the time to acquire the lock and the current timestamp. If and only if the client is able to acquire the lock from the majority of instances (minimum 3 instances) and the total elapsed time is less than the lock validity time, the lock is considered acquired.
- If the lock acquired, the validity time of the new lock is calculated as initial validity time minus the time elapsed as computed in the previous step
- If the client fails to acquire the lock, the client will attempt to unlock all of the instances.