Module A-1·20 min read

SET key value NX PX as the atomic lock primitive, UUID lock values to prevent accidental release, lock extension with conditional PEXPIRE, the critical GC-pause failure mode, and why distributed locks need fencing tokens.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

A-1 — Single-Instance Locking: SET NX PX and Lock Correctness

Who this module is for: You need to ensure only one process at a time executes a critical section — a payment deduction, a job processing step, a cache recompute. This module covers the correct Redis single-instance lock primitive, the mistakes that make naive implementations unsafe, and the fundamental limitation that requires fencing tokens for true correctness.


The Lock Primitive: SET NX PX

A Redis distributed lock uses a single key with three properties:

  1. Existence — the key exists means the lock is held
  2. Identity — the key's value identifies the lock holder (prevents accidental release)
  3. Expiry — the key has a TTL so it auto-releases if the holder crashes

The atomic primitive that satisfies all three in a single command:

SET lock:resource "lock-value" NX PX 30000
  • NX — only set if the key does Not eXist (acquire only if nobody holds the lock)
  • PX 30000 — expire in 30,000 milliseconds (auto-release if holder crashes)

Returns OK if the lock was acquired, nil if already held by another client.

Why this must be a single command: A non-atomic acquire would be:

text

Between EXISTS and SET, another client can acquire the lock. Between SET and EXPIRE, a crash leaves a permanent lock. The SET key value NX PX single command eliminates both races.


Lock Value: UUID for Identity

The lock value must uniquely identify the holder. Use a cryptographically random UUID:

typescript

Why identity matters: Without a unique value, any client can release any lock:

text

With a UUID, releasing the lock requires presenting the same UUID that was set:

typescript

The Lua script atomically checks that the current lock value matches before deleting — if the lock expired and was acquired by another client, the check fails and we do not release their lock.


Full Lock Implementation

typescript

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.