Learnitweb

Redis SET Command Options: NX and XX

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

OptionBehaviorUse Case
NXSets the key only if it does not existUse when you want to insert a new key safely
XXSets the key only if it already existsUse 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:

  1. First command created the key.
  2. Second command with NX did nothing (key already existed).
  3. 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

CommandMeaningExampleResult
SET key valueSet or overwrite valueSET a bAlways succeeds
SET key value NXSet only if key does not existSET a b NXCreates new key if absent
SET key value XXSet only if key existsSET a b XXUpdates only existing key
SET key value NX EX 10Create new key with 10s expirySET lock:1 busy NX EX 10Used 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.