Apply precise cache expiration
Session and cache entries need sub-second or exact millisecond lifetimes.
Redis · Module
Sets a key's expiration timeout in milliseconds. Optional NX, XX, GT, and LT modes conditionally control whether the timeout is applied.
PEXPIRE assigns a timeout to an existing key in milliseconds. Redis removes the key after the timeout elapses; optional mutually exclusive modes restrict setting the expiry based on whether an expiry exists or how the new timeout compares with the current one.
PEXPIRE key milliseconds [NX | XX | GT | LT]| Name | Type | Description |
|---|---|---|
key | key | Key whose timeout is modified. |
milliseconds | integer | Timeout duration, in milliseconds. |
mode | option | Optional mutually exclusive condition: NX, XX, GT, or LT. |
Integer reply: 1 if the timeout was set; 0 if it was not set, including when the key does not exist or an option condition fails.
SET session:42 "active"
PEXPIRE session:42 1500
PTTL session:42Stores a value, assigns a 1.5-second expiration, then reads the remaining lifetime in milliseconds.
Session and cache entries need sub-second or exact millisecond lifetimes.
A write should establish an expiry only if another operation has not already set one.
A refresh should extend or shorten an existing lifetime only under a chosen comparison.
PEXPIRE sets a key's time-to-live using milliseconds rather than seconds. It returns 1 when the timeout is applied and 0 when it is not, such as when the key does not exist.
Follow-up: How would you verify millisecond precision? Use PTTL after setting the timeout; it reports the remaining lifetime in milliseconds.
NX applies the timeout only if the key currently has no expiry, while XX requires an existing expiry. GT applies it only when the new timeout is greater than the current one, and LT requires it to be less.
Follow-up: What happens if these modes are combined? The options are mutually exclusive, so they must be supplied individually.
A positive timeout causes the key to expire after the specified duration. Redis can remove expired keys when accessed or through background expiration, so expiration-related events are not guaranteed to occur exactly when the TTL reaches zero.
Follow-up: What event accompanies a negative timeout? Redis deletes the key immediately and emits only a del event, rather than an expire event.
EXPIREPEXPIREATPEXPIRETIMEPTTLTTLSET