RM.
RM.

Reputation: 2043

How to choose the right value for the expiryTime parameter for RedLockFactory.CreateLockAsync() method?

I am using RedLock.net library for resource locking. To lock a resoruce I am using RedLockFactory.CreateLockAsync.

public async Task<IRedLock> RedLockFactory.CreateLockAsync(string resource,
      TimeSpan expiryTime,
      TimeSpan waitTime,
      TimeSpan retryTime,
      CancellationToken? cancellationToken = null)

I understand that this method will attempt to acquire a lock for waitTime by keep retrying every retryTime. However I do not understand what would be the right value for expiryTime. Once a lock has been acquired it will be kept until the lock is Disposed and that is irrespective of the expiryTime. In other words even if expirtyTime is set to 5 seconds if the lock is only diposed after 10 seconds then the lock will be kept for 10 seconds.

In many examples the value of 30 is used without explanation.
I have tested with a value of 0. A lock is not acquired at all.
I have tested with a value of 5 milliseconds. A lock is acquired and kept until disposed.

So how to choose the right value for the expiryTime parameter? It seems to me that this parameter is unnecessary and any non zero positive value is ok.

Upvotes: 2

Views: 2606

Answers (1)

Sam
Sam

Reputation: 381

ExpiryTime determines the maximum time that a lock will be held in the case of a failure (say, the process holding the lock crashing). It also indirectly determines how often the lock is renewed while it is being held.

e.g.

If you set an expiry time of 10 minutes:

  • the automatic lock renewal timer will call out to redis every 5 minutes (expiry time / 2) to extend the lock
  • if your process crashes without releasing the lock, you will have to wait up to a maximum of 10 minutes until the key expires in redis and another process can take out a lock on the same resource

If you set an expiry time of 10 milliseconds:

  • the automatic lock renewal timer will call out to redis every 5 milliseconds (expiry time / 2) to extend the lock (which might be a little excessive)
  • if your process crashes without releasing the lock, you will have to wait up to a maximum of 10 milliseconds until the key expires in redis and another process can take out a lock on the same resource

It's a balance between how much time you're willing to wait for a lock to expire in the failure case vs how much load you put on your redis servers.

Upvotes: 6

Related Questions