I am using Redis 5 for my project, for my requirement, I have used ZADD to store data in the format, Device ID {Timestamp : Value}. I have to only store the data only for 2 weeks of time after which I want the data to be expired from Cache. Is there a possible way to remove the keys that are older than 2 weeks automatically or should I have to use a separate monitor to delete the keys using ZREMRANGE?
2
Answers
No you dont have to do in manually. Redis will handle that.
You can set and update expire duration of a key with EXPIRE command.
example:
my_lovely_key with expire after 60 seconds.
you can get the TTL of key like this:
The only way for Redis to remove keys that are older than 2 weeks automatically, is by expiring the entire key, the entire sorted set in your case.
If you want to work it out automatically, then you’ll have to use multiple keys, partitioning your data by date, so you can expire accordingly. For example, you can create a sorted set per day.
EXPIREAT
uses a Unix timestamp. Or useEXPIRE
with 1209600 seconds (two weeks).This way you have 14-15 keys at all times, oldest ones expiring automatically. You can use ZUNIONSTORE or ZINTERSTORE to operate on all of them.
You can use a key per day, per hour or per week, your call.
As Itamar pointed out, expiring partial contents of one key, like from a sorted set, is not supported, you will need to implement your own logic. You’ll have to choose what is simpler and best for your use case: partition in keys per dates to auto-expire, or implement your own ZREMRANGE logic.
Redis Streams
Sounds like your use case is telemetry-related, like a heartbeat (append-only). Take a look at Redis Streams.
You can have the Redis server set the timestamp for you, in the ID. It will do wonders to your memory efficiency: items are stored in a radix tree as delta-compressed macro nodes, same-field compression and integers encoded as binary. Antirez claims 13x memory efficiency.
The downsides:
But you can overcome these by using date-partitioning. Streams are so memory-efficient you may use one stream per week, and have 2-3 streams live, appending only to the latest one, setting
EXPIRE
to each stream accordingly.Take a look at the Redis Streams course from Redis University. Totally recommended.