0
0
Redisquery~20 mins

SETNX for set-if-not-exists in Redis - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
SETNX Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What 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?
Redis
SETNX mykey 10
SETNX mykey 20
GET mykey
Anil
B"20"
C"10"
DError: key does not exist
Attempts:
2 left
💡 Hint
SETNX sets the key only if it does not exist.
🧠 Conceptual
intermediate
1:30remaining
What 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?
A0
B1
Cnil
DError
Attempts:
2 left
💡 Hint
SETNX returns 1 if it sets the key, 0 otherwise.
📝 Syntax
advanced
1:30remaining
Which 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.
ASET user:1 active XX
BSET user:1 active NX
CSETNX user:1 active
DSET user:1 active IFNOTEXISTS
Attempts:
2 left
💡 Hint
SETNX is a dedicated command for set-if-not-exists.
optimization
advanced
2:00remaining
How 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?
A
SETNX lock 1
EXPIRE lock 10
BSET lock 1 EX 10
CSETNX lock 1 EX 10
DSET lock 1 NX EX 10
Attempts:
2 left
💡 Hint
Use the SET command with NX and EX options together.
🔧 Debug
expert
2:30remaining
Why 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?
ABecause SETNX and EXPIRE are not atomic together, a crash between calls can leave key without expiration
BBecause EXPIRE command is invalid inside Lua scripts
CBecause KEYS and ARGV are not accessible in Lua scripts
DBecause SETNX returns a string, not a number, causing the if condition to fail
Attempts:
2 left
💡 Hint
Consider atomicity of multiple commands in Lua scripts.