Consensus, leader election & distributed locks
Explain what Raft solves and when you need a coordinator like etcd or ZooKeeper.
By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.
In short
Consensus lets a group of nodes agree on a value, such as who the leader is, even when some fail. Raft does this with elected leaders and majority votes, and tools like etcd and ZooKeeper package it for coordination.
Explained simply
Consensus is the problem of getting several computers to agree on one thing, even when some of them crash or messages are delayed. Who is the leader right now? Which order did these writes happen in? Is this lock taken? If machines disagree on such questions, data gets corrupted.
The trick that makes it work is the majority. A decision only counts when more than half of the nodes accept it. Two different majorities of the same group always share at least one member, so two conflicting decisions can never both win. With five nodes, any three can decide, and the system survives two failures.
Raft is the most popular consensus algorithm today because it was designed to be easy to understand. One node is elected leader, it puts every change into an ordered log, and a change is committed once a majority has stored it. If the leader dies, the others elect a new one.
You rarely build consensus yourself. Tools like etcd (which runs Kubernetes) and ZooKeeper package it as a small, very reliable database for coordination: who is leader, which config is current, and which process holds a lock.
Press Play on a diagram to walk through it one step at a time.
- 1Heartbeat timeout, become candidateNode A to Node A: Heartbeat timeout, become candidate
- Node A to Node B: RequestVote (term 5)2RequestVote (term 5)
- Node A to Node C: RequestVote (term 5)3RequestVote (term 5)
- Node B to Node A: Vote granted4Vote granted
- 5Majority reached, become leaderNode A to Node A: Majority reached, become leader
- Node A to Node B: Heartbeat / AppendEntries6Heartbeat / AppendEntries
- Node A to Node C: Heartbeat / AppendEntries7Heartbeat / AppendEntries
- Client 1 to Lock service: Acquire lock1Acquire lock
- Lock service to Client 1: Granted, token 332Granted, token 33
- Client 1 to Storage: Write with token 333Write with token 33
- 4Reject any token below 33Storage to Storage: Reject any token below 33
- 1Follower
Accepts entries, waits for heartbeats
- 2Candidate
Election timeout: new term, ask for votes
- 3Leader
Won a majority, sends heartbeats
- 4Steps down
Sees a higher term, becomes follower
- Back to step 1
In depth
What consensus actually solves
Consensus means a group of nodes agrees on a value so that every node that decides picks the same value, the value was proposed by someone, and eventually the healthy nodes decide. Repeat that for every slot in a log and you get a replicated log: every node applies the same commands in the same order and ends in the same state. This is called state machine replication.
That one tool solves many problems: electing exactly one leader, assigning unique increasing IDs, storing cluster membership and config atomically, and implementing locks.
There is a theoretical limit, the FLP result: in a fully asynchronous network, no deterministic algorithm can guarantee it always finishes if even one node may crash. Real algorithms like Raft and Paxos stay always safe (never disagree) and use timeouts to make progress whenever the network behaves reasonably.
Raft log replication
In Raft, all writes go to the leader. The leader appends the command to its log with the current term number and sends it to followers in AppendEntries messages, which also serve as heartbeats. When a majority (including the leader) has stored the entry, the leader marks it committed, applies it to its state machine and replies to the client. Followers learn the new commit index in later messages and apply the entry too.
Two rules keep this safe. The election restriction: a node only votes for a candidate whose log is at least as up to date as its own, so a new leader always has every committed entry. And log matching: each AppendEntries carries the index and term of the previous entry; if a follower's log does not match, it rejects the message and the leader backs up until the logs agree, overwriting the follower's uncommitted extras.
- Client to Leader: SET x = 51SET x = 5
- Leader to Follower 1: AppendEntries index 8, term 32AppendEntries index 8, term 3
- Leader to Follower 2: AppendEntries index 8, term 33AppendEntries index 8, term 3
- Follower 1 to Leader: Stored4Stored
- 52 of 3 stored: commit index 8Leader to Leader: 2 of 3 stored: commit index 8
- Leader to Client: OK6OK
- Leader to Follower 2: Next heartbeat carries commit index 87Next heartbeat carries commit index 8
Sizing a consensus cluster
A cluster of N nodes needs a majority of floor(N/2) + 1 to make progress, so it tolerates floor((N-1)/2) failures: 3 nodes tolerate 1, 5 tolerate 2, 7 tolerate 3. An even number adds cost without adding tolerance: 4 nodes need 3 for a majority and still survive only 1 failure.
More nodes are not free. Every write waits for a majority, so more members and longer distances mean slower writes. 3 or 5 members is typical for etcd and ZooKeeper.
Placement matters as much as count. Put members in different availability zones so one zone failure leaves a majority. With 5 nodes across 3 zones (2, 2, 1), losing any one zone leaves at least 3. Spreading members across regions survives a region loss but adds tens of milliseconds to every write, because each write waits for a cross-region round trip.
- 3 nodes: tolerate 1 failure; 5 nodes: tolerate 2
- Even sizes add cost, not tolerance
- Spread members across zones so no zone holds a majority
etcd and ZooKeeper in practice
etcd is a key-value store built on Raft. Kubernetes stores all its cluster state in it. It offers watches (get notified when a key changes), leases (keys that vanish if the owner stops sending keep-alives) and transactions (compare-and-set). Leader election uses a lease: the first process to create the leader key with its lease wins, and if it dies, the lease expires and the key disappears. etcdctl even has lock and elect commands. Keep data small: etcd is designed for megabytes to a few gigabytes of metadata, with a default storage quota of 2 GB.
ZooKeeper uses its own protocol, ZAB, and stores data in a tree of znodes. Ephemeral znodes vanish when the client session ends, and sequential znodes get an increasing number, which gives a classic election recipe: lowest number wins. Kafka used ZooKeeper for years, but Kafka 4.0 removed it in favour of KRaft, its built-in Raft.
Distributed locks done safely
A distributed lock lets only one process at a time do some work. Locks must expire, or a crashed holder would block everyone forever, so they are leases with a time limit. That creates the classic danger: a process gets the lock, pauses for 40 seconds in a garbage collection or a slow disk write, the lease expires, another process gets the lock, and then the first wakes up and writes, believing it still holds the lock.
The fix is a fencing token: a number that increases each time the lock is granted. The holder sends it with every write, and the storage rejects any token lower than the highest it has seen. etcd's key revision and ZooKeeper's zxid can serve as tokens.
Ask what the lock is for. If it only avoids duplicate work, a simple Redis lock with an expiry is fine. If correctness depends on it, use a consensus-backed lock plus fencing.
- Avoid doing the same job twice
- A rare double run is acceptable
- Redis SET NX with expiry is enough
- Example: one cron runner
- Two holders would corrupt data
- Needs consensus (etcd, ZooKeeper)
- Must use fencing tokens
- Example: one writer to a file
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Explain what consensus solves~45m
- 2Walk through Raft leader election~45m
- 3Know when to use etcd or ZooKeeper~45m
- 4Use distributed locks with fencing tokens~45m
Key points
- Consensus needs a majority, so 5 nodes tolerate 2 failures.
- Raft elects a leader per term; the leader replicates a log to followers.
- Use etcd or ZooKeeper for leader election, config and locks, not bulk data.
- Distributed locks can expire mid-work; fencing tokens stop stale holders.
Key terms
Tap a card to flip it. 0/5 known
Examples
Leader election and locks with etcdctl
Step 1: grant a lease with a 10 second TTL. Step 2: create the leader key only if it does not exist, attached to the lease, in one transaction. Step 3: the winner runs keep-alive to renew the lease; if the process dies, the lease expires and the key vanishes, so another node can win. Step 4: for simple cases, etcdctl has built-in elect and lock commands that do this for you and hold until the process is stopped.
etcdctl lease grant 10
# lease 694d7d1e2f3a0b11 granted with TTL(10s)
etcdctl txn --interactive
# compares: create("/svc/leader") = "0"
# success: put /svc/leader node-a --lease=694d7d1e2f3a0b11
etcdctl lease keep-alive 694d7d1e2f3a0b11
# built-in helpers
etcdctl elect svc-election node-a
etcdctl lock nightly-report-lock ./run_report.shWhy a 4-node cluster is worse than a 3-node one
Step 1: 3 nodes need 2 for a majority, so they survive 1 failure. Step 2: 4 nodes need 3 for a majority, so they also survive only 1 failure. Step 3: but with 4 nodes, more machines can fail, so the chance that 2 fail together is higher, and every write must wait for 3 acknowledgements instead of 2. Step 4: if the 4 nodes are split 2 and 2 across two zones and the link between zones breaks, neither side has a majority and the cluster stops. So go from 3 straight to 5, and spread across 3 zones.
Quick reference
- Majority = floor(N/2) + 1; tolerated failures = floor((N-1)/2)
- Use odd sizes: 3 nodes tolerate 1 failure, 5 tolerate 2
- Raft: leader appends, majority stores, then the entry is committed
- A node only votes for a candidate whose log is at least as up to date
- etcd: watches, leases, transactions; default storage quota 2 GB; keep data small
- ZooKeeper: ephemeral and sequential znodes; Kafka 4.0 replaced it with KRaft
- Locks are leases; protect real correctness with fencing tokens
Common mistakes
- Running consensus with an even number of nodes, gaining no extra fault tolerance.
- Trusting a lock lease without fencing after a long GC pause.
- Storing large application data in etcd or ZooKeeper.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Fill in the majority size and tolerated failures for clusters of 1, 2, 3, 4, 5 and 6 nodes.
- Exercise 2medium
A 5-node etcd cluster must survive the loss of any single availability zone. How do you place the nodes across 3 zones, and why not 2 zones?
- Exercise 3hard
Write pseudocode for a storage service that enforces fencing tokens on writes to a file, and show how it blocks a client whose lock expired.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between Raft and Paxos?
- Both solve the same problem with similar guarantees. Raft was designed to be easier to understand and implement, with a strong leader and clear election rules, so most new systems (etcd, Consul, CockroachDB, Kafka KRaft) use Raft.
- Can I use Redis for distributed locks?
- Yes for efficiency, such as making sure a job usually runs once, using SET key value NX PX 30000. For locks that protect correctness, prefer a consensus-backed store and fencing tokens, because Redis locks can be held by two clients after failovers or long pauses.
- Why not run consensus on every database write?
- Each consensus write waits for a majority round trip, which limits throughput and adds latency. Systems use it for the critical metadata (who leads, what the config is) and often for replicated logs within each shard, not one global log for everything.