Redis Distributed Lock Acquisition

Serialize critical sections across instances with a Redis lock using SET NX with expiry, token-checked release, and lease renewal.

TypescriptNodeData Integrity

Code

typescriptsnippet
52 lines
import { createClient } from 'redis';

const redis = createClient({ url: 'redis://127.0.0.1:6379' });
await redis.connect();

function randomToken() {
  return crypto.randomUUID();
}

async function acquireLock(key: string, ttlMs: number) {
  const token = randomToken();
  const ok = await redis.set('lock:' + key, token, { NX: true, PX: ttlMs });
  return ok ? token : null;
}

async function releaseLock(key: string, token: string) {
  const script = `
    if redis.call("GET", KEYS[1]) == ARGV[1] then
      return redis.call("DEL", KEYS[1])
    else
      return 0
    end
  `;
  return (await redis.eval(script, {
    keys: ['lock:' + key],
    arguments: [token],
  })) === 1;
}

async function withLock<T>(
  key: string, ttlMs: number, fn: () => Promise<T>,
): Promise<T | null> {
  const token = await acquireLock(key, ttlMs);
  if (token === null) return null;

  const renew = setInterval(() => {
    redis.expire('lock:' + key, ttlMs / 1000).catch(() => {});
  }, ttlMs / 3);

  try {
    return await fn();
  } finally {
    clearInterval(renew);
    await releaseLock(key, token);
  }
}

const result = await withLock('billing:nightly', 30_000, async () => {
  console.log('nightly billing started under lock');
  return { invoices: 42 };
});
console.log('lock result:', result?.invoices ?? 'busy');

How it works

Redis Distributed Lock Acquisition keeps everything in the functions randomToken, acquireLock, releaseLock and withLock.

Every asynchronous step is awaited, so rejections surface where the call happens. Reach for redis and what you get is createClient — that is the whole API contact area.

What comes back is a new object, not a reference to anything passed in.

What to watch for

  • Dependency check: redis — not built-in, must be present in the project.
  • crypto exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard token === null short-circuits the flow with an early return when its condition holds.

Using it

The primary signature is function randomToken()

The demo output is labeled (nightly billing started under lock, lock result:), so every printed line maps back to a specific operation.

Key statements

const result = await withLock('billing:nightly', 30_000, async () => {
  console.log('nightly billing started under lock');
  return { invoices: 42 };
});
redis.expire('lock:' + key, ttlMs / 1000).catch(() => {});
return (await redis.eval(script, {
  keys: ['lock:' + key],
  arguments: [token],
})) === 1;

Interactive Tools for This Topic

FAQ

Does `randomToken` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Which packages must be installed first?
Yes. The imports resolve to `redis`, which the package manager must provide.