12

I want to implement Absolute and Sliding Caching In Redis. Does anyone have any resource link then it will be helpful

1 Answer 1

20

Redis already have many commands for this :

  • EXPIRE : Set a timeout on key.
  • EXPIREAT : Same as previous but takes an absolute Unix timestamp (seconds since January 1, 1970).
  • TTL : Returns the remaining time to live of a key that has a timeout

One important thing you have to know about Expiration on Redis : the timeout value is cleared only when the key is removed or overwritten using SET or GETSET. All others commands (INCR, LPUSH, HMSET, ...) will never change the initial timeout.

Absolute expiration is a native feature of Redis using EXPIRE. To implement a sliding expiration you simply need to reset to timeout value after each command.

A basic way to do this could be

MULTI GET MYKEY EXPIRE MYKEY 60 EXEC 
Sign up to request clarification or add additional context in comments.

3 Comments

It's been 7 years, is there still no sliding expiration in Redis?
so sad to see an industry standard caching system still does not have native sliding expiration. It is what it is.
Note that as of Redis 6.2.0 the GETEX command allows you to do this in a single command.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.