Expire sessions
Session and authentication state
Redis · Command
Sets a relative expiration timeout, in seconds, on a key. When the timeout elapses, Redis automatically deletes the key.
EXPIRE assigns a relative timeout, in seconds, to an existing key. Redis automatically removes the key after the timeout; calling EXPIRE again replaces the current timeout, while conditional options can restrict when the replacement occurs.
EXPIRE key seconds [NX | XX | GT | LT]| Name | Type | Description |
|---|---|---|
key | key | The key whose expiration should be set. |
seconds | integer | The time to live, in seconds. |
condition | enum | Optional condition: NX, XX, GT, or LT. |
An integer reply: 1 if the timeout was set, or 0 if the key does not exist or the requested condition is not satisfied.
SET session:123 user-42
EXPIRE session:123 300 NX
TTL session:123Creates a five-minute cache entry only when the key has no existing expiration, then checks its remaining lifetime.
Session and authentication state
Cached API responses or computed results
Temporary locks or coordination markers
EXPIRE takes a key and a relative lifetime in seconds, then returns 1 when the timeout is set or 0 when it is not. A missing key therefore produces 0.
Follow-up: How would you apply a timeout only when the key has none? Use the NX option: EXPIRE key seconds NX.
A later EXPIRE normally replaces the key's existing timeout with the new number of seconds. NX, XX, GT, and LT constrain whether that replacement is allowed.
Follow-up: Which option updates only a longer existing timeout? GT permits the change only when the new timeout is greater than the current one.
The timeout is measured in seconds, but Redis expiration resolution is one millisecond. Redis also preserves expiration information across persistence and replication.
Follow-up: Which commands provide millisecond-based expiration and inspection? PEXPIRE sets milliseconds, while PTTL reports the remaining lifetime in milliseconds.
EXPIREATEXPIRETIMEPEXPIREPERSISTPTTLSETTTL