How to Set an Expiry Only When the New Expiry is Less Than the Existing Expiry in Redis

When setting a timeout on a key in Redis, we have the option of setting the timeout only if it’s less than the existing timeout. We can do this with the LT option of commands such as EXPIRE, EXPIREAT, PEXPIRE, and PEXPIREAT.

Example

Suppose we set a key with the following expiry:

SET user "Marge" EX 780

Result:

OK

This key has an expiry of 780 seconds.

Let’s use the EXPIRE command to try to set an expiry that’s greater than the current expiry:

EXPIRE user 800 LT

Result:

(integer) 0

We get an integer reply of 0, which means that the expiry wasn’t set. It wasn’t set because our new expiry is greater than the current expiry. This is working exactly as expected.

Let’s now set an expiry that’s less than the existing expiry:

EXPIRE user 60 LT

Result:

(integer) 1

This time it worked. We can now use other commands, such as TTL to check the current time to live:

TTL user

Result:

(integer) 55