Pradeep Andrewson
Pradeep Andrewson

Reputation: 77

How to automatically remove an expired key from a set?

127.0.0.1:6379> keys *

1) "trending_showrooms"
2) "trending_hashtags"
3) "trending_mints"

127.0.0.1:6379> sort trending_mints by *->id DESC LIMIT 0 12

1) "mint_14216"
2) "mint_14159"
3) "mint_14158"
4) "mint_14153"
5) "mint_14151"
6) "mint_14146"

The keys are expired but the keys are inside set. I have to remove the expire keys automatically in redis

Upvotes: 1

Views: 3840

Answers (2)

davissp14
davissp14

Reputation: 775

You can't set a TTL on individual members within the SET.

This blog post dives a bit deeper on the issue and provides a few workarounds. https://quickleft.com/blog/how-to-create-and-expire-list-items-in-redis/

Hope that helps.

Upvotes: 1

Niloct
Niloct

Reputation: 10015

Please ready this page entirely: https://redis.io/topics/notifications

Summing up, you must have a sentinel program listening to PUB/SUB messages, and you must alter the redis.conf file to enable keyevent expire notifications:

in redis.conf:

notify-keyspace-events Ex

In order to enable the feature a non-empty string is used, composed of multiple characters, where every character has a special meaning according to the following table

E     Keyevent events, published with __keyevent@<db>__ prefix.
x     Expired events (events generated every time a key expires)

Then the sentinel program must listen to the channel __keyevent@0__:del, if your database is 0. Change the database number if using any other than zero.

Then when you subscribe to the channel and receive the key which is expiring, you simply issue a SREM trending_mints key to remove it from the set.

IMPORTANT

The expired events are generated when a key is accessed and is found to be expired by one of the above systems, as a result there are no guarantees that the Redis server will be able to generate the expired event at the time the key time to live reaches the value of zero.

If no command targets the key constantly, and there are many keys with a TTL associated, there can be a significant delay between the time the key time to live drops to zero, and the time the expired event is generated.

Basically expired events are generated when the Redis server deletes the key and not when the time to live theoretically reaches the value of zero.

So keys will be deleted due to expiration, but the notification is not guaranteed to occur in the moment TTL reaches zero.

ALSO, if your sentinel program misses the PUB/SUB message, well... that's it, you won't be notified another time! (this is also on the link above)

Upvotes: 1

Related Questions