Sometimes your redis needs a little help keeping up with expiries.
First, it's helpful to know how expiries are handled in redis internals:
Redis keys are expired in two ways: a passive way, and an active way.
A key is actively expired simply when some client tries to access it, and the key is found to be timed out.
Of course this is not enough as there are expired keys that will never be accessed again. This keys should be expired anyway, so periodically Redis test a few keys at random among keys with an expire set. All the keys that are already expired are deleted from the keyspace.
Specifically this is what Redis does 10 times per second:
Test 100 random keys from the set of keys with an associated expire. Delete all the keys found expired. If more than 25 keys were expired, start again from step 1.
This is a trivial probabilistic algorithm, basically the assumption is that our sample is representative of the whole key space, and we continue to expire until the percentage of keys that are likely to be expired is under 25%
This means that at any given moment the maximum amount of keys already expired that are using memory is at max equal to max amount of write operations per second divided by 4.
Effectively, there are scenarios where there are just too many expiring keys in a dataset for redis to be able to keep up with them via its passive method, so we need to take matters into our own hands.
redis = Redis.new(connection_params)
reh = RedisExpiryHelper.new(redis)
reh.run