Distributed lock = give exactly one client access to a resource across many machines. Sounds simple. Nuances lurk in timeouts + failures.

Client AClient BClient CLock ServiceRedis / ZK / etcdSET NX + TTLRedis simpleZK ephemeralauto-releaseetcd leaserenewableFencing tokenmonotonic IDStorage backendchecks tokenatomic write
Distributed locking with backing store + fencing token for safety
Advertisement

Redis SET NX + TTL

SET lock:x id EX 30 NX. Atomic. TTL handles crash cleanup. Simple + widely used.

Redis SET NX + TTL

SET lock:x id EX 30 NX. Atomic. TTL handles crash cleanup. Simple + widely used.

Advertisement

ZooKeeper ephemeral

Create ephemeral znode. Auto-deleted if client session dies. No TTL guessing.

etcd lease-based

Client holds a lease. Key with lease auto-expires. Client renews. Similar to ZK but simpler API.

Fencing token

Critical: monotonically increasing token issued with lock. Storage validates token on write. Prevents zombie clients (paused GC) from wrecking data.

Never trust just TTL

GC pause can extend past TTL. Two clients think they hold lock. Fencing token catches it.

SET NX + TTL is 90%. Add fencing token if writes matter. Otherwise ZooKeeper/etcd ephemerals.