Back
+30 XP
Concept

Asynchronous Distributed Mutex via Lock Server

Distributed locks can fail if a client experiences an unexpected GC pause or network partition, letting another client claim the lock while the first still believes it owns it. Fencing tokens provide strictly monotonic sequence numbers to safely reject stale writers.

python
class DistributedLockServer:
    def __init__(self):
        self.token_seq = 0
        self.owner = None
    def acquire(self, client):
        self.token_seq += 1
        return self.token_seq

# Asynchronous Distributed Mutex via Lock Server A distributed lock isn't as simple as setting a flag in Redis. If Worker A acquires a lock with a 5-second TTL and then suffers a 10-second GC pause or OS swap stall, Worker B will acquire the lock after TTL expiry. When Worker A wakes up, both workers execute critical write code at the same time. 💀🛡️ Martin Kleppmann’s **Fencing Token** pattern fixes this: every lock grant generates a strictly increasing number ($1, 2, 3\dots$). Storage services only accept writes with a fencing token higher than the highest token observed so far, discarding stale writes instantly. ```python class LockServer: def __init__(self): self.owner = None self.expires_at = 0.0 self.fencing_token = 0 ``` ## Pop Quiz Why are monotonic fencing tokens necessary in distributed locking systems? - [ ] They allow storage backends to reject delayed write requests from expired or paused lock owners. - [ ] They encrypt lock metadata using public key cryptography across cluster boundaries. - [ ] They force the Linux kernel to prioritize socket delivery on low-bandwidth connections." - [ ] They ensure that expired locks cannot be reclaimed until an operator manually restarts the service. ## Real-World Challenge Implement an asynchronous `LockServer` supporting: 1. `await acquire(client_id: str, ttl_sec: float) -> int | None`: Returns a new fencing token if acquired, or `None` if the lock is held and unexpired. 2. `await release(client_id: str, token: int) -> bool`: Releases the lock only if client ID and token match the active lease. <details> <summary>Solution</summary> ```python import asyncio class LockServer: def __init__(self): self.lock = asyncio.Lock() self.owner = None self.expires_at = 0.0 self.fencing_token = 0 async def acquire(self, client_id: str, ttl_sec: float) -> int | None: async with self.lock: loop = asyncio.get_running_loop() now = loop.time() if self.owner is None or now >= self.expires_at: self.owner = client_id self.expires_at = now + ttl_sec self.fencing_token += 1 return self.fencing_token return None async def release(self, client_id: str, token: int) -> bool: async with self.lock: if self.owner == client_id and self.fencing_token == token: self.owner = None self.expires_at = 0.0 return True return False # Verification async def run_test(): server = LockServer() t1 = await server.acquire("worker_alpha", ttl_sec=0.05) assert t1 == 1 t2 = await server.acquire("worker_beta", ttl_sec=0.05) assert t2 is None # Wait for alpha's lease to expire await asyncio.sleep(0.06) t3 = await server.acquire("worker_beta", ttl_sec=0.05) assert t3 == 2 # Alpha tries to release with old expired token released = await server.release("worker_alpha", t1) assert released is False # Beta releases with current valid token released = await server.release("worker_beta", t3) assert released is True asyncio.run(run_test()) ``` </details>