0%
Distributed Systems: Consensus, Clocks, and Replication
Foundations
Time and Order
Replication
Consistency Models
Transactions and Operations
Leases, Locks and Fencing
Many systems need exactly one process to do something at a time: one scheduler running a cron job, one writer appending to a file, one worker processing a partition, one primary database accepting writes. On a single machine, a mutex solves this. Across machines, the obvious analogue, a lock held in some shared service, turns out to be far subtler, because the holder of the lock can pause, crash or lose its network connection while still believing it holds the lock. This section explains why, and sets up the tools the rest of the lesson builds: leases, fencing tokens and consensus backed lock services.
Two reasons to want a lock
Martin Kleppmann distinguishes two purposes for a distributed lock. A lock for efficiency prevents duplicated work: if two workers occasionally both send the same daily report, the cost is an extra email, so a lock that is usually right is fine. A lock for correctness prevents corruption: if two writers both believe they own a file, a ledger or a database primary, data can be lost or made inconsistent. The tools differ. Efficiency locks can use simple, cheap mechanisms that are occasionally wrong. Correctness locks need guarantees that hold even when processes pause and clocks drift, and as this lesson shows, a lock alone cannot provide them.
The problem with holding a lock forever
A lock service that grants locks until the holder releases them has an obvious flaw: if the holder crashes, the lock is never released, and the whole system stops. The lock service cannot tell a crashed holder from a slow one, which is the failure detection problem from earlier in the course. So every practical distributed lock has a time limit. After the limit, the lock service considers the holder gone and may grant the lock to someone else. A lock with a time limit is called a lease.
The process pause problem
A lease solves the crashed holder problem but introduces a new one. Suppose client A acquires a lease for ten seconds, then pauses for fifteen seconds, perhaps in a long garbage collection, a virtual machine migration, a page fault storm or a stopped process. The lease expires, and the lock service grants it to client B, which starts writing. Then A wakes up. From its point of view, no time has passed, and it believes it still holds the lease, so it writes too. Now two clients write concurrently, and the lock has failed at exactly the moment it was needed.
Checking the lease does not help
A natural response is to check the lease right before writing. But the pause can happen between the check and the write, so no amount of checking closes the gap. The same applies to network delays: a write sent while the lease was valid can sit in a network buffer and arrive after the lease expired. And clocks make it worse: the client measures lease time with its own clock, which may run slower than the lock service clock, so the client believes the lease lasts longer than the service does. Any scheme where the client alone decides whether it is still the holder is unsafe under pauses, delays and drift.
Pauses are common
It is easy to dismiss long pauses as rare, but production systems see them regularly. Garbage collectors in the JVM and other runtimes have historically paused for seconds on large heaps. Virtual machines are suspended during live migration. A process can be stopped by an operator, swapped out under memory pressure or delayed by a slow disk on a synchronous log write. In 2012, a GitHub outage involved a MySQL cluster where a paused node caused two primaries to exist simultaneously. HBase documented data loss caused by region servers that paused past their ZooKeeper session timeout and kept writing. These are not theoretical events.
What a correct lock needs
The lesson of the pause problem is that the resource being protected must take part in the protection. The lock service alone can promise at most that it will not grant overlapping leases according to its own clock. To stop a stale holder from causing damage, the storage or service receiving writes must be able to reject writes from holders whose lease has been superseded. The standard technique for this is the fencing token, the subject of a later section. Before that, the next section looks at how leases work and what they can safely guarantee.
The overall shape of the solution
Put together, a safe design has three parts. A consensus backed service, such as ZooKeeper or etcd, issues leases and guarantees that it never grants overlapping leases from its own perspective. Each grant comes with a monotonically increasing number, the fencing token. And every protected resource remembers the highest token it has seen and rejects requests carrying a lower one. Leases provide liveness when holders die; fencing provides safety when holders pause. Neither alone is enough.
The lock service view versus the holder view
It helps to separate two views of the same lock. The lock service has an authoritative view: according to its own state, replicated by consensus, the lease belongs to exactly one client at any moment. Each client has its own belief about whether it holds the lease, formed from replies it received in the past and its own clock. The service view is always consistent. The client beliefs can be stale. Every safety bug in this area comes from a client acting on a stale belief, and every remedy either shrinks the window in which beliefs can be stale or makes the protected resource consult something closer to the authoritative view.
Why not just use a consensus protocol for everything?
If consensus guarantees agreement, why not route every protected write through the consensus group itself? For small amounts of metadata, that is exactly what systems do: configuration, leadership records and small counters live in etcd or ZooKeeper and are updated with conditional writes, so there is no separate lock at all. But consensus groups are slow and small, typically handling thousands of writes per second and a few gigabytes of data. The resources people want to protect, such as large files, databases and external services, live elsewhere. The lock lives in the consensus group, the resource lives outside it, and fencing bridges the gap.
Mutual exclusion is a liveness and safety trade
Every lock design balances two failure modes. If the lease is too eager to expire, a slow but healthy holder loses the lock and work is interrupted or duplicated. If the lease is too reluctant to expire, a dead holder keeps everyone waiting. No lease length removes both risks, because the lock service cannot distinguish slow from dead. This is the same impossibility that runs through the whole course, showing up in the smallest coordination primitive. Fencing is what lets a design choose short, available leases without giving up safety.
A brief history
Distributed locking has a long research history. Lamport bakery algorithm from 1974 achieved mutual exclusion among processes without shared hardware locks. The lock managers in early clustered databases such as VAX clusters coordinated access to shared disks. Google Chubby, published in 2006, popularized the coarse grained lock service backed by consensus and introduced sequencers, its name for fencing tokens. Every modern lock service follows the Chubby blueprint.
What this lesson builds toward
The remaining sections develop each piece in turn: how leases measure time safely, how fencing tokens make resources reject stale holders, how real lock services implement both and how to design systems that use them, including when to avoid locks altogether. Together they turn a fragile intuition, take a lock then act, into a design that stays correct under pauses, delays and drift.
A process can pause past its lease expiry, or its write can be delayed in the network, and it will act as if it still holds the lock. Checking the lease before acting does not close the gap. The protected resource must reject stale holders itself.