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

Redis 7.0.0 introduced some potentially useful options for setting timeouts on keys. One of these is the GT option, which allows us to set the expiry only if the new expiry is greater than the existing one.

The GT option is available for commands such as EXPIRE, EXPIREAT, PEXPIRE, and PEXPIREAT.

Example

Suppose we set a key with the following expiry:

SET user "Barney" EX 3600

Result:

OK

This key has an expiry of 3600 seconds.

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

EXPIRE user 60 GT

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 less than the current expiry. This is working exactly as expected.

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

EXPIRE user 4600 GT

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) 4563