Difficulty: Intermediate
What does `SET key value NX` do, and how do you use it correctly to build a distributed lock or an idempotency check?
SET key value NX writes the key only if it does not already exist, and it does the check and the write as one atomic operation. It returns OK when it created the key and nil when the key was already there. Combined with an expiry (SET lock:order:991 <token> NX PX 30000), it is the standard building block for a single-instance distributed lock and for idempotency keys.
The naive version is two commands: EXISTS key, then SET key if it was missing. Between those two calls another client can do the same check, and both believe they won. Redis executes each command on a single thread, so SET ... NX cannot be interleaved with another client's command. Exactly one caller gets OK.
The older SETNX command does the same check but cannot set a TTL. If the process crashes after SETNX and before EXPIRE, the lock is stuck forever. Since Redis 2.6.12, SET accepts NX together with EX/PX, so always use that form.
SET lock:resource <random-token> NX PX 30000. The random token (a UUID) identifies the owner; the TTL guarantees the lock eventually frees if the owner dies.DEL could delete a lock that expired and was re-acquired by someone else.Practical rule: use Redis locks for efficiency (avoid doing the same work twice). For correctness-critical decisions like moving money, rely on database constraints or fencing.
SET webhook:pay_Nx81 1 NX EX 86400 lets only the first delivery proceed.SET rebuild:product:991 1 NX EX 10 recomputes an expired cache entry.Since Redis 7.0 you can also combine NX with GET to learn the existing value in the same call when the set fails.
import Redis from 'ioredis';
import { randomUUID } from 'node:crypto';
const redis = new Redis();
const RELEASE = `
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0`;
export async function withLock(resource, ttlMs, fn) {
const key = `lock:${resource}`;
const token = randomUUID();
// Atomic: set only if absent, with an expiry
const ok = await redis.set(key, token, 'PX', ttlMs, 'NX');
if (ok !== 'OK') throw new Error('Resource busy, retry later');
try {
return await fn();
} finally {
// Delete only if we still own it
await redis.eval(RELEASE, 1, key, token);
}
}
// await withLock('order:991', 30000, () => settleOrder(991));
The random token prevents one worker from deleting a lock that has since been taken by another. The Lua script makes check-and-delete atomic.
# First delivery
SET webhook:pay_Nx81 processing NX EX 86400
# Duplicate delivery a few seconds later
SET webhook:pay_Nx81 processing NX EX 86400
The second call returns nil, so the handler can acknowledge the duplicate without processing the payment again.
SET NX, Distributed lock, Lock token, Redlock, Idempotency key