Set an Expiry on an Existing Redis Key Only When the Key Doesn’t Already Have an Expiry

When setting an expiry for an existing key in Redis, we now have the option to set the expiry only if the key doesn’t already have an expiry. That’s because Redis 7.0.0 introduced some new options that allows us to do this and other things.

In this case, we can use the NX option when setting the expiry to specify that the expiry should only be set if the key doesn’t already have an expiry. We can use this option on commands such as EXPIRE, EXPIREAT, PEXPIRE, and PEXPIREAT.

Example

Suppose we have a key called user with no associated expiry:

TTL user

Result:

(integer) -1

Running the TTL command against this key returns -1, which means the key exists but it has no associated expiry.

We can now use a command such as EXPIRE to set an expiry against that key. And we can use the NX option to make sure the expiry is set only if the key doesn’t already have a timeout:

EXPIRE user 3600 NX

Result:

(integer) 1

An integer reply of 1 means that the timeout was set.

We can verify this by running TTL again:

TTL user

Result:

(integer) 3565

This time it returns the current time to live of the key.

Now let’s try using the same method to reset the expiry of the same key:

EXPIRE user 60 NX

Result:

(integer) 0

This time we get an integer reply of 0, which means that nothing was updated – the expiry wasn’t reset. We can verify this by running TTL again:

TTL user

Result:

(integer) 3430

The key still has 3430 seconds before it expires, therefore it wasn’t reduced to 60 seconds like we tried to do here.

The NX option can also be applied to the SET command, so that the key is set only if it doesn’t already exist. The SET command also allows us to set a timeout for the key if required.