Expiring cache entries
Cache a serialized response with a bounded lifetime so stale data disappears automatically.
Redis · Command
SETEX stores a string at a key and gives it a timeout in seconds. It is deprecated in favor of SET with the EX option.
SETEX writes a string to the specified key and assigns an expiration measured in seconds. It replaces an existing value and is functionally the same as SET with the EX option; invalid seconds cause an error.
SETEX key seconds value| Name | Type | Description |
|---|---|---|
key | key | The name of the key. |
seconds | long | The time to live, in seconds. |
value | string | The value to set. |
Simple string reply: OK when the operation succeeds.
redis-cli SETEX cache:user:42 60 '{"name":"Ada"}'
redis-cli TTL cache:user:42
redis-cli GET cache:user:42Stores a JSON string for 60 seconds, then checks its remaining lifetime and reads the value.
Cache a serialized response with a bounded lifetime so stale data disappears automatically.
Store a short-lived token or session value without requiring a separate expiration command.
Set a safety timeout on a transient coordination key.
SETEX takes a key, a lifetime in seconds, and a string value. It sets the value and expiration together in one operation, with O(1) complexity.
Follow-up: How should new code express the same operation? Use SET key value EX seconds, which is the documented replacement.
The syntax is SETEX key seconds value. The seconds argument is the key's time to live, and the value is the string stored under the key.
Follow-up: What happens if seconds is invalid? Redis returns an error rather than applying the command.
An existing key is overwritten with the supplied string and receives the specified expiration. The command creates the key when it does not already exist.
Follow-up: How can the remaining lifetime be inspected? Use TTL on the key after SETEX.
SETTTLGETPSETEX