A distributed lock prevents concurrent execution of a critical section across multiple processes or machines. Unlike a thread mutex, a distributed lock must tolerate network failures, process crashes, and clock skew. UUID v7 tokens used as lock values add self-describing timestamps to the standard pattern. See Idempotency Key for a related coordination primitive.
Redis-based lock with UUID v7 token
import { createClient } from 'redis';
import { v7 as uuidv7 } from 'uuid';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
interface LockResult {
acquired: boolean;
token: string | null;
}
// Acquire lock — UUID v7 token encodes acquisition time
async function acquireLock(resource: string, ttlMs: number): Promise<LockResult> {
const token = uuidv7(); // UUID v7 — timestamp = when lock was acquired
const key = `lock:${resource}`;
// SET key token NX PX ttlMs — atomic compare-and-set
const ok = await redis.set(key, token, { NX: true, PX: ttlMs });
return { acquired: ok === 'OK', token: ok === 'OK' ? token : null };
}
// Release lock — only the holder (matching token) can release
async function releaseLock(resource: string, token: string): Promise<boolean> {
const key = `lock:${resource}`;
// Lua script ensures atomic check-and-delete
const script = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
`;
const result = await redis.eval(script, { keys: [key], arguments: [token] });
return result === 1;
}
// Get lock age from UUID v7 token — no DB query needed
function getLockAgeMs(token: string): number {
const hex = token.replace(/-/g, '').slice(0, 12);
return Date.now() - parseInt(hex, 16);
}
Usage pattern
async function processOrder(orderId: string) {
const { acquired, token } = await acquireLock(`order:${orderId}`, 30_000);
if (!acquired || !token) {
throw new Error('Order is already being processed');
}
try {
// Critical section — only one process runs this at a time
await fulfillOrder(orderId);
} finally {
await releaseLock(`order:${orderId}`, token);
}
}
PostgreSQL advisory lock with UUID v7 correlation
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function withAdvisoryLock<T>(lockId: number, fn: () => Promise<T>): Promise<T> {
const client = await pool.connect();
const correlationId = uuidv7(); // UUID v7 — tracks when lock was acquired
try {
await client.query('SELECT pg_advisory_lock($1)', [lockId]);
console.log(`Lock ${lockId} acquired at ${new Date(
parseInt(correlationId.replace(/-/g, '').slice(0, 12), 16)
).toISOString()} [${correlationId}]`);
return await fn();
} finally {
await client.query('SELECT pg_advisory_unlock($1)', [lockId]);
client.release();
}
}
Lock audit log with UUID v7 range query
-- Find all locks acquired in the last 5 minutes using UUID v7 timestamps
SELECT token, resource, holder, acquired_at
FROM lock_audit
WHERE token > uuid_v7_from_timestamp(now() - interval '5 minutes')
ORDER BY token; -- UUID v7 sort = chronological acquisition order
Distributed lock properties
| Property | Description |
|---|---|
| Mutual exclusion | Only one holder at a time |
| Deadlock prevention | TTL-based expiry — UUID v7 timestamp enables self-expiry |
| Fencing token | UUID v7 token provides ordering for stale write detection |
| Audit trail | UUID v7 tokens in logs encode acquisition time |
Further reading
- Idempotency Key — Preventing Duplicate Operations
- UUID v7 for Audit Logging
- Write Skew — Concurrency Anomaly
- UUID v7 in Distributed Systems
- UUID in Redis — Keys, Streams, and Session IDs
Frequently asked questions
How does a distributed lock work?
A distributed lock uses an atomic compare-and-set operation on a shared store (Redis, DynamoDB, PostgreSQL advisory locks) to ensure only one holder succeeds. The lock holder receives a unique token; only the holder with that token can release the lock. Using UUID v7 as the token provides uniqueness plus an embedded timestamp — if the holder crashes, the lock expires based on the TTL, which can be derived from the UUID v7 token creation time. See Idempotency Key for a related pattern.
Why use UUID v7 as a distributed lock token instead of a random string?
UUID v7 tokens embed their acquisition timestamp. This enables: 1) TTL calculation without a separate acquired_at column — ageMs = Date.now() - extractMs(token). 2) Audit log reconstruction — all locks acquired in a 1-minute window can be found by UUID v7 range query. 3) Stale lock detection — a token older than the expected operation timeout is provably stale without a database query. See UUID v7 for Audit Logging.
What is Redlock and how does UUID v7 fit?
Redlock is an algorithm for distributed locks across multiple Redis instances. Each lock acquisition attempt uses a unique random value as the token — this is typically a random string or UUID v4. Substituting UUID v7 provides the same uniqueness guarantee (74 random bits) while adding an embedded timestamp for TTL alignment and audit tracing. The Redlock algorithm itself is unchanged.