Skip to main content
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

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.
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.

Related topics

MSETNXHSETNX