Reading — step 1 of 3
Conditional Writes
~1 min readString Commands
SET NX & XX — Conditional Writes
Redis SET supports flags that make writes conditional.
NX — Only If Not Exists
SET key value NX sets the key only if it doesn't already exist.
- Key doesn't exist → sets it, returns
+OK\r\n - Key exists → does nothing, returns
$-1\r\n(null)
This is how distributed locks work — SET lock_key owner NX EX 30 atomically acquires a lock.
XX — Only If Exists
SET key value XX sets the key only if it already exists.
- Key exists → updates it, returns
+OK\r\n - Key doesn't exist → does nothing, returns
$-1\r\n
Parsing Flags
Flags appear after the value: SET key value [NX|XX]. Parse the remaining arguments after key and value to detect flags. Flags are case-insensitive.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…