Upstash Documentation

SETNX

Set value if key doesn't exist.
2 min read
Warning

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

Use SETNX to set a value only if the key does not already exist.

The reply is 1 when the key was created and 0 when it was already there and nothing was written. The check and the write are atomic, so exactly one of several racing clients succeeds.

That makes it the classic lock primitive, but on its own it is an incomplete one: a client that fails after acquiring leaves the key behind forever. Prefer SET key value NX EX <ttl>, which claims the key and attaches an expiration in the same step, and release the lock with DELEX so you only delete it while you still own it.

Syntax#

Arguments#

ArgumentRequiredRepeatableDescription
<key>YesNoRedis key targeted by the command.
<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
RESP2Integer: 1 if the key was set, 0 if it already exists
RESP3Integer: 1 if the key was set, 0 if it already exists
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