In this lecture, we will explore two important conditional options available with the SET
command — NX and XX.
These options allow you to control when a key should be created or updated, based on whether it already exists in the Redis database.
1. Basic SET Behavior
Before we dive into the options, let’s recap the normal SET
command behavior.
Example:
SET a "A"
This command creates a key a
with value "A"
.
If you execute:
SET a "B"
The new value "B"
simply overwrites the existing value of "A"
.
You can verify it with:
GET a
Output:
"B"
By default, Redis doesn’t care whether a key already exists or not — it just sets or replaces it.
However, there are many cases where you don’t want Redis to overwrite existing data accidentally.
That’s where the NX
and XX
options come in.
2. Understanding NX and XX Options
The Redis SET
command provides two special conditional flags:
- NX — Set the key only if it does NOT already exist.
- XX — Set the key only if it already exists.
Let’s understand both with examples.
3. Using NX (Set if Not Exists)
Syntax:
SET key value NX
This command will set the key only if it does not already exist in Redis.
If the key already exists, the command does nothing and returns nil
.
Example 1: Key does not exist
FLUSHDB SET a "B" NX
Output:
OK
Since key a
did not exist earlier, Redis creates it successfully.
If you now check:
GET a
Output:
"B"
Example 2: Key already exists
Now, try to set a new value with NX again:
SET a "C" NX
Output:
(nil)
Redis does not update the value because the key a
already exists.
Verifying:
GET a
Output:
"B"
The value remains unchanged.
In short:NX
prevents accidental overwrites. It’s very useful when you want to insert data only if it’s new — similar to an “INSERT IF NOT EXISTS” in SQL.
4. Using XX (Set if Exists)
Syntax:
SET key value XX
This command sets the key only if it already exists in Redis.
If the key does not exist, Redis does nothing and returns nil
.
Example 1: Key does not exist
FLUSHDB SET a "B" XX
Output:
(nil)
Since the key a
doesn’t exist yet, Redis does not create it.
Example 2: Key already exists
Let’s first create a key:
SET a "B"
Now, use the XX
flag:
SET a "C" XX
Output:
OK
Redis updates the key because it already exists.
Check:
GET a
Output:
"C"
In short:XX
ensures that you only update existing data, preventing accidental creation of new keys.
5. Comparison of NX and XX
Option | Behavior | Use Case |
---|---|---|
NX | Sets the key only if it does not exist | Use when you want to insert a new key safely |
XX | Sets the key only if it already exists | Use when you want to update only existing data |
6. Combined Example
Let’s see both options in action together:
FLUSHDB SET a "B" NX SET a "C" NX # ignored since key already exists SET a "D" XX # updates since key exists GET a
Output:
"D"
Here’s what happened:
- First command created the key.
- Second command with NX did nothing (key already existed).
- Third command with XX updated it because the key existed.
7. Practical Use Cases
a. Preventing Duplicate Records
If you’re caching user profiles or session tokens, you might not want to overwrite an existing user’s data accidentally.
In such cases:
SET user:1001 "Samir" NX
This ensures that once the user record is created, subsequent inserts won’t overwrite it unless explicitly allowed.
b. Updating Only Existing Cache Entries
If your application only wants to refresh data that already exists:
SET product:101 "updated-info" XX
This ensures that you don’t accidentally create unnecessary new cache entries.
c. Distributed Lock Implementation
A very common use of the NX
option is in distributed locking using Redis:
SET lock:resource1 "locked" NX EX 10
This sets a lock key only if it doesn’t exist (NX), and it automatically expires in 10 seconds (EX).
This is the foundation of Redis-based distributed locks.
8. Summary
Command | Meaning | Example | Result |
---|---|---|---|
SET key value | Set or overwrite value | SET a b | Always succeeds |
SET key value NX | Set only if key does not exist | SET a b NX | Creates new key if absent |
SET key value XX | Set only if key exists | SET a b XX | Updates only existing key |
SET key value NX EX 10 | Create new key with 10s expiry | SET lock:1 busy NX EX 10 | Used in locking mechanisms |
9. Conclusion
The NX
and XX
flags in Redis provide fine-grained control over how and when keys are created or modified.
They are essential for scenarios like:
- Conditional key creation
- Avoiding accidental overwrites
- Safely updating existing data
- Implementing distributed locks
By mastering these options, you can make your Redis operations more predictable, safe, and application-friendly — especially in distributed environments where multiple services may interact with the same Redis database.