Intermediate LevelSystem Design & Architecture
What are Fencing Tokens and why are they necessary in distributed locking?
β Interview Prompt: Explain Distributed Lock failures, GC pauses, lock expiration race conditions, and Fencing Tokens.
Distributed locks can fail due to unexpected Garbage Collection (GC) pauses or network delays: a process holding a lock pauses, its lock TTL expires, another process acquires the lock, and the first process wakes up and corrupts data!
Fencing Tokens Solution:
Whenever a lock manager grants a lock, it returns a monotonically increasing Fencing Token ($1, 2, 3...$). The storage resource accepts writes ONLY if the fencing token is greater than the highest token processed so far!
Code Implementation Example
typescript
// Storage resource enforcing Fencing Token validation
export async function writeWithFencing(token: number, data: any) {
if (token <= lastProcessedFencingToken) {
throw new Error('Stale Distributed Lock: Fencing token rejected!');
}
lastProcessedFencingToken = token;
await storage.save(data);
}π‘Validating Fencing Tokens to reject stale lock holders.
π― Interview Key Takeaway
Pass monotonically increasing Fencing Tokens to storage resources to prevent stale lock holders from corrupting data.
#System Design#Fencing Tokens#Distributed Locks#Concurrency#Intermediate
Back to all System Design & Architecture Questionsβ