RedLock.net icon indicating copy to clipboard operation
RedLock.net copied to clipboard

The TTL keeps resetting instead of expiring the key

Open MatheusTheBot opened this issue 11 months ago • 2 comments

Expected Behavior: After creating a new key with TTL, said key would be disposed without needing to call RedLockfactory.Dispose();

Current Behavior: After creating a new key with TTL, said key resets its TTL before getting expired and if manually deleted from the database with Redis Insights, the same key is not deleted and appears again after few seconds. This behavior keeps until my application is finished.

Here is a simple working example of the issue

Image

Image

Image

Image

When i try creating a new key on redis, it successfully does, but does said key does not expire when it reach its TTL, instead it resets the key's TTL to its original value and keeps that way until i finish the application.

What i have tried:

  • Doing a new request does not seems to work
  • Setting RedisService to Scoped also does not help, even though in theory after a request, the instance would be destroyed and so would be the RedLockFactory property
  • Adding a deconstructor calling RedLockFactory.Dispose() on RedisService also does not work
  • If I try call redLock.Dispose() on TestRegister(), it does work, but the key is instantly deleted from the database

I'm creating this issue to be sure that this is the intended behavior and how should i proceed

MatheusTheBot avatar Mar 17 '25 15:03 MatheusTheBot

I guess this is because the RedLock class not is implementing an destructor that disposing the refresh timer. See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers for more about destructor and I think it can be a good point to implement so the timer etc is finalizer correctly even when developer missing to implement the execute the disposal.

Tasteful avatar Mar 17 '25 15:03 Tasteful

If you don't Dispose() IRedLock instance, then its internal timer will keep refreshing the lock (TTL). This is by desing of this locking mechanism.

Internally RedLock has a timer that automatically tries to keep the redis lock key alive. In the worst case of a process crashing without releasing the lock, it will automatically be expired by redis after the specified expiry time.

..always dispose, always wrap in using

cbmek avatar Dec 08 '25 10:12 cbmek