Fencing tokens solve a fundamental problem in distributed locking: a process can hold a lock, pause (garbage collection, network partition), have its lock expire and be re-granted to another process, then resume and overwrite the second holder’s work. A fencing token prevents this by giving storage systems a way to detect and reject stale writes. See Distributed Lock for the lock acquisition context.
The problem fencing tokens solve
Time →
T=0 Process A acquires lock. Token = 33.
T=1 Process A writes to storage with token 33. Accepted.
T=2 Process A pauses (GC, network).
T=3 Lock expires. Process B acquires lock. Token = 34.
T=4 Process B writes to storage with token 34. Accepted.
T=5 Process A resumes. Tries to write with token 33.
Storage sees 33 < 34 → REJECTS write. Data protected.
UUID v7 as a fencing token
import { v7 as uuidv7 } from 'uuid';
interface LockGrant {
token: string; // UUID v7 — encodes grant time
resource: string;
holder: string;
expiresAt: number;
}
// Lock service issues UUID v7 token on each grant
function issueLock(resource: string, holder: string, ttlMs: number): LockGrant {
return {
token: uuidv7(), // UUID v7 — each new grant has a newer token
resource,
holder,
expiresAt: Date.now() + ttlMs,
};
}
// Storage system: accept write only if token is newer than last seen
class FencedStore {
private highWatermark: string = '';
write(key: string, value: unknown, token: string): boolean {
// UUID v7 lexicographic comparison = chronological
if (token <= this.highWatermark) {
console.warn(`Stale write rejected: token ${token} <= hwm ${this.highWatermark}`);
return false;
}
this.highWatermark = token;
// perform write...
return true;
}
}
Redis implementation
import { createClient } from 'redis';
import { v7 as uuidv7 } from 'uuid';
const redis = createClient();
// Acquire lock and return UUID v7 fencing token
async function acquireWithFencingToken(resource: string, ttlMs: number) {
const token = uuidv7();
const key = `lock:${resource}`;
const ok = await redis.set(key, token, { NX: true, PX: ttlMs });
return ok ? token : null;
}
// Conditional write: only proceed if our token is current
async function fencedWrite(resource: string, token: string, writeOp: () => Promise<void>) {
const current = await redis.get(`lock:${resource}`);
if (current !== token) {
throw new Error('Lock lost — write fenced');
}
// Note: in production use a Lua script for atomicity
await writeOp();
}
UUID v7 vs strict monotonic tokens
| Property | UUID v7 token | Database sequence token |
|---|---|---|
| Generation | Decentralized, no coordination | Centralized sequence |
| Monotonicity | Time-ordered (1ms) + random | Strictly monotonic |
| Same-ms ordering | Probabilistic (random bits) | Guaranteed |
| Coordination overhead | None | Requires DB or Redis INCR |
| Suitable for | Loose time ordering, audit logs | Strict per-ms fencing |
When UUID v7 suffices
- Lock TTLs are seconds or minutes — same-millisecond ordering does not matter
- Audit log reconstruction — “what was held during the outage window”
- Detecting locks acquired 10+ seconds before a write — UUID v7 timestamps are unambiguous
When to use strict monotonic tokens
- High-frequency lock churn (< 1ms between acquisitions)
- Storage systems that must reject all out-of-order writes with zero tolerance
- Financial ledger writes where strict sequence matters
Further reading
- Distributed Lock — Mutual Exclusion in Distributed Systems
- Monotonic Counter
- Idempotency Key
- UUID v7 for Audit Logging
- Write Skew — Concurrency Anomaly
Frequently asked questions
What is a fencing token?
A fencing token is a value provided by a lock service when a lock is granted. The token value increases monotonically with each lock grant. When a lock holder makes a write to a storage system, it includes the token. The storage system rejects writes with a token lower than the highest token it has seen — this prevents a slow or paused lock holder from overwriting data after its lock has expired and been re-granted to another holder. See Distributed Lock.
Can UUID v7 be used as a fencing token?
UUID v7 provides time-ordered uniqueness with 1ms granularity plus 74 random bits. It is not strictly monotonic — two UUIDs generated in the same millisecond may sort in random order by their random bits. For applications where strict monotonicity is required, use a database sequence or Redis INCR. For applications where approximate time ordering suffices (detecting a lock holder that is minutes stale), UUID v7 provides sufficient ordering with no coordination overhead. See Monotonic Counter.
How does UUID v7 improve on random tokens for lock fencing?
A random token (UUID v4) provides no ordering — a storage system cannot tell whether one lock grant is newer than another without querying the lock service. UUID v7 embeds a timestamp: a token acquired 10 minutes ago is provably older than one acquired now, without any external query. This enables passive staleness detection in storage systems and audit logs. See UUID v7 for Audit Logging.