Back
+20 XP
Concept

Distributed Locks & Atomic Token Semantics

Distributed locks synchronize separate nodes. A robust implementation requires atomic acquisition (`SET NX PX`), a Time-To-Live (TTL) to prevent deadlocks on node crashes, and unique tokens to prevent releasing another node's lock 🔒.

python
import uuid

class DistLock:
    def __init__(self):
        self.store = {}

    def acquire(self, key):
        token = str(uuid.uuid4())
        if key not in self.store:
            self.store[key] = token
            return token
        return None

    def release(self, key, token):
        if self.store.get(key) == token:
            del self.store[key]
            return True
        return False

lock = DistLock()
tok = lock.acquire("resource_1")
print(f"Acquired: {tok is not None} 🔒")
print(f"Conflict rejected: {lock.acquire('resource_1') is None} 🛑")
print(f"Released: {lock.release('resource_1', tok)} ✅")

# 85. Distributed Locks & Atomic Token Semantics Distributed locks synchronize separate nodes. A robust implementation requires atomic acquisition (`SET NX PX`), a Time-To-Live (TTL) to prevent deadlocks on node crashes, and unique tokens to prevent releasing another node's lock 🔒. ```python import uuid class DistLock: def __init__(self): self.store = {} def acquire(self, key): token = str(uuid.uuid4()) if key not in self.store: self.store[key] = token return token return None def release(self, key, token): if self.store.get(key) == token: del self.store[key] return True return False lock = DistLock() tok = lock.acquire("resource_1") print(f"Acquired: {tok is not None} 🔒") print(f"Conflict rejected: {lock.acquire('resource_1') is None} 🛑") print(f"Released: {lock.release('resource_1', tok)} ✅") ``` In production Redis setups, lock releases are executed as atomic Lua scripts (`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) end`) to avoid race conditions between GET and DEL 🛡️! --- ### Question Why must a distributed lock match a unique client token before executing release? 🧠 - [ ] a. To prevent a delayed process whose TTL elapsed from mistakenly deleting another client's newly acquired lock 🔒 - [ ] b. To verify client authentication credentials against an LDAP active directory - [ ] c. To compress key metadata before writing to network sockets - [ ] d. To notify the kernel that thread memory can be safely swapped to disk --- ### Challenge Build `DistLock` with `acquire(key)` and `release(key, token)`. Acquire `'lock_a'`, verify second acquire returns `None`, release with token, and print `'LOCK_OK'`. 🎯 <details> <summary>Solution</summary> ```python import uuid class DistLock: def __init__(self): self.data = {} def acquire(self, key): tok = str(uuid.uuid4()) if key not in self.data: self.data[key] = tok return tok return None def release(self, key, token): if self.data.get(key) == token: del self.data[key] return True return False lock = DistLock() t1 = lock.acquire('lock_a') assert lock.acquire('lock_a') is None assert lock.release('lock_a', t1) is True print('LOCK_OK') ``` </details>

Checkpoint

Why must a distributed lock match a unique client token before executing release? 🧠

Practice

Build `DistLock` with `acquire(key)` and `release(key, token)`. Acquire `'lock_a'`, verify second acquire returns `None`, release with token, and print `'LOCK_OK'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks