azure-redis-cacheredis-cache

Reliable Redis cache TTL expiration hook


Does Azure Redis cache allow me to set a function to reliably trigger whenever a certain key in my cache expires?


Solution

  • You can combine a client using Redis Pub/Sub and Redis Keyspace Notifications to have a client receive a message when events happen to specific keys, or when specific events happen to any key. You can then use pattern-matching subscriptions to receive messages for more than a single key. You can also subscribe to multiple channels from a single client; all messages include which channel it is publishing to so your client can decide what to do.

    To receive a message when any key beginning with foo expires, do the following:

    1. Set notify-keyspace-events config value to Kx using the Azure Portal. Steps to set value for Azure are here. More details on the config value schema are defined here.
    2. Using the client of your choice, PSUBSCRIBE (pattern subscribe) to the channel for your key: PSUBSCRIBE '__keyspace@*__:foo*'
    3. Using another client connection, set a value for your key with a TTL: SET foo42 bar EX 5
    4. After 5 seconds, you should see a message on your subscribing client: "pmessage","__keyspace@*__:foo*","__keyspace@0__:foo42","expired"

    To receive a message when any key expires, do the following:

    1. Set notify-keyspace-events config value to Ex
    2. PSUBSCRIBE to the keyevent channel for keys being expired: PSUBSCRIBE '__keyevent@*__:expired'
    3. In another client, set a key with a TTL: SET foo bar EX 5
    4. After 5 seconds, see a message on your subscribing client: "pmessage","__keyevent@*__:expired","__keyevent@0__:expired","foo"

    For clients to quickly develop and debug, I would recommend using redis-cli or the Redis console in the Azure Portal.

    Hope this helps. Good luck!