4 Ways to Return a Key’s Expiry in Redis

There are several ways to return a key’s expiry in Redis. The method used depends on how we want the expiry to be returned.

We can use the TTL command to return the timeout in seconds. We can alternatively use the PTTL command to return it in milliseconds. Another way to do it is to use the EXPIRETIME which returns the absolute Unix timestamp of the key in seconds, or the PEXPIRETIME command which returns the absolute Unix timestamp of the key in milliseconds.

The TTL Command

Suppose we set the following key with an expiry:

SET lastname "Burr" EX 60

Result:

OK

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

TTL lastname

Result:

(integer) 54

The PTTL Command

Here it is using the PTTL command:

PTTL lastname

Result:

(integer) 26752

The EXPIRETIME Command

Here it is using the EXPIRETIME command, which returns the absolute Unix timestamp of the key in seconds:

EXPIRETIME lastname

Result:

(integer) 1657596158

The PEXPIRETIME Command

Here it is using the PEXPIRETIME command, which returns the absolute Unix timestamp of the key in milliseconds:

PEXPIRETIME lastname

Result:

(integer) 1657596157971

When the Key has Already Expired

If the key has already expired, or if it doesn’t exist, the above commands return an integer reply of -2.

Here’s an example of using TTL on the same key after it has expired:

TTL lastname

Result:

(integer) -2

When the Key has No Expiry

If the key exists but it doesn’t have an associated timeout, the above commands return an integer reply of -1.

Let’s create the key again, but this time with no expiry:

SET lastname "Burr"

Result:

OK

Now let’s try to find its timeout:

TTL lastname

Result:

(integer) -1

We get an integer reply of -1 as expected.