Sometimes many machines must agree: who is the single leader, who owns this job, who may update this record right now. On one machine you would use a lock. Across machines, with separate clocks, unreliable networks and servers that can freeze for seconds, the same idea gets much harder.
This lesson introduces distributed locks, leases (locks that expire), leader election, fencing tokens and the idea behind consensus (how a group of machines agrees on one value despite failures). You will not be asked to implement Raft, but you must know when to reach for a coordination service and what can go wrong.
Detailed Notes
What is it?
Coordination means getting several independent machines to act as one: only one runs a scheduled job, only one is the primary database, only one holds a lock on a resource.
A distributed lock gives one client exclusive access to a resource across machines.
A lease is a lock with a time limit. The holder must renew it before it expires. If the holder dies, the lease simply runs out and someone else may take over. Leases are the right default because a plain lock held by a crashed machine would block everyone forever.
Leader election picks one node among several as the leader (also called primary or master) that does the exclusive work, such as accepting writes or running a scheduler. If it fails, the others elect a new one.
Consensus is the problem of getting a group of nodes to agree on a single value even when some nodes crash and messages are delayed. Algorithms such as Raft and Paxos solve it. They are the machinery underneath coordination services like ZooKeeper, etcd and Consul.
Why do we need it?
Without coordination, you get one of two bad outcomes:
Two machines act as leader (a state called split brain): both accept writes, the data diverges and is hard or impossible to repair.
Nobody acts as leader: the system is stuck until a human steps in.
Concrete cases: a nightly billing job that must run once (not on all 10 servers), a database primary that must be unique, a flash-sale inventory counter, a cron scheduler, a distributed file's single writer, and an exclusive "seat hold" in a ticketing system.
How does it work?
Why a simple lock is not enough
Imagine a lock stored in a Redis key. Client 1 takes it, begins writing to a file, then freezes for 40 seconds in a garbage collection pause (the runtime stops the program to free memory). The lock expires after 30 seconds. Client 2 takes the lock and writes. Client 1 wakes up, still believes it holds the lock, and overwrites Client 2's data. The lock service did everything right; the client's own view of time was wrong. Clocks differ between machines and processes can pause at any moment, so you can never be sure a lease is still valid at the instant you act.
Fencing tokens
The fix: every time the lock is granted, the lock service hands out an increasing number, a fencing token (33, then 34, then 35...). The client sends the token with every write to the protected resource, and the resource remembers the highest token it has seen and rejects anything lower. Now the stale Client 1 (token 33) is refused once Client 2 (token 34) has written.
Fencing Tokens Stop a Stale Lock HolderRequest flow
Client 1 freezes and its lease expires. The storage layer rejects its late write because the token is old.
The lesson: the resource itself must check; a lock alone cannot make a pausing client safe.
Leader election with a coordination service
Do not write your own. Use a small, strongly consistent cluster (3 or 5 nodes) running consensus, such as etcd or ZooKeeper. A common pattern:
Every candidate tries to create the same key (/election/leader) with a lease of 10 seconds. Only one succeeds because the store is strongly consistent: exactly one writer wins.
The winner is the leader and renews its lease every 3 seconds (a heartbeat).
The others watch the key. If the leader crashes or is partitioned away, renewals stop, the lease expires after 10 s, the key disappears, and the watchers race to create it again. A new leader emerges with a higher term or epoch number, used as the fencing token.
Leader Election with a LeaseArchitecture
Consensusetcd node 1quorum 2 of 3etcd node 2holds the keyetcd node 3replicaNode A: leaderrenews every 3 sNode B: standbywatches the keyNode C: standbywatches the keyheartbeatwatchwatchreplicatereplicate
Key point. The consensus cluster decides who is leader. Workers only need to watch one key.
Whoever creates the key owns the lease and renews it. When renewals stop, another node takes over.
The timeouts are a trade-off: a 10 s lease means up to about 10 s without a leader after a crash. Shorter leases recover faster but cause false failovers when a healthy leader is merely slow.
Consensus in one paragraph
Why 3 or 5 nodes? Consensus protocols require a majority quorum (more than half) to agree before anything is committed: 2 of 3, or 3 of 5. Any two majorities overlap in at least one node, so two groups can never both believe they are in charge. A cluster of 2n+1 nodes tolerates n failures: 3 nodes survive 1 failure, 5 nodes survive 2. A partitioned minority simply cannot make progress, which is the CAP trade-off from the consistency lesson, choosing consistency over availability on the small side. In Raft the nodes elect a leader for a numbered term; the leader appends each change to a log and commits it once a majority has stored it.
text
Nodes Quorum Failures tolerated
3 2 1
5 3 2
7 4 3
More nodes = more fault tolerance, but each write needs more acknowledgements (slower).
Practical guidance
Prefer not to need a lock. Partition the work so each item has exactly one owner (consistent hashing from the partitioning lesson), use a queue with one consumer per partition, or use optimistic concurrency (a version number checked on update: UPDATE ... WHERE id=7 AND version=12). These avoid coordination entirely.
Use a lock when the correctness of a rare critical section matters, with a lease, a short expiry and a fencing token.
Keep the coordination cluster small and out of the hot path. It stores a few kilobytes of metadata (who is leader, configuration), not your business data. A lock per request would make it the bottleneck: it handles roughly thousands, not millions, of writes per second.
Efficiency locks versus correctness locks. If a duplicate run merely wastes money (two servers sending the same cache refresh), a simple Redis lock with a TTL is fine. If duplicates corrupt data (double-spend), you need consensus-backed locks and fencing.
Interview tip. Avoid claiming "I'll use a Redis lock so only one worker runs" as if it were perfectly safe. Say what happens if the holder pauses or the lock expires early, and mention fencing tokens or idempotent operations. Also say you would use an existing coordination service rather than implement consensus yourself.
Real-world example
A database cluster has one primary and two replicas. The nodes use a consensus cluster (like etcd) to elect the primary. When the primary's host fails, its lease expires within about 10 seconds and a replica is elected with a higher term number. The old primary, if it comes back, sees the higher term and demotes itself instead of accepting writes, and storage rejects any write carrying an older term.
System design example
A ticketing system must ensure a seat is never sold twice during a flash sale. Options:
Distributed lock per seat in a coordination store: correct, but 100,000 users requesting 50,000 seats creates heavy contention on the lock service.
Database row with optimistic concurrency: UPDATE seats SET holder=:u, version=version+1 WHERE seat=:s AND holder IS NULL. One statement, atomic in the database, zero extra moving parts. Exactly one request sees "1 row updated".
Add a hold with a lease: the holder field is set with an expiry of 5 minutes; a background job (run by an elected leader so only one instance sweeps) releases expired holds.
The decision: let the database be the arbiter for per-seat correctness, and use leader election only for the single housekeeping job.
Interview discussion. "For anything that must have exactly one owner I'd use a lease through a consensus-backed store like etcd, not hand-rolled code. Because a holder can pause past its lease, I'd attach a fencing token and have the resource reject stale tokens. Where possible I'd avoid locks by partitioning ownership or using optimistic concurrency."
Trade-off thinking. Locks give simple reasoning but add latency, a failure point and the pause problem. Optimistic concurrency has no waiting but retries on conflict, so it suits low contention. Shorter leases fail over faster but risk false failovers; longer leases are calmer but slower to recover. A bigger consensus cluster tolerates more failures but writes get slower.
Key interview takeaway
Use leases, never locks without expiry. Remember the pause problem and fix it with fencing tokens. Elect leaders through a consensus-backed service with 3 or 5 nodes and a majority quorum, and avoid coordination where partitioning or optimistic concurrency will do.
Real World Example
A database cluster elects its primary through an etcd-style consensus store. When the primary's host dies, its lease expires in about 10 seconds and a replica takes over with a higher term. If the old primary returns, it sees the higher term and demotes itself, and storage rejects writes carrying the older term.