Distributed Locks Explained: One Writer at a Time, Across Machines

Distributed locks explained in plain terms start with a familiar problem: two machines both decide to do the same job at the same moment. The central question is how a system with no shared memory can guarantee that only one machine acts at a time, and the answer is a lock service that hands out a single token, holds it until the work is done, and takes it back if the holder disappears.

A distributed lock is a promise enforced by a third party. A machine asks a lock service for exclusive access to a named resource, the service grants it to one machine at a time, and every other machine waits its turn. It sounds simple, and the basic idea is, but the failures of distributed systems make the details surprisingly sharp.

This article explains how distributed locks work, the fencing problem that catches out careless designs, and when a lock is the wrong tool altogether.

Key takeaways

  • A distributed lock grants exclusive access to a named resource across machines.
  • A lock service is the third party that decides who holds the lock.
  • Locks must expire, or a crashed holder blocks everyone forever.
  • Fencing tokens stop a stale holder from acting after losing its lock.
  • Many problems that look like locking problems are better solved without locks.

What a distributed lock is

On a single machine, a lock is easy: a mutex in memory, held by one thread at a time, released when the work finishes. Across machines there is no shared memory, so the lock has to live somewhere all the machines can reach, usually a dedicated service such as etcd, ZooKeeper, or a Redis instance set up for the purpose.

The lock service keeps a record for each named lock, noting which client holds it and until when. A machine that wants the lock asks the service, and the service either grants it or tells the machine to wait. When the holder finishes, it tells the service to release the lock, and the service grants it to the next waiter.

The classic use is protecting a job that must run exactly once. A scheduled task that runs on several servers, a payment that must not be processed twice, a file that must not be written by two workers at once: all of these are distributed lock problems, and all of them fail messily without one.

Why locks must expire

The first hard problem is what happens when the holder crashes. On a single machine, the operating system cleans up after a dead process, but across a network nobody notices immediately that a holder has gone. Without a safeguard, a crashed holder would keep the lock forever and every other machine would wait forever.

The safeguard is a lease: every lock comes with an expiry time. The holder must renew the lease regularly, a heartbeat that says it is still alive and still working, and if the heartbeat stops, the lock service expires the lock and grants it to someone else. The lease turns a permanent blockage into a temporary delay.

Leases introduce their own risk, which is the second hard problem. A machine that pauses, because of a long garbage collection or a slow network, can miss its renewal window and lose its lock while it still believes it holds it. It then carries on working as if it were the exclusive owner, while a second machine has already been granted the same lock, and both write at once.

Fencing tokens: the fix for stale holders

The fix is the fencing token, a number that increases every time a lock is granted. The first holder gets token 1, the next gets token 2, and so on, and every protected operation must carry the token that granted it. A storage system that sees a write carrying token 1 after it has already seen token 2 rejects the older write.

The token turns a silent disaster into a loud, safe failure. The stale holder’s writes are refused rather than applied, so the data stays consistent even though the holder did not know it had lost the lock. The holder may be surprised, but the data is not corrupted, which is the trade that matters.

Fencing only works if every part of the system checks the token. A token that is issued but never verified is decoration, and a storage layer that accepts writes without comparing tokens is exactly as unsafe as a system with no tokens at all. Our guide to linearizability explains the consistency standard that fencing is built to preserve.

A dark office with a single glowing brass key on a desk between two laptops, one screen lit and one dark
A dark office with a single glowing brass key on a desk between two laptops, one screen lit and one dark, shows the distributed lock idea: only one machine holds the key at a time.

Distributed locks compared with other coordination

Locks are one of several ways for machines to coordinate, and they are often the bluntest. Leader election picks one machine to decide, consensus protocols agree on a sequence of operations, and idempotent operations make it safe to retry without any coordination at all.

The table below sets out the main contrasts.

Aspect Distributed lock Leader election Idempotent operations
What it guarantees One holder at a time One decision-maker Safe retries, no coordination
Needs a lock service Yes Yes, usually the same one No
Failure mode Stale holder writes twice Two leaders after a partition Duplicate effects if not careful
Latency cost One round trip per lock Paid once, then cheap None
Best for Short exclusive jobs Long-lived coordination Operations that can safely repeat

The practical result is that locks suit short, well-defined jobs, while longer coordination belongs to a leader, and work that can be made idempotent should be, because the cheapest coordination is none at all.

How to use a distributed lock well

Keep the locked section short. A lock held for seconds is a minor risk, while a lock held for minutes is a long window in which the holder can stall, lose its lease, and cause exactly the double-write the lock was meant to prevent. Do the slow work outside the lock, and hold it only for the final step.

Always set a timeout on acquiring the lock, so that a machine that cannot get it fails fast instead of queuing forever. A waiter that gives up cleanly is far easier to reason about than one that hangs, and a job that reports it could not get the lock is far better than a job that silently never runs.

Make the protected work idempotent as well, so that even if two holders do slip through, the damage is limited. A lock plus an idempotent operation is two layers of defence, and either one alone is thinner than both together. Our guide to idempotency explains how to design operations that are safe to repeat.

Choose the lock service with the same care as the data it protects. A lock service that is itself unavailable blocks every job that needs a lock, so it must be at least as reliable as the system around it, which is why teams usually run it on a consensus-based store. Our guide to leader election explains the closely related problem of picking one machine to decide, which most lock services solve internally.

When not to use a distributed lock

The most common mistake is reaching for a lock when the real need is a queue. If the work is a stream of jobs that many machines can process, a queue hands each job to one worker and needs no locking at all, and it survives worker crashes by reassigning unacknowledged jobs.

Another mistake is locking to protect a counter or a balance. A counter that many machines increment is better handled with an atomic increment operation, and a balance that must never go negative is better handled with a conditional update, because both avoid the lock entirely and scale far better.

Locks are also the wrong tool for ordering events across machines. A lock can say who goes first right now, but it cannot reconstruct the order of things that already happened, and it cannot tell two independent events apart, which is work for logical clocks and versioning instead.

The rule of thumb is simple: if the operation can be made idempotent, make it idempotent. If the work can be queued, queue it. Reach for a distributed lock only when exactly one machine must do exactly one thing at exactly one moment, and there is no other way to express that.

Strengths and limits

The greatest strength of distributed locks is that they are easy to understand. One holder, one token, one resource, and a lease that cleans up after crashes, is a model that most engineers can hold in their heads, which makes it easy to use correctly and easy to debug.

They are also widely available. Every serious distributed store offers a locking primitive, and libraries exist in every language, so a team can add a lock to a system in an afternoon rather than building coordination from scratch.

The limits are real, though. A lock is a single point of contention, a stale holder can still cause damage if fencing is missing, and a lock service outage freezes every job that depends on it. The history of distributed systems is full of outages caused by a lock service that became the very bottleneck it was meant to remove.

Distributed locks checklist

  • Give every lock a lease so a crashed holder cannot block everyone.
  • Renew the lease with a heartbeat while the work is running.
  • Use fencing tokens and check them on every protected write.
  • Keep the locked section as short as possible.
  • Set a timeout when acquiring a lock; never wait forever.
  • Make the protected work idempotent as a second layer of defence.
  • Run the lock service on a reliable consensus-based store.
  • Consider a queue or an atomic operation before reaching for a lock.
  • Monitor lock wait times; a growing queue signals a holder that is stuck.

Frequently asked questions

What is a distributed lock in simple terms?

It is an agreement, enforced by a lock service, that only one machine at a time may use a named resource, with a lease that expires if the holder crashes.

What is a fencing token?

It is a number that increases each time a lock is granted, carried with every protected write, so that a stale holder’s outdated writes are rejected instead of applied.

Why do distributed locks need leases?

Because a crashed holder cannot release its lock, and without an expiry the lock would stay held forever and block every other machine.

What is the difference between a lock and leader election?

A lock grants exclusive access for a short job, while leader election picks one machine to coordinate for a long period; both often use the same underlying service.

Can a distributed lock guarantee exactly-once execution?

Not on its own. A stale holder can still act after losing its lock, so exactly-once needs fencing tokens and idempotent operations alongside the lock.

When should I avoid distributed locks?

When the work can be queued, made idempotent, or handled with an atomic operation, all of which avoid the contention and failure modes a lock introduces.

The bottom line

Distributed locks explained in one line are this: one key, one holder, a lease that expires, and a token that fences out the ghosts.

They are a useful tool and a dangerous habit, and the difference is knowing when the job genuinely needs one and when a simpler design would do.

This article is general information about how distributed locks work, not advice about locking in a particular system.

Latest articles

Scroll to Top