scan does not delete expired keys in redis

Viewed 546

I have some keys which have expiration in redis. I check them with EXISTS in my application and I decide based on its output.

When they reach their expiration time, the TTL command, returns -1, but they are not removed from redis and EXISTS command still returns 1 for them; which my app assumes that they are not yet expired.

However, since I realized that these keys will be deleted once someone tries to access them using SCAN or similar commands, I tried to do the same. I used SCAN on my key, but it didn't delete my key.

Is there any command to check if a key is not expired? A command that returns 1 only if both following conditions are true:

  1. The key exists in redis
  2. The expiration of the is positive
1 Answers

In Redis 2.6 or older the TTL command returns -1 if the key does not exist or if the key exist but has no associated expire.

Starting with Redis 2.8 the return value in case of error changed:

  • The command returns -2 if the key does not exist.
  • The command returns -1 if the key exists but has no associated expire.

So in your case, your keys exists but they don't have an associated expiration . Actually you are accessing the keys with your EXISTS commands executed on your keys, but they don't have expiration - so they are not expired.

So you need to set expiration for those keys, then they will expired actively(whey you accessed them) or passively (with redis's expiration algorithm running behind the scenes)

Related