Conditional initialization
Prevent a one-time initialization value from being overwritten when multiple clients race to create the same key.
Redis · Module
Sets a string value only when a key does not already exist. It returns 1 when the key is created and 0 when no write occurs; SET with NX is the recommended replacement for new code.
SETNX attempts to store a string value only when the named key is absent. It performs no write when the key already exists and reports whether the write occurred with an integer result.
SETNX key value| Name | Type | Description |
|---|---|---|
key | key | The name of the key. |
value | string | The value to set, only if the key does not already exist. |
Integer reply: 1 if the key was set; 0 if the key was not set.
SETNX mykey "Hello"
SETNX mykey "World"
GET mykeyThe first command creates the key and returns 1; the second does nothing and returns 0, so GET still returns Hello.
Prevent a one-time initialization value from being overwritten when multiple clients race to create the same key.
Claim a key as a basic coordination marker so only the client receiving 1 proceeds.
Use the return code to distinguish the first insertion from later duplicate attempts.
SETNX stores the supplied string only if the key does not exist. It returns 1 when it creates the key and 0 when the key already exists.
Follow-up: How should new code express the same condition? Use SET with the NX option, which is the documented replacement for SETNX.
The command takes exactly a key and a value: SETNX key value. The value is written only when the key is absent; an existing key is left unchanged.
Follow-up: What happens if the existing key contains a different data type? SETNX performs a presence check and does not replace the existing value.
A successful result of 1 indicates that the client acquired the lock key; a result of 0 means another client already holds it. The documented pattern releases the lock with DEL.
Follow-up: What limitation should be considered for a production lock? A robust design needs an expiration and ownership-safe release strategy rather than relying only on a bare SETNX key.
SETGETDEL