Atomic SET if not exists

Difficulty: Intermediate

Question

What does `SET key value NX` do, and how do you use it correctly to build a distributed lock or an idempotency check?

Answer

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.

Why atomicity matters

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.

Building a lock the right way

  1. Acquire: 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.
  2. Do the work within the TTL.
  3. Release safely: delete the key only if it still holds your token. This must be atomic, so it is done in a small Lua script. A plain DEL could delete a lock that expired and was re-acquired by someone else.
  4. Retry with backoff and jitter if acquisition fails.

Limits of a single-node lock and Redlock

  • If the owner pauses (a long GC, a slow network call) past the TTL, the lock expires and a second client can enter. The first client then resumes believing it still holds the lock.
  • With asynchronous replication, a primary can grant a lock, fail over before replicating it, and the new primary grants it again.
  • Redlock acquires the lock on a majority of N independent Redis primaries (typically 5) to survive single-node failure. Martin Kleppmann's well-known critique argues it is still unsafe under clock jumps and process pauses, and recommends fencing tokens: a monotonically increasing number checked by the storage system itself.

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.

Other uses of NX

  • Idempotency keys. A payment webhook from a gateway like Razorpay may be delivered more than once. SET webhook:pay_Nx81 1 NX EX 86400 lets only the first delivery proceed.
  • Cache stampede protection. Only the request that wins SET rebuild:product:991 1 NX EX 10 recomputes an expired cache entry.
  • First-write-wins registration, such as claiming a coupon code.

Since Redis 7.0 you can also combine NX with GET to learn the existing value in the same call when the set fails.

Two workers racing for the same lock. Only one SET NX succeeds; the owner releases with a token check.
  1. Worker A → Redis: SET lock:o991 tokA NX PX 30000
  2. Redis → Worker A: OK (lock acquired)
  3. Worker B → Redis: SET lock:o991 tokB NX PX 30000
  4. Redis → Worker B: nil (already held)
  5. Worker A → Redis: Lua: if value is tokA then DEL
  6. Redis → Worker A: 1 (released)

Code examples

Lock with safe release (Node.js, ioredis)

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.

Idempotent webhook handling

# 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.

Key points

  • SET NX writes only if the key is absent and is atomic; returns OK or nil
  • Always pair NX with EX/PX in one command; SETNX plus EXPIRE can leave a stuck lock
  • Store a random token and release with a compare-and-delete Lua script
  • Single-node locks can fail under long pauses or failover; use fencing for correctness
  • Also used for idempotency keys and cache stampede protection

Common follow-up questions

  • Why is DEL alone unsafe for releasing a lock?
  • What is Redlock and what are the main criticisms of it?
  • What is a fencing token and who checks it?
  • How would you extend a lock for a job that runs longer than expected?

Interview tips

  • Write the full command with a token and TTL; SET key value NX alone is an incomplete answer
  • Explain the release race and the Lua script without being asked
  • Mentioning the Redlock debate and fencing tokens marks you as senior-minded

Concepts covered

SET NX, Distributed lock, Lock token, Redlock, Idempotency key

More Redis & Caching questions