How can I update a redis value without affecting the remaining TTL?

paulkon picture paulkon · Feb 20, 2014 · Viewed 36.5k times · Source

Is it possible to SET redis keys without removing their existing ttl? The only way I know of at the present time is to find out the ttl and do a SETEX but that seems less accurate.

Answer

fgasparini picture fgasparini · Feb 20, 2014

According to Redis documentation, the SET command removes the TTL because the key is overwritten.

However you can use the EVAL command to evaluate a Lua script to do it automatically for you.

The script bellow checks for the TTL value of a key, if the value is positive it calls SETEX with the new value and using the remaining TTL.

local ttl = redis.call('ttl', ARGV[1]) if ttl > 0 then return redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end

Example:

> set key 123

OK

> expire key 120

(integer) 1

... after some seconds

> ttl key

(integer) 97

> eval "local ttl = redis.call('ttl', ARGV[1]) if ttl > 0 then return redis.call('SETEX', ARGV[1], ttl, ARGV[2]) end" 0 key 987

OK

> ttl key

96

> get key

"987"