Distributed locking

Distributed locking lets multiple nodes agree that only one holder “owns” a lock at a time (e.g. for a job or resource). Implementations use a shared store (Redis, etcd, Zookeeper) with compare-and-set or lease semantics. Used for leader election, single-run jobs, or protecting a shared resource across services.

Lock acquire and release

sequenceDiagram participant A as Node A participant B as Node B participant Redis as Redis/Store A->>Redis: SET lock:job1 token NX EX 30 Redis-->>A: OK (acquired) B->>Redis: SET lock:job1 token NX EX 30 Redis-->>B: nil (failed - held by A) A->>Redis: DEL lock:job1 (release) B->>Redis: SET lock:job1 token NX EX 30 Redis-->>B: OK (acquired)

Key concerns

flowchart LR A[Acquire lock] --> B[Do work] B --> C[Release lock] A -->|Fail| D[Retry or skip] Note[TTL: auto-release if holder dies]

Use distributed locks when you need mutual exclusion across processes (e.g. one scheduler instance, one consumer per partition). Prefer libraries (Redlock, etcd) and always set a TTL and owner token.