| name | consensus-algorithms |
| description | Understand and apply distributed consensus algorithms for leader election, distributed locks, and consistent state. Outputs algorithm selection guide, Raft/Paxos explanation, implementation patterns, and failure scenario analysis. |
| argument-hint | ["cluster size","consistency requirements","network characteristics","failure tolerance"] |
| allowed-tools | Read, Write |
Consensus Algorithms
Consensus algorithms allow distributed nodes to agree on a single value even when some nodes fail. They underpin leader election, distributed locks, configuration management, and any system requiring strong consistency across replicas. Understanding consensus is essential for understanding Kubernetes, etcd, ZooKeeper, and Kafka.
The Consensus Problem
CHALLENGE:
N nodes must agree on a value
Any node can fail (crash or network partition)
No shared memory; only message passing
SAFETY requirements (what must never happen):
Only a single value is decided
A decided value was proposed by some node
LIVENESS requirement (what must eventually happen):
Some value is eventually decided
(Not guaranteed during partition — see CAP theorem)
CAP Theorem:
Consistency (linearisability) + Availability + Partition Tolerance
Choose 2. Consensus algorithms choose CP — consistency over availability.
Raft (Most Understandable)
RAFT ROLES:
Leader: Receives writes; replicates to followers
Follower: Passively replicate from leader
Candidate: Seeking election; in between leader terms
LEADER ELECTION:
1. All nodes start as followers with random election timeout (150-300ms)
2. If no heartbeat received before timeout → become Candidate
3. Increment term; vote for self; request votes from peers
4. Win majority → become Leader for this term
5. Send heartbeats to prevent new elections
LOG REPLICATION:
1. Leader receives write; appends to its log
2. Leader sends AppendEntries to all followers
3. Followers append to their log; acknowledge
4. When majority acknowledge → entry is committed
5. Leader notifies followers of commit; they apply to state machine
KEY PROPERTIES:
- Leader has all committed entries (election guarantee)
- Committed entries never overwritten
- At most one leader per term