In Redis, the TTL command returns the remaining time to live of a given key, in seconds.
If the key doesn’t have a timeout, an integer reply of -1 is returned. If the key doesn’t exist, -2 is returned.
Redis also has a PTTL command, which works the same, but returns its result in milliseconds.
Syntax
The syntax goes like this:
TTL key
Where key is the key for which to get the time to live.
Example
Suppose we set a key with an expiry:
SET dinner "Cottage Pie" EX 86400
Result:
OK
Here, I used the EX argument of the SET command to set an expiry in seconds.
We can now use the TTL command to check the key’s time to live:
TTL dinner
Result:
(integer) 86352
We can see that the time to live is slightly lower than the timeout that we set. That’s because TTL returns the current time to live. Therefore, if we wait a minute or so and then run the command again, the TTL has decreased further:
TTL dinner
Result:
(integer) 86245
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 TTL 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 dinner
Result:
(integer) 1
Now let’s run the TTL command against that key again:
TTL dinner
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 dinner
Result:
(integer) 1
And now let’s try to run TTL against it:
TTL dinner
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.