Video in progress
What do the NX, XX, EX and PX options of the SET command do?
NX means write only if the key doesn't exist, XX means write only if it does. EX sets a TTL in seconds, PX in milliseconds. They combine in one atomic command.
📖 Answer
SET lock:order:9 worker-1 NX PX 30000 # takes it if free, 30 s
SET config:theme dark XX # updates only an existing key
SET session:abc '{...}' EX 1800 GET # writes and returns the old value
The best-known use of NX is a simple lock and "only once" logic: for example, if the same payment webhook arrives twice, SET webhook:<id> 1 NX EX 86400 returns OK only the first time.
In old code you'll see SETNX plus a separate EXPIRE. That's dangerous: if the application crashes after SETNX, the EXPIRE never runs and the key stays forever. SET ... NX EX does both in a single atomic step.
In Java: redis.opsForValue().setIfAbsent(key, value, Duration.ofSeconds(30)).
Sign up to mark studied questions and save your progress.