Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing TTL with redis sorted set members

Tags:

redis

I'm doing a setup for autocomplete and am looking into using redis sorted sets. There's quite a bit of documentation on this, but the gist is adding prefixes, for example abc would ZADD mySet - 0 a, 0 ab, 0 abc, 0 abc*.

Then as queries come in use ZRANK on the query then based on that, use ZRANGE to get matching results.

In any case, I want to implement a TTL on not the set, but the specific members of the set. I know this is not possible out of the box in redis, so I'm looking at implementing an alternative solution. One option is to use a timestamp as the rank, but this won't work in autocomplete as the rank matters, they need to have the same score to sort lexicographically.

The solution I'm thinking is to effectively replicate the sorted set, into an unsorted set. This would store values such as <prefix>:timestamp. Then on a schedule can get the members here, check times, delete from sorted set if expired. Obviously this increases the memory usage, but that's suitable.

My question is are there any better ways to do this? In terms of scale and or simplicity. Thanks!

like image 992
dzm Avatar asked Oct 15 '25 14:10

dzm


1 Answers

Use another Sorted Set to keep track of TTL-like timestamps as scores, query it periodically, or on every call, to find and remove "expired" prefixes.

like image 70
Itamar Haber Avatar answered Oct 18 '25 07:10

Itamar Haber