Redis PTTL Command Explained

In Redis, the PTTL command returns the remaining time to live of a given key, in milliseconds.

If the key doesn’t have a timeout, an integer reply of -1 is returned. If the key doesn’t exist, -2 is returned.

PTTL works the same as the TTL command, except that it returns the result in milliseconds instead of seconds.

Syntax

The syntax goes like this:

PTTL key

Where key is the key for which to get the time to live.

Example

Suppose we set a key with an expiry:

SET beverage "Water" PX 86400000

Result:

OK

Here, I used the PX argument of the SET command to set an expiry in milliseconds.

We can now use the PTTL command to check the key’s time to live:

PTTL beverage

Result:

(integer) 86376856

We can see that the time to live is slightly lower than the timeout that we set. That’s because PTTL returns the current time to live. Therefore, if we wait a minute or so and then run the command again, the time to live has decreased further:

PTTL beverage

Result:

(integer) 86330093

Non-Volatile Keys

In Redis, a key with a timeout is considered volatile. A key without a timeout is considered non-volatile. When we run the PTTL command against a non-volatile key (i.e. a key without a timeout), we get an integer reply of -1.

To test this, let’s remove the time to live from our key:

PERSIST beverage

Result:

(integer) 1

Now let’s run the PTTL command against that key again:

PTTL beverage

Result:

(integer) -1

We get -1 as expected.

Non-Existent Keys

If the key doesn’t exist, an integer reply of -2 is returned (although in Redis 2.6 and below, it returns -1).

To test this, let’s delete the key:

DEL beverage

Result:

(integer) 1

And now let’s try to run PTTL against it:

PTTL beverage

Result:

(integer) -2

As expected, we get an integer reply of -2.

As mentioned, in Redis 2.6 and below, it returns -1 in such cases.