SETNX(3valkey)

πŸ“¦
version 9.0.6 Β· 2 versions
, in fedora 44

πŸ’– NAME πŸ’–

setnx β€” set the string value of a key, but like… only if that key doesn't exist yet. it's giving "no takebacks, first come first served" 🫢


✨ SYNOPSIS ✨

SETNX key value

🌸 DESCRIPTION 🌸

okay so here's the tea: SETNX sets key to hold the string value if key does not exist. When it does actually set it, it's literally identical to SET. But if key already holds a value? bestie, nothing happens. no operation, no drama, we move on. πŸ’…

and yes, SETNX is short for "SET if Not eXists" β€” say it with me now, iykyk ✨

πŸŽ€ Alternative πŸŽ€

you can also just use SET with the NX argument. same vibe, different font. πŸ’œ


πŸ’Œ REPLY πŸ’Œ

you're getting one of these two, no in-between:


⚑ COMPLEXITY ⚑

O(1) β€” constant time, she's fast, she's efficient, she's iconic. πŸ”₯


πŸ‘‘ ACL CATEGORIES πŸ‘‘

@fast @string @write


πŸ“œ HISTORY πŸ“œ

  • Available since: 1.0.0 β€” an OG, a legend, main character energy since day one. ⭐

🌈 EXAMPLES 🌈

127.0.0.1:6379> SETNX mykey "Hello"
(integer) 1
127.0.0.1:6379> SETNX mykey "World"
(integer) 0
127.0.0.1:6379> GET mykey
"Hello"

see how the second one got hit with that 0? the key was already taken, bestie. "Hello" stays winning. 😌

πŸ” Design pattern: Locking with SETNX πŸ”

before we go any further, some housekeeping, and it's important so listen up:

  1. this pattern is discouraged in favor of valkey-distlock(7) the Redlock algorithm, which is only a bit more complex to implement but offers better guarantees and is fault tolerant. so like, do that one instead, fr fr.
  2. we're documenting the old pattern anyway because certain existing implementations link to this page as a reference. plus it's a genuinely interesting example of how Valkey commands can be used in order to mount programming primitives. 🧚
  3. anyway, even assuming a single-instance locking primitive, starting with 2.6.12 it's possible to create a much simpler locking primitive, equivalent to the one discussed here, using the SET command to acquire the lock, and a simple Lua script to release the lock. that pattern is documented in the SET command page. πŸ’œ

that said β€” SETNX can be used, and was historically used, as a locking primitive. for example, to acquire the lock of the key foo, the client could try the following:

SETNX lock.foo <current Unix time + lock timeout + 1>

if SETNX returns 1 the client acquired the lock, setting the lock.foo key to the Unix time at which the lock should no longer be considered valid. the client will later use DEL lock.foo in order to release the lock. slay. ✨

if SETNX returns 0 the key is already locked by some other client. we can either return to the caller if it's a non blocking lock, or enter a loop retrying to hold the lock until we succeed or some kind of timeout expires. πŸŒ€

πŸ’€ Handling deadlocks πŸ’€

in the above locking algorithm there is a problem: what happens if a client fails, crashes, or is otherwise not able to release the lock? 😭 it's possible to detect this condition because the lock key contains a UNIX timestamp. if such a timestamp is equal to the current Unix time the lock is no longer valid.

when this happens we can't just call DEL against the key to remove the lock and then try to issue a SETNX, as there is a race condition here, when multiple clients detected an expired lock and are trying to release it. and race conditions are, like, the villain of this story.

  • C1 and C2 read lock.foo to check the timestamp, because they both received 0 after executing SETNX, as the lock is still held by C3 that crashed after holding the lock.
  • C1 sends DEL lock.foo
  • C1 sends SETNX lock.foo and it succeeds
  • C2 sends DEL lock.foo
  • C2 sends SETNX lock.foo and it succeeds
  • ERROR: both C1 and C2 acquired the lock because of the race condition. πŸ’€

fortunately, it's possible to avoid this issue using the following algorithm. let's see how C4, our sane client, uses the good algorithm:

  • C4 sends SETNX lock.foo in order to acquire the lock
  • the crashed client C3 still holds it, so Valkey will reply with 0 to C4.
  • C4 sends GET lock.foo to check if the lock expired. if it is not, it will sleep for some time and retry from the start.
  • instead, if the lock is expired because the Unix time at lock.foo is older than the current Unix time, C4 tries to perform:
GETSET lock.foo <current Unix timestamp + lock timeout + 1>
  • because of the GETSET semantic, C4 can check if the old value stored at key is still an expired timestamp. if it is, the lock was acquired. πŸ‘‘
  • if another client, for instance C5, was faster than C4 and acquired the lock with the GETSET operation, the C4 GETSET operation will return a non expired timestamp. C4 will simply restart from the first step. note that even if C4 set the key a bit a few seconds in the future this is not a problem. πŸ¦‹

in order to make this locking algorithm more robust, a client holding a lock should always check the timeout didn't expire before unlocking the key with DEL because client failures can be complex, not just crashing but also blocking a lot of time against some operations and trying to issue DEL after a lot of time (when the LOCK is already held by another client). 🫢


πŸ‘€ SEE ALSO πŸ‘€

append(3valkey), decr(3valkey), decrby(3valkey), delifeq(3valkey), get(3valkey), getdel(3valkey), getex(3valkey), getrange(3valkey), getset(3valkey), incr(3valkey), incrby(3valkey), incrbyfloat(3valkey), lcs(3valkey), mget(3valkey), mset(3valkey), msetnx(3valkey), psetex(3valkey), set(3valkey), setex(3valkey), setrange(3valkey), strlen(3valkey), substr(3valkey)


and that's the whole page, bestie!! πŸŽ€ this was SETNX(3valkey) from the Valkey Command Manual, version 9.0.0, dated 2025-10-21. go forth and set-if-not-exists responsibly, and remember: if it already exists, it's not your key to set. periodt. πŸ’…βœ¨πŸ’–

πŸ“¦ where this page comes from