Azure / AzureCacheForRedis

Repository to share Tools, Patterns, Samples, and track issues
MIT License
10 stars 10 forks source link

Unexpected keys without expiration #11

Closed Valdeminas closed 2 years ago

Valdeminas commented 2 years ago

Hi.

We use Azure redis cache. All of our keys are created with this code using StackExchange.Redis

public RedisCacheService(
            IConnectionMultiplexer cacheConnection)
        {
            _cacheConnection = cacheConnection;
            _cache = cacheConnection.GetDatabase();
        }

public async Task<long> IncrementAsync(string key, TimeSpan expiration)
        {
            var redisKey = new RedisKey(key);
            var tran = _cache.CreateTransaction();
            _ = tran.StringSetAsync(redisKey, 0, expiration, When.NotExists);
            var counterTask = tran.StringIncrementAsync(redisKey, 1);
            if (await tran.ExecuteAsync())
            {
                return await counterTask;
            }
            throw new InvalidOperationException($"Redis transaction failed.");
        }

I check for keys without expiry, by running this command via Redis console window in Azure portal:

EVAL "local keys = {} for i, name in ipairs(redis.call('keys', '*')) do local persistent = redis.call('pttl', name) < 0 if persistent == true then table.insert(keys, name) end end return keys" 0

Over the weekend we do ~42M sets. I would expect there to be 0 keys without expiration. However, the above command returns 11. If I delete these 11 keys, after a while there again are keys without expiration.

What could be causing this?

Thanks.

Valdeminas commented 2 years ago

Just a quick update.

Rewrote our code to evaluate the following script

@"local current current = redis.call('incr',@key) if current == 1 then redis.call('pexpire', @key, @timeout) end return current"; And the issue now seems to be fixed.