Read cache freshness
A cache client needs to expose or calculate how long a cached entry remains valid with millisecond precision.
Redis · Module
Returns the remaining expiration time of a key in milliseconds. It distinguishes an existing key without expiration (-1) from a missing key (-2).
PTTL takes one key and reports how long that key will remain before expiration, measured in milliseconds. A nonnegative result is the remaining lifetime; -1 distinguishes an existing key without expiration from -2, which means the key does not exist.
PTTL key| Name | Type | Description |
|---|---|---|
key | key | The name of the key whose remaining expiration should be returned. |
An integer: the remaining TTL in milliseconds; -1 if the key exists without an associated expiration; or -2 if the key does not exist.
SET session:42 "user-123" PX 30000
PTTL session:42Stores a session with a 30-second millisecond expiration, then reads its remaining lifetime.
A cache client needs to expose or calculate how long a cached entry remains valid with millisecond precision.
A rate limiter needs the remaining lockout interval to tell a client when retrying may be reasonable.
An operations check verifies whether a key has an expiration and observes its remaining duration.
PTTL returns the remaining time to live for a key in milliseconds. Unlike TTL, which reports seconds, PTTL uses millisecond units.
Follow-up: How would you distinguish a missing key from a persistent key? Check for -2 for a missing key and -1 for an existing key without an expiration.
The command accepts one required argument: the key whose expiration is being inspected. Its time complexity is O(1), making the lookup constant time.
Follow-up: What should a caller do when the result is nonnegative? Treat it as the remaining lifetime in milliseconds, while remembering that it can decrease immediately after the read.
PTTL returns an integer reply: a nonnegative TTL in milliseconds, -1 when the key exists without an expiration, or -2 when the key does not exist. These meanings apply to both RESP2 and RESP3.
Follow-up: Which command can establish a millisecond expiration before checking it? PEXPIRE sets a relative timeout with millisecond precision.
TTLEXPIREPEXPIREPEXPIREATPERSIST