SET with NX saves a value only if its key doesn’t exist yet. It’s how you claim something once, such as a username, without overwriting a claim that’s already there. This guide claims the username ana in Valkey®.
Type the commands at the valkey-cli prompt. To open it, run valkey-cli in a terminal.
Note: Every command and output on this page is real, run on Valkey 9.2 on an Apple silicon Mac with macOS 26.
Syntax
SET key value NX
key: the name to claim.value: what to save under it.NX: write only if the key doesn’t exist.
From the SET documentation (opens in a new tab).
Step 1: Claim the Name
SET username:ana "user-1" NX
OK
OK: the key didn’t exist, so Valkey saved it.
Step 2: Try to Claim It Again
SET username:ana "user-2" NX
(nil)
(nil): the name is taken, so nothing was written, and the first value stays:
GET username:ana
"user-1"

Clean Up
DEL username:ana
(integer) 1
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Checking with EXISTS first, then saving with SET | Another client can create the key between the two commands | Use SET … NX, which checks and saves in one step |
Reading (nil) as an error | Your app reports a failure | Treat (nil) as “already taken” |
FAQ
What about the SETNX command?
SETNX key value does the same job. The SET documentation (opens in a new tab) says SET’s options can replace it and that it may be removed in a future version, so use SET … NX.
Can SET NX also set an expiry?
Yes: add EX and a number of seconds, as in SET key value NX EX 60. The SET documentation uses this for a simple lock.
Conclusion
SET key value NX saves only when the key is free and replies (nil) when it isn’t, so the first claim always wins.
Related
- Valkey Tutorial — Part 4: Strings and Counters
- Valkey Tutorial — Part 2: Your First Valkey Commands with valkey-cli
Additional Resources
Valkey® is a registered trademark of LF Projects, LLC. Redis® is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with the Valkey project, LF Projects or Redis Ltd., and isn’t endorsed, supported or certified by them.
0 comments