1

I'm trying to use RedLock to prevent 2 users from doing an operation on the same resource at once (Booking something too quickly from one another). But I want it to fail completely if the resource is already acquired by someone else (Booking availability will be gone after the transaction of request commits). It's not clear to me on docs what happens if the resource is still locked and how to fail at that point. Does it just throw an error? https://github.com/mike-marcacci/node-redlock#usage-promise-style.

const redlock = new Redlock(...);
let lock;
try {
  lock = redlock.lock('bookId', 120000);
} catch (err) {
  // ... lock failed to be acquired because someone else still had it? (after retries are finish)
}
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • The doc for node-redlock is pretty lacking for explaining how the `.lock()` method actually works and what its precise behavior is. It appears that it implements the "Redlock Algorithm" which you can read about [here](https://redis.io/topics/distlock). That explains timeouts and error handling to some level. You control the retry parameters with the options to `new Redlock(...)`. – jfriend00 Jun 18 '21 at 00:13

1 Answers1

0

The above example I used did in fact work. Once all tries to acquire the lock are spent, it does throw an error. In most mutual exclusion cases, that shouldn't occur. It should be configured such that there is enough time for other clients waiting on the locked resource to eventually get it. In the case you want it to fail completely (You don't want the second client to ever acquire the resource), just configure the Redlock for a single attempt and the Redlock will throw.

const redlock = new Redlock(...);
let lock;
try {
  lock = redlock.lock('bookId', 120000);
} catch (err) {
  // Attempted to grab lock but failed after all attempts (configured) are finished
}
  • Hi ALostBegginer, I am also in the situation where I dont want any other client to obtain lock on same resource but want to log the attempt. So then when creating Redlock, I should give retryCount:0 ? and error inside catch will give me required log? Any help would be really great, thanks! – CuriousCurie Oct 03 '22 at 06:59