Redis PERSIST Command Explained

The Redis PERSIST command removes any existing timeout on a given key. It returns an integer reply of 1 if the timeout was removed, or 0 if the key doesn’t exist or doesn’t have an associated timeout.

Syntax

The syntax goes like this:

PERSIST key

Where key is the key for which to remove the expiry.

Example

Suppose we set a key with an expiry:

SET lunch "Salad" EX 86400

Result:

OK

Here, I used the EX argument of the SET command to set an expiry in seconds.

Now let’s check the key’s time to live:

TTL lunch

Result:

(integer) 86349

There is still plenty of time before this key expires.

In Redis 7.0.0 and higher, we can also use the EXPIRETIME command to check the absolute Unix time that it will expire:

EXPIRETIME lunch

Result:

(integer) 1655961287

OK, now let’s use the PERSIST command to remove the expiry associated with the key:

PERSIST lunch

Result:

(integer) 1

We get an integer reply of 1, which means the expiry was removed.

Now when we use the TTL command, we get -1:

TTL lunch

Result:

(integer) -1

This means that the key exists, but doesn’t have an expiry.

When the Key Has No Expiry

If the key has no expiry, PERSIST returns 0.

To test this, let’s run PERSIST against the same key, now that we’ve removed its timeout:

PERSIST lunch

Result:

(integer) 0

As expected.

When the Key Doesn’t Exist

If the key doesn’t exist, PERSIST returns 0. To test this, let’s delete the key, and then run PERSIST against it.

Delete the key:

DEL lunch

Result:

(integer) 1

This means that the key was deleted.

Now let’s run PERSIST against it:

PERSIST lunch

Result:

(integer) 0

As expected, we get an integer reply of 0.