Upstash Documentation

SETEX

Set value with expiration.
2 min read
Warning

Prefer SET with the EX argument in new code: SET <key> <value> EX <seconds>.

Use SETEX to set a value together with a lifetime in seconds.

The value and the expiration are applied atomically, so the key never exists without an expiration; writing the value and expiring it in two commands leaves a window in which a failure makes the key permanent. A lifetime of zero or less returns an error.

Use PSETEX for millisecond precision. SET with EX or PX does the same thing and additionally supports conditions and reading the previous value.

Syntax#

Arguments#

ArgumentRequiredRepeatableDescription
<key>YesNoRedis key targeted by the command.
<seconds>YesNoLifetime in seconds.
<value>YesNoString value to store.

Response#

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

ProtocolReply
RESP2Simple string OK
RESP3Simple string OK
Note

Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.

Examples#

TCP examples use the TLS REDIS_URL from the Upstash console. REST examples use UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN.

Redis CLI
@upstash/redis
upstash_redis
ioredis
node-redis
redis-py
go-redis
jedis
redis-rs