Set an Expiry on an Existing Key in Redis, But Only When the Key Already Has an Expiry

When setting a timeout for a key in Redis, we have the option of setting it only if the key already has an expiry. So, if the key doesn’t already have an associated timeout, the new timeout won’t apply. The new timeout will only apply if the key already has an existing timeout. In such cases the expiry will be reset to the new expiry.

We can do this with the XX option of the EXPIRE command. We can also use the XX option on commands such as EXPIREAT, PEXPIRE, and PEXPIREAT.

The XX option was introduced in Redis 7.0.0.

Example

Suppose we set the following key with an expiry:

SET user "Homer" EX 60

Result:

OK

We can use the TTL command to check the current time to live:

TTL user

Result:

(integer) 54

Let’s now use the EXPIRE command with the XX option to reset the key’s TTL:

EXPIRE user 3600 XX

Result:

(integer) 1

An integer reply of 1 means that the timeout was successfully reset.

Let’s now check the current time to live again:

TTL user

Result:

(integer) 3524

When the Key Doesn’t Have an Existing Timeout

Let’s remove the timeout so that the key no longer has an expiry. We can do this with the PERSIST command:

PERSIST user

Result:

(integer) 1

Now when we use the TTL command, we see that the key doesn’t have an associated timeout:

TTL user

Result:

(integer) -1

An integer reply of -1 indicates that the key doesn’t have an expiry.

Now let’s use the EXPIRE command with the XX option to try to set an expiry again:

EXPIRE user 3600 XX

Result:

(integer) 0

An integer reply of 0 means that the expiry wasn’t set.

We can further verify this with the TTL command:

TTL user

Result:

(integer) -1