System Design FAQ: Top Questions
41. How would you design a Distributed Locking System?
A Distributed Locking System allows multiple nodes to coordinate safely over shared resources without race conditions โ critical for leader election, job scheduling, and safe updates in distributed systems.
๐ Functional Requirements
- Acquire and release lock atomically
- Handle lock expiry (TTL)
- Ensure only one owner per lock at any time
- Optional fencing token to prevent stale lock usage
๐ฆ Non-Functional Requirements
- Low-latency acquire/release (<10ms)
- Highly available and fault-tolerant
- Idempotent unlock operations
๐๏ธ Core Components
- Lock Store: Redis, ZooKeeper, or etcd
- Lock Client: Sends acquire/release requests
- Leader Election: Optional heartbeat-based monitor
๐ Redis Locking via Redlock (Python)
import redis
import uuid
import time
client = redis.StrictRedis()
lock_key = "lock:job42"
lock_value = str(uuid.uuid4())
ttl = 5000 # in ms
# Acquire lock
if client.set(lock_key, lock_value, nx=True, px=ttl):
print("Lock acquired!")
# Release lock
stored = client.get(lock_key)
if stored and stored.decode() == lock_value:
client.delete(lock_key)
๐งช Etcd Locking (gRPC)
etcdctl lock job42
# blocks until lock is acquired; stores lease ID for release
๐งฉ Fencing Token Concept
- Each lock acquisition increases a version counter
- All operations receive a fencing token (monotonic ID)
- Storage or service checks fencing ID for freshness
๐ Lock Table (PostgreSQL Example)
CREATE TABLE locks (
resource TEXT PRIMARY KEY,
owner_id TEXT,
fencing_token BIGINT,
updated_at TIMESTAMP DEFAULT now()
);
๐ Observability
- Lock acquisition wait time
- Abandoned locks cleanup frequency
- Failed release attempts
๐งฐ Tools/Infra Used
- Redis: Fast atomic SET/DEL support
- etcd: Consensus-based distributed coordination
- ZooKeeper: Hierarchical ephemeral nodes
๐ Final Insight
Distributed locks are tricky โ they require TTL, fencing, and consensus strategies for robustness. Prefer libraries like Redlock or use purpose-built coordination stores like etcd when correctness is critical.