okolobaxa
okolobaxa

Reputation: 342

Expiration callback in StackExchange.Redis

Does StackExchange.Redis has any ability to execute callback after cache item was expired? Like ICacheItemRefreshAction in Microsoft.Practices.EnterpriseLibrary.Caching

    [Serializable]
    private class CacheEventHandler : ICacheItemRefreshAction
    {
        public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
        {
            // Item has been removed from cache. Perform desired actions here, based upon
            // the removal reason (e.g. refresh the cache with the item).
            ResetStaticData();
        }
    }

Upvotes: 4

Views: 5999

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

This isn't ever possible (or it might be very unreliable), because Redis has some limitations on its built-in keyspace events when it comes to raising an event when a key expires (learn more here):

Timing of expired events

Keys with a time to live associated are expired by Redis in two ways:

  • When the key is accessed by a command and is found to be expired.
  • Via a background system that looks for expired keys in background, incrementally, in order to be able to also collect keys that are never accessed.

Thus, what you want isn't reliable at all. What happens if you want to re-introduce data after some cached key has expired but Redis tells you that the so-called key has expired so late?

In the other hand, Redis keyspace notifications are implemented using regular pubsub channels, and Redis pubsub is implemented over the concept of fire-and-forget. What happens if the process listening for key expirations isn't working when Redis wants to notify it?

I suggest you that you may better solve the issue using a task scheduler rather than relying on Redis for this.

When to rely on built-in expiration system

Even when you can't rely on notifications about key expirations, I would say that built-in expiration system is very powerful.

A sample use case might be that you need to expose a set of data to your users, and these users access to that data set a lot of times per hour.

That is, you add the so-called data set to Redis and you put an expiration time of 2 hours, and since the whole data doesn't change very much, your users won't access to the primary data while the data is cached in Redis.

After the data has expired, until not a great number of users access the data, Redis has no cache for it.

There're a lot of use cases for the expire command, but again, I would say that it's not good to take actions in real-time based on cache expiration.

If you want to go this route anyway...

...check a Q&A I openen a long time ago where you'll find a sample code about how to subscribe to keyspace pubsub channels:

Upvotes: 5

Related Questions