How to Implement Distributed Locking Safely
Use leases, ownership tokens, and fencing to make distributed locks safe, and learn when Redis, databases, or consensus services fit.
On this page
Introduction
A distributed lock is an agreement that at most one process enters a critical section at a time. It underpins cron job deduplication, schema migrations, leader election, and inventory reservations. But a lock cannot stop a process that already believes it holds it; it only coordinates processes that can reach the lock service and whose pauses behave well enough.
The design must separate efficiency from safety. A lock can prevent most duplicate work, while the protected resource itself rejects stale writers. Confusing the two produces systems that look correct until a garbage collection pause or a failover exposes the gap.
What a Lock Can and Cannot Promise
A lock provides mutual exclusion only while its lease is valid and the lock service is reachable. It cannot stop a paused process when the lease expires. A long garbage collection pause, a suspended virtual machine, or a starved event loop can freeze a worker past its TTL; a second worker then acquires the lock while the first is still about to write.
Failover has the same problem. If Redis replicates asynchronously and the primary dies before the acquisition reaches a replica, the promoted replica never saw the lock. A partition can leave a worker believing it holds a lock the service has already given away. These are ordinary distributed-systems events, not exotic failures.
A lock is therefore often a performance optimization rather than a safety guarantee. Enforce correctness at the resource with a conditional write, version number, unique constraint, or fencing token. If the resource cannot enforce anything, the lock is best effort and should be described that way.
Leases, Ownership Tokens, and Fencing
Every acquisition should produce a lease with a unique owner token, an expiry, and a monotonically increasing fencing token. The owner token prevents one process from releasing or renewing another’s lease. The expiry recovers from a crashed owner. The fencing token lets the resource distinguish the current owner from a stale one.
Each successful acquisition receives a larger token than every previous acquisition. The resource stores the highest token it has seen and rejects smaller ones, so a stale worker that wakes after expiry cannot overwrite the new owner’s work.
UPDATE jobs
SET status = 'completed', fencing_token = $2
WHERE id = $1
AND (fencing_token IS NULL OR fencing_token < $2)
RETURNING id;
The check must be atomic with the write; reading the token and writing in separate transactions leaves a race. If an external API cannot compare tokens, fencing is unavailable, and the lock cannot provide safety against pauses. That limitation should determine which operations you place behind it.
A Redis Implementation and Its Traps
Use SET key token NX PX ttl as one command; separate SETNX and EXPIRE calls can leave a lock without expiry after a crash. Release must compare the token and delete in one Lua script, or an expired owner can delete a new owner’s lock.
-- acquire: unique token, TTL in milliseconds
if redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then
return 1
end
return 0
-- release: only the current owner may delete the key
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
An acquisition timeout is ambiguous: the command may have succeeded. Query the key and compare the token before retrying, and make the following operation idempotent so an uncertain acquisition does not duplicate work.
TTL is a compromise. A short TTL recovers quickly from crashes but expires during slow work; a long TTL blocks the resource after a crash. A watchdog can renew while the owner is alive, but renewal depends on the same process, and a renewal arriving after expiry must not resurrect the old token. Renewal improves efficiency, not safety. Single-node Redis loses locks on failover. Redlock acquires a majority of independent masters, but still assumes bounded clock drift and timely execution; it is not a substitute for fencing in correctness-critical systems.
Database and Consensus Alternatives
If every worker shares a relational database, database locks are often simpler. PostgreSQL pg_try_advisory_lock(key) returns a boolean immediately, while pg_advisory_xact_lock(key) releases at commit or rollback. Row locks with SELECT ... FOR UPDATE serialize access to a row, and a unique constraint can enforce a once-only job without a lock.
Database locks disappear when a connection drops, which is useful after a crash, but long transactions block unrelated work. They also do not coordinate workers writing to another system. Keep critical sections short and set lock and statement timeouts.
For leader election across services, use a consensus-backed store. etcd leases expire unless renewed and expose revisions usable as fencing tokens; ZooKeeper ephemeral sequential nodes provide ownership; Consul sessions offer locking with health checks. These provide linearizable coordination at the cost of another operational dependency.
Failure Modes and Testing
The classic failure is a pause longer than the TTL: the first worker resumes and writes after the second has taken over. Fencing rejects the stale write only if every mutation path checks it, including asynchronous jobs, retries, and admin tools. One unprotected path defeats the design.
Clock assumptions cause subtler failures. The lock service owns expiry, but client deadlines use local time. Never treat a local clock comparison as proof that the lease is valid, and stop work when renewal fails instead of assuming the lock survived a partition. Other failure modes include unconditional DEL of another owner’s lock, renewal after expiry, nested locks acquired in different orders, and a lock outage that blocks all work. Decide explicitly whether to fail open or closed; duplicate emails may tolerate open, payment settlement may not.
Tests must use real Redis, PostgreSQL, or etcd instances, because mocks cannot reproduce atomicity or failover. Cover two clients racing, release with the wrong token, expiry during a pause, renewal after expiry, a stale write rejected by fencing, restart or failover, and a partition that prevents renewal. Inject delays rather than relying on timing luck, and assert the invariant that matters: a write with an older token is never accepted after a newer token.
Limitations and When Not to Lock
Distributed locks add a dependency, latency, and a failure mode to every critical section. If a unique constraint, conditional update, idempotency key, or single-writer partition can enforce the invariant, prefer it; those mechanisms fail more predictably. If duplicate work is harmless, a lock may not be worth the complexity.
Never use a lock as a substitute for a transaction, and never describe a Redis lease as mutual exclusion without fencing. Document the lease duration, renewal policy, ownership token, outage behavior, and the resource-side check that makes stale writes harmless. A lock that is merely probable is still useful for reducing work, but it is not a correctness boundary.
Sources: Redis: Distributed Locks, Martin Kleppmann: How to do distributed locking, PostgreSQL: Advisory Locks.
FAQ
- Is a Redis lock with a TTL safe for critical sections?
- Only if the protected resource also enforces a fencing token, or if occasional concurrent execution is tolerable. A process pause longer than the TTL lets a second owner acquire the lock while the first still believes it holds it.
- Should I use Redlock?
- Redlock improves availability across independent Redis nodes, but it still relies on bounded clock drift and timely process execution. For correctness-critical mutual exclusion, use a consensus-backed service or enforce a monotonic fencing token at the resource.
- When is a database lock enough?
- When all workers share the database and the critical section is transactional, PostgreSQL advisory locks or row locks are simpler and avoid another distributed system. They do not help when the protected resource lives outside that database.
Report a problem with this articleOpens a pre-filled issue on GitHub.