Redis: Event on key expire

Created on 16 Apr 2019  路  1Comment  路  Source: redis/redis

I wonder if there is a feature in redis that allow me to get all expired keys (I mean some kind of event, that gives me an opportunity to take back all expire records). The purpose of it is in saving old values into another database. I've heard that it's possible using publishing mechanism, but google can't help we with this idea.

Most helpful comment

Hello @MehranMazhar

There is no such feature that is built into Redis - the expiry mechanism does not provide a way to "dump" the values upon expiration. It is indeed possible to subscribe to keyspace notifications to be notified of expiry events, but such messages would not include the values - only key names.

You can, however, make something like that with Redis. There quite a few ways, but the easiest imo would go something like that:

  1. Assuming your to-be-expired key is called 'foo', when you create it don't expire it but rather create another key called 'foo:expire' and set the TTL on it.
  2. Subscribe to keyspace notifications (https://redis.io/topics/notifications) on the '*:expire' pattern.
  3. Upon getting an expiry event, fire the logic to store and remove the "old" data ('foo')

Note: PubSub does not ensure delivery, so you may end up with "old" data that was not deleted. A periodic SCAN can help with that.

>All comments

Hello @MehranMazhar

There is no such feature that is built into Redis - the expiry mechanism does not provide a way to "dump" the values upon expiration. It is indeed possible to subscribe to keyspace notifications to be notified of expiry events, but such messages would not include the values - only key names.

You can, however, make something like that with Redis. There quite a few ways, but the easiest imo would go something like that:

  1. Assuming your to-be-expired key is called 'foo', when you create it don't expire it but rather create another key called 'foo:expire' and set the TTL on it.
  2. Subscribe to keyspace notifications (https://redis.io/topics/notifications) on the '*:expire' pattern.
  3. Upon getting an expiry event, fire the logic to store and remove the "old" data ('foo')

Note: PubSub does not ensure delivery, so you may end up with "old" data that was not deleted. A periodic SCAN can help with that.

Was this page helpful?
0 / 5 - 0 ratings