Distributed locks and leader election
Making sure only one worker does a job at a time, and why a lock needs a lease and a fencing token to be safe.
On the roadmap:Advanced · step 4: Distributed systems
Lesson 18 of 23 · 9 min read · quiz · exercise
The need
Sometimes only one worker may do something at a time: run a nightly job, update a shared resource, be the primary of a group. On one machine you use a mutex. Across machines you need a distributed lock or leader election, and failure makes it tricky.
A naive lock and why it breaks
SET lock:job 1 NX (set only if not exists)
... do the work ...
DEL lock:job
Problems:
- The holder crashes before deleting: the lock is stuck forever.
- Add an expiry (a lease) to fix that, and a new problem appears: the holder is merely slow (a long pause, a network stall), the lease expires, a second worker takes the lock, then the first wakes up and keeps working. Now two hold it.
Leases and fencing tokens
A lease is a lock that expires unless renewed. It lets the system recover from failures, but it cannot, by itself, stop a stalled holder from acting after it has lost the lock.
The fix is a fencing token: every time the lock is granted, the lock service hands out a number that always increases. The holder sends the token with every write to the protected resource, and the resource rejects any request with a token older than one it has already seen.
Figure SDA-CORE-18-1 · Leases and fencing tokens · © forcsguy.com
This makes safety depend on the resource, not on timing.
Where to keep locks
Use a service built for coordination, with consensus underneath: etcd, ZooKeeper, Consul. A single Redis instance gives a convenient but weaker lock (it can lose the lock on failover). If correctness matters, prefer a consensus-based service or a database transaction.
Often you can avoid a lock: make the operation idempotent, use a conditional write (compare-and-set on a version), or let a queue hand each job to just one consumer.
Image: Senior Airman John Wright · Public domain · Source · Wikimedia Commons: Lajes Field Air Traffic Control
Leader election
The same tools elect a leader: nodes compete to create an ephemeral key or hold a lease; the winner leads and renews it. If it fails, the lease expires and another is chosen. Followers watch for changes.
- Expect brief periods with no leader during failover.
- Guard against a former leader acting too late (fencing tokens again, or stepping down when it cannot renew).
- Avoid split brain (two leaders) by requiring a majority (a quorum) to agree.
Rules of thumb
- Keep critical sections short, and renew the lease while working.
- Prefer designs that need no lock: idempotency, conditional writes, partitioned ownership.
- Always handle "I lost the lock" by stopping work.
- Test with pauses and network partitions, not only crashes.
Related reading
- ZooKeeper: Wait-free Coordination for Internet-scale Systems (paper)Hunt et al. · Yahoo! ResearchPapers
- How Ringpop from Uber Engineering Helps Distribute Your ApplicationUber Engineering · UberCase Studies
- The Chubby Lock Service (paper)Mike Burrows · GooglePapers
- Google SRE Book: Managing Critical State (Distributed Consensus)Google SRE team · GoogleBlogs
Show 6 moreShow fewer
- The Byzantine Generals Problem (paper)Lamport, Shostak and Pease · Microsoft ResearchPapers
- Paxos Made Simple (paper)Leslie Lamport · Microsoft ResearchPapers
- Apache ZooKeeperApache Software Foundation · GitHubGitHub
- Google SRE Book: Distributed Periodic Scheduling with CronGoogle SRE team · GoogleBlogs
- Nextdoor Engineering BlogNextdoor engineers · NextdoorBlogs
- Localytics Engineering BlogLocalytics engineers · LocalyticsBlogs
Check your understanding
Question 1 of 3
0 correct so far
Why should a distributed lock have an expiry (a lease)?
Topics covered in this lesson
Practise it: Losing the leader's machines
Everything below is already set up for this lesson: change the design, run the traffic, and see whether you meet the goal.
- 1The task
- 2Build and test
A group of nodes fails together. The system survives only if enough healthy capacity remains.
Goal: Under 2% errors after losing 3 servers.
Leader election finds a new leader quickly, but the survivors still need the capacity to do the work.
Try it yourself
A nightly job must run on exactly one of five identical servers. Sketch a safe approach, and say what could go wrong with a simple 'set a key if it does not exist' lock.
Click what a strong design here would need:
More in Building blocks
© 2026 forcsguy.com. Original lesson text and diagrams. Books and sites linked above belong to their authors.