mike-marcacci / node-redlock

A node.js redlock implementation for distributed, highly-available redis locks
MIT License
1.83k stars 172 forks source link

[QUESTION] Why does Redlock need to try to acquire the lock in all the N instances sequentially? #182

Open GO-DIE opened 2 years ago

GO-DIE commented 2 years ago

In Distributed locks with Redis – Redis - The Redlock algorithm, it says:

In order to acquire the lock, the client performs the following operations:

  1. It gets the current time in milliseconds.
  2. It tries to acquire the lock in all the N instances sequentially, using the same key name and random value in all the instances. During step 2, when setting the lock in each instance, the client uses a timeout which is small compared to the total lock auto-release time in order to acquire it. For example if the auto-release time is 10 seconds, the timeout could be in the ~ 5-50 milliseconds range. This prevents the client from remaining blocked for a long time trying to talk with a Redis node which is down: if an instance is not available, we should try to talk with the next instance ASAP.
  3. ...

I don't understand why it needs to try to acquire the lock in all the N instances sequentially. What can go wrong if we try to acquire the lock in all the N instances in parallel?

pwliuab commented 1 year ago

If it is in parallel, every instance can acquire a lock which is another race condtion again. e.g. A,B,C,D acquire the same lock at the same time. If it is not executed sequetially, can we say all of them get the lock ? We need to treat it as first come first serve bias. It can ensure that critical session is accessed only one user instead of multiple users at the same time.

iliasbhal commented 2 months ago

if it's done in parallel, the system will probably never be able to step into the its critical section. The processes will probably acquire some of the locks but never all of them. And retrying won't help, it will just create backpressure on your system.

But if done sequentially, it will fail early and never block another process from acquiring the remaining locks. Let me know if that makes sence 👍