w3resource

Redis TTL

Redis TTL Command

Redis TTL command is used to get the remaining time of key expiry in seconds.

Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.

Here are some common uses and scenarios for the "TTL" command:

  • Cache Management: Check the expiration status of cached data.
  • Session Handling: Determine the remaining session timeout.
  • Dynamic TTL Adjustment: Adjust TTL based on business logic or user interactions.
  • Rate Limiting: Query TTL for rate limiting and access control.

Syntax:

TTL KEY_NAME

Available since

1.0.0.

Return Value

Integer value TTL in milliseconds, or a negative value

  • TTL in milliseconds..
  • -1, if the key does not have expiry timeout.
  • -2, if the key does not exist.

Return Value Type

Integer

Example: Redis TTL

First, create a key in redis and set some value in it.

Now set the expiry of the key and after that just check the remaining expiry time.

127.0.0.1:6379[1]> SET key "Apple"
OK
127.0.0.1:6379[1]> EXPIRE key 20
(integer) 1
127.0.0.1:6379[1]> TTL key
(integer) 16

Example: Redis TTL another example

First, create a key in redis and set some value in it.

Now set the expiry of the key, and after that just check the remaining expiry time.

127.0.0.1:6379[1]> SET key "PHP"
OK
127.0.0.1:6379[1]> EXPIRE key 10
(integer) 1
127.0.0.1:6379[1]> TTL key
(integer) 6
127.0.0.1:6379[1]> TTL key
(integer) -2
127.0.0.1:6379[1]> GET key
(nil)

Previous: SORT
Next: TYPE



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/redis/redis-ttl-key.php