Challenge - 5 Problems
SETNX Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediateWhat is the output of this Redis command sequence?
Consider the following Redis commands executed in order:
SETNX mykey 10
SETNX mykey 20
GET mykey
What will be the output of the GET command?
SETNX mykey 10
SETNX mykey 20
GET mykey
What will be the output of the GET command?
Redis
SETNX mykey 10 SETNX mykey 20 GET mykey
Attempts:
2 left
💡 Hint
SETNX sets the key only if it does not exist.
✗ Incorrect
The first SETNX sets 'mykey' to '10' because it does not exist yet. The second SETNX does nothing because 'mykey' already exists. So GET returns '10'.
🧠 Conceptual
intermediateWhat does the SETNX command return when the key already exists?
If you run SETNX on a key that already exists in Redis, what is the return value?
Attempts:
2 left
💡 Hint
SETNX returns 1 if it sets the key, 0 otherwise.
✗ Incorrect
SETNX returns 0 if the key already exists and it does not set the value.
📝 Syntax
advancedWhich of these is the correct syntax to set a key only if it does not exist in Redis?
Choose the correct Redis command syntax to set key 'user:1' to 'active' only if it does not exist.
Attempts:
2 left
💡 Hint
SETNX is a dedicated command for set-if-not-exists.
✗ Incorrect
SETNX key value sets the key only if it does not exist. The SET command with NX option is valid in newer Redis versions and is the preferred syntax here.
❓ optimization
advancedHow can you atomically set a key with expiration only if it does not exist?
You want to set key 'lock' with value '1' only if it does not exist, and have it expire after 10 seconds atomically. Which Redis command achieves this?
Attempts:
2 left
💡 Hint
Use the SET command with NX and EX options together.
✗ Incorrect
The SET command supports NX (set if not exists) and EX (expire seconds) options atomically. SETNX does not support expiration directly.
🔧 Debug
expertWhy does this Lua script using SETNX fail to set expiration correctly?
Given this Redis Lua script:
local set = redis.call('SETNX', KEYS[1], ARGV[1])
if set == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
return set
The script sometimes leaves the key without expiration. Why?
local set = redis.call('SETNX', KEYS[1], ARGV[1])
if set == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
return set
The script sometimes leaves the key without expiration. Why?
Attempts:
2 left
💡 Hint
Consider atomicity of multiple commands in Lua scripts.
✗ Incorrect
Although Lua scripts run atomically, if the script crashes or is interrupted between SETNX and EXPIRE calls, the key may be set without expiration. The two commands are separate calls.
