A distributed lock is a coordination mechanism that ensures only one process across several machines can hold a given lock and act on a shared resource at a time. In concurrency, it extends the idea of a mutex beyond a single address space: instead of shared memory, the processes agree on ownership through a network-accessible coordination service such as a consensus-based key-value store or a database.
Distributed locks appear wherever several service instances must not perform the same work simultaneously, for example running a scheduled job once, updating a shared file or reserving limited inventory. They are much harder to implement correctly than local locks, because networks delay messages, processes pause and clocks drift.
How a distributed lock works
A client acquires the lock by asking the coordination service to create or claim a record under an agreed name, such as lock:invoice-batch. The service grants the claim only if no other client currently holds it, using an atomic operation such as compare-and-swap or a conditional write.
Because a client can crash while holding the lock, practical implementations attach a lease with a time-to-live (TTL). If the holder does not renew the lease before it expires, the service releases the lock automatically, which prevents permanent blocking after a failure. The holder renews the lease periodically through a heartbeat and deletes the record when it finishes the critical section.
The core properties that a distributed lock must provide are listed below.
| Property | Meaning | Typical mechanism |
|---|---|---|
| Mutual exclusion | At most one holder at any moment | Atomic conditional write |
| Liveness | A crashed holder does not block others forever | Lease with TTL |
| Fault tolerance | The lock survives failure of service nodes | Replication with consensus |
| Safety under delays | A stale holder cannot corrupt the resource | Fencing tokens |
| Fairness | Waiting clients are served in a predictable order | Sequential queue nodes |
Common implementations and their guarantees
Implementations differ mainly in how strongly they guarantee mutual exclusion when nodes fail or the network partitions. Systems built on a consensus algorithm such as Raft or ZAB provide linearizable operations, while single-node caches trade correctness for speed.
| Implementation | Basis | Strength of guarantee |
|---|---|---|
| ZooKeeper ephemeral sequential nodes | ZAB consensus, session-bound nodes | Strong, with ordered waiting |
| etcd lease with revision | Raft consensus, monotonic revisions | Strong, revision usable as fencing token |
| Single Redis key with SET NX PX | One in-memory node | Weak if the node fails or fails over |
| Redlock across Redis nodes | Majority of independent nodes with timing | Disputed under clock and pause faults |
| Relational database row lock | Transactions or advisory locks | Strong within one database primary |
Redlock illustrates the central controversy. It acquires the lock on a majority of independent Redis instances and relies on bounded clock drift and network delay for correctness. Critics argue that a long garbage-collection pause or a clock jump can let two clients believe they hold the lock simultaneously, so the algorithm should not protect correctness-critical operations without additional fencing.
Fencing tokens and the stale holder problem
A lease alone cannot guarantee safety. A client may acquire the lock, then pause for longer than the TTL, for instance during a stop-the-world garbage collection or a virtual machine migration. The lease expires, another client acquires the lock, and the first client resumes and writes to the resource while believing it is still the holder.
The standard remedy is a fencing token: a number that increases every time the lock is granted. The client sends its token with each write, and the protected resource rejects any write carrying a lower token than the highest one it has already seen. This moves the final safety check to the resource itself, which is the only component that can enforce it reliably.
Fencing requires that the storage system supports conditional writes on the token. When it does not, the lock should be treated as an efficiency optimization that prevents duplicate work most of the time, not as a guarantee of correctness.
Distributed locks compared with related concurrency tools
Distributed locks share goals with local primitives but face different failure modes. The comparison below places them next to their neighbors in concurrency.
| Mechanism | Scope | Main failure concern |
|---|---|---|
| Mutex | Threads in one process | Deadlock and contention |
| Read-write lock | Threads with many readers | Writer starvation |
| Database transaction | Operations within one database | Isolation anomalies |
| Distributed lock | Processes on many machines | Partitions, pauses and clock drift |
| Leader election | One long-term coordinator in a cluster | Split brain after partitions |
A distributed lock held for a long time is effectively leader election, and many coordination libraries implement both with the same primitives. When the protected data lives in a single database, a transaction or row-level lock in that database is usually simpler and safer than an external lock service.
Practical guidance and common mistakes
The first design question is why the lock is needed. If duplicate execution only wastes resources, a lightweight lock with occasional failures is acceptable. If duplicate execution corrupts data or charges a customer twice, the design needs a consensus-backed store, fencing tokens and preferably idempotent operations.
- Choosing a TTL that is too short causes leases to expire during normal work; too long a TTL delays recovery after crashes.
- Releasing a lock without checking ownership can delete another client’s lock; compare a unique owner value before deleting.
- Ignoring renewal failures lets the holder continue after losing the lock; stop work when renewal fails.
- Relying on wall-clock time across machines introduces errors from clock skew; prefer monotonic clocks and server-side leases.
- Holding locks across slow external calls increases contention and the window for stale holders.
The idea in brief
A distributed lock is like a single key to a shared room that many people in different buildings want to use. Instead of passing a physical key, they ask a trusted coordinator who has it, and the coordinator lets only one person in at a time.
The tricky part is that people can fall asleep inside or lose contact. So the key expires after a set time, and a numbered ticket system makes sure that someone who wakes up late cannot cause damage with an old key.
A practical scenario
An online ticketing service runs six instances of its billing service behind a load balancer. Every night at 02:00, a scheduled job must generate invoices exactly once. Without coordination, all six instances start the job, and customers receive duplicate invoices.
The team adds a lock in etcd named billing-nightly with a 30-second lease renewed every 10 seconds. The instance that acquires it runs the job and passes the lease revision as a fencing token to the invoice database, which stores the highest token per batch and rejects older ones. During testing, an engineer freezes the active instance for 45 seconds; another instance takes over, and the frozen one’s late writes are rejected. Duplicate invoices stop entirely, and the job completes even when an instance fails mid-run.