Redis: possible to expire an element in an array or sorted set?

CachingRedis

Caching Problem Overview


Is it currently only possible to expire an entire key/value pair? What if I want to add values to a List type structure and have them get auto removed 1 hour after insertion. Is that currently possible, or would it require running a cron job to do the purging manually?

Caching Solutions


Solution 1 - Caching

There is a common pattern that solves this problem quite well.

Use sorted sets, and use a timestamp as the score. It's then trivial to delete items by score range, which could be done periodically, or only on every write, with reads always ignoring the out of range elements, by reading only a range of scores.

More here: https://groups.google.com/forum/#!topic/redis-db/rXXMCLNkNSs

Solution 2 - Caching

> Is it currently only possible to expire an entire key/value pair?

As far as I know, and also according to key commands and document about expiration, currently you can set expiration only to specific key and not to it's underlying data structure. However there is a discussion on google groups about this functionality with outlined alternative solutions.

Solution 3 - Caching

I came upon a different method of handling this, don't know if it's helpful to any of you,but here goes:

The hash and the sorted set are linked by a guid.

  1. I have a hash that is set to expire in 'x' seconds
  2. I have a sorted set that is used for ranged queries
  3. The data for both is added in a transaction, so if one fails, they both fail.
  4. Upon a ranged query, use 'EXISTS' to see if the hashed value exists as the results are iterated over
  5. If it does not exist, it has expired, so delete the item from the sorted set

Solution 4 - Caching

What about creating two seperate sorted sets?

Main sorted set which is key = value.

Expire sorted set which is key = expire_timestamp. If you only want to expire a single score you can set as key:unique_id = expire_timestamp.

With mercy of zrangebyscore we can get expired keys. Then all we need to do is check periodically and zrem. If you only want to expire a single score: ​zincrby -1.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrandombitsView Question on Stackoverflow
Solution 1 - CachingAdriaan PelzerView Answer on Stackoverflow
Solution 2 - Cachingyojimbo87View Answer on Stackoverflow
Solution 3 - CachingJEPriceView Answer on Stackoverflow
Solution 4 - CachingfishukeView Answer on Stackoverflow