Cache lifetime monitoring
Inspect how long a cached value can remain before Redis removes it.
Redis · Command
Returns a key's remaining expiration time in seconds. It distinguishes missing keys from existing keys that have no expiration.
TTL inspects a key's expiration and returns the number of seconds until Redis removes it. It returns special negative values when the key is missing or exists without an expiration, allowing clients to distinguish those states.
TTL key| Name | Type | Description |
|---|---|---|
key | key | The key whose remaining expiration time should be inspected. |
An integer number of seconds remaining; -1 if the key exists without an expiration; -2 if the key does not exist.
SET session:123 active EX 60
TTL session:123
Stores a key with a 60-second expiration, then reports its remaining lifetime in seconds.
Inspect how long a cached value can remain before Redis removes it.
Check whether a session or token key is nearing expiration.
Identify whether a key is absent, persistent, or configured to expire.
TTL returns the remaining time to live for a key in seconds. It is an introspection command, so it checks expiration without changing the key.
Follow-up: How would you obtain finer resolution? Use PTTL, which reports the corresponding expiration information in milliseconds.
TTL returns -2 when the key does not exist and -1 when the key exists but has no expiration. A nonnegative result is the remaining lifetime in seconds.
Follow-up: How can a key acquire an expiration? Set one with EXPIRE, or write it using an expiration option such as SET with EX.
Use TTL when second-level precision is sufficient for checking cache or session lifetime. For millisecond resolution, use PTTL instead.
Follow-up: What should a client do when TTL returns -2? Treat the value as absent and avoid assuming that an expiration is merely near.
EXPIREPTTLSET