SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Consensus Algorithms

How a group of machines agrees on one value, even when some of them fail.

⏱ 14 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Consensus means getting several machines to agree on one value, even when some machines crash and messages get lost or delayed.

  • Agreement is needed for things like who is the leader, which write comes next or who holds a lock.
  • The main trick is the majority vote (quorum): a decision counts only when more than half of all nodes accept it.
  • Two majorities always overlap, so two different answers can never both win. Well-known protocols: Paxos, Raft and ZAB.

02Concept: What is it?

One machine can decide alone. But one machine is a single point of failure. So we use a group, and the group must act like one reliable machine. That needs every healthy node to end up with the same answer, and that answer must have been proposed by someone, not invented.

A consensus algorithm promises three things:

  1. Agreement (safety): no two nodes decide different values.
  2. Validity (safety): the decided value was really proposed by some node.
  3. Termination (liveness): every working node eventually decides.

The hard part is that the network is unreliable and nobody can tell a slow node from a dead one. A famous result, the FLP impossibility, says no algorithm can guarantee all three in a fully asynchronous network if even one node may crash. Real protocols therefore always protect safety (never agree on two things) and give up liveness for a while when the network is bad. They use timeouts to make progress most of the time.

The majority rule
5 nodes, majority = 3
πŸ–₯️N1
πŸ–₯️N2
πŸ–₯️N3
πŸ–₯️N4
πŸ–₯️N5
Network cut: 3 and 2
3 nodesmajority: can decide
2 nodesno majority: waits
Has a majority Must wait
Any two groups of 3 out of 5 share at least one node. That shared node stops two different decisions.
🧠Safe first, fast second
When a consensus group cannot reach a majority, it stops instead of guessing. A stuck cluster is annoying. Two clusters that disagree can corrupt data.

03Real-Life Example

🍡A Jury That Must Be Unanimous or Majority
A town picks its mayor by a council of 5. Messengers carry the votes, but some messengers get lost and some councillors are away. The rule is: a person becomes mayor only when 3 councillors have signed for them. If the road is cut and only 2 councillors can talk to each other, they cannot make anyone mayor, and that is correct. On the other side of the cut, the 3 can. Two mayors can never be chosen, because any 3 and any other 3 must share a councillor, and that councillor signs only once per term.
The council
Consensus
Councillor
A node in the cluster
Picking the mayor
Agreeing on a value, such as a leader
3 signatures out of 5
A majority (quorum)
A signature given only once per term
A node votes once per round or term
Messenger lost on the road
A dropped or delayed message
Councillors cut off by a flood
A network partition
Waiting when no majority can be found
Giving up liveness to keep safety
One round of agreement, simplified
πŸ™‹Proposea node suggests a value
→↓
πŸ—³οΈVotenodes accept or refuse
→↓
βœ…Majority?more than half agree
→↓
πŸ“£Commiteveryone learns it

04Why Do We Need It?

πŸ‘‘One leader, always
Clusters must agree on exactly one leader, or two leaders will accept conflicting writes (split brain).
πŸ“’A single order of events
Replicas must apply writes in the same order, or their data drifts apart.
πŸ”’Locks that really lock
A lock service must give a lock to one client, even when servers fail.
βš™οΈShared configuration
Every node must see the same settings and membership list.
πŸ›‘οΈNo single point of failure
A small group of nodes can lose a member and keep working.
🧩A base for bigger systems
Strongly consistent databases and coordination services are built on consensus.
Consensus lets a group of unreliable machines behave like one reliable machine, as long as a majority is alive and connected.

05Where Do We Use It?

🧭Coordination services
ZooKeeper (ZAB), etcd (Raft) and Consul (Raft) store small, critical data for other systems.
☸️Kubernetes
The cluster state lives in etcd, which uses Raft.
πŸ—„οΈDistributed SQL databases
Spanner (Paxos), CockroachDB and TiDB (Raft) agree on each write across replicas.
πŸ“¨Message systems
Kafka (KRaft mode) and other brokers use consensus for metadata and leaders.
πŸ”Distributed locks
Locks and leases that survive node crashes rest on consensus.
⛓️Blockchains
Different consensus rules (proof of work, proof of stake, BFT) let strangers agree on a ledger.

06Types / Parts / How It Works

Families of consensus

Crash faults and Byzantine faults
Crash fault tolerant (CFT)
Nodes may crash or be slow
Paxos, Raft, ZAB
needs 2f + 1 nodes to survive f crashes
Byzantine fault tolerant (BFT)
Nodes may lie or attack
PBFT, Tendermint, HotStuff
needs 3f + 1 nodes to survive f liars
Most company systems only expect nodes to stop. Open networks must also expect nodes that lie.

Common algorithms

AlgorithmIdeaUsed by
PaxosProposers ask acceptors in two phases. A majority accepts.Google Chubby and Spanner, many internal systems
Multi-PaxosPick a stable leader, and skip the first phase for later values.Most production Paxos systems
RaftA clear leader, a replicated log and simple rules. Made to be easy to understand.etcd, Consul, CockroachDB, TiKV
ZABA leader orders updates and broadcasts them. Similar to Raft.Apache ZooKeeper
PBFT / TendermintThree message rounds that tolerate lying nodes.Permissioned blockchains
Proof of work / stakeOpen competition or stake decides who adds the next block.Public blockchains

How many nodes?

Cluster sizeMajorityCrashes survived
321
431 (no better than 3)
532
743
VisualizerMajority vote vs one fixed bossCrash nodes and cut the network in two. See when the cluster can still decide, and how a single boss ends up with two leaders (split brain) while the majority rule never does.
How do the nodes agree?
πŸ–₯️
Node 1
follower
πŸ–₯️
Node 2
follower
πŸ–₯️
Node 3
follower
πŸ–₯️
Node 4
follower
πŸ–₯️
Node 5
follower
Alive
5
of 5 nodes
Majority needed
3
more than half of 5
Can decide?
Yes
needs a majority
Leaders now
1
exactly one
Crashes survived
2
and still decide
5 of 5 nodes are alive and a majority is 3. The cluster can decide. It survives up to 2 crashed node(s).

A simplified picture: a majority is more than half of ALL nodes (not just the ones alive), so two sides of a network cut can never both have one. That is why consensus clusters use an odd size: 3 survive 1 crash, 5 survive 2, 7 survive 3. A real protocol (Paxos, Raft) adds the message rounds that are skipped here.

07How to Use It / Steps / Implementation

Using consensus in a real system

  1. 1
    Do not write your own
    Consensus is very hard to get right. Use etcd, ZooKeeper, Consul or a database that already has Raft or Paxos inside.
  2. 2
    Use an odd number of nodes
    3 or 5 is common. Going from 3 to 4 adds cost and no extra crash tolerance.
  3. 3
    Spread nodes across failure zones
    Put them in different racks or availability zones, so one failure does not take a majority.
  4. 4
    Keep the data small
    Consensus stores are for leaders, locks, configuration and metadata, not for big data.
  5. 5
    Expect delay
    Every write waits for a majority to answer. Across regions, that means cross-region latency.
  6. 6
    Handle 'no majority'
    Clients must handle timeouts and 'no leader' errors with retries and backoff.
  7. 7
    Monitor leaders and quorum
    Alert on frequent leader changes, slow disks (fsync) and a lost quorum.
πŸ’‘Use it for the small, critical decisions
A good design keeps the heavy data in a normal database and uses a small consensus group only to decide who the leader is and where things live.
⚠️Slow disks look like dead nodes
A node that pauses on a slow disk or a long garbage collection can miss heartbeats, and the cluster may elect a new leader again and again. Use fast disks for the log and tune the timeouts.

08Key Terms to Know

TermMeaning in easy words
ConsensusGetting several nodes to agree on one value despite failures
QuorumThe number of nodes that must agree, usually more than half
SafetyNothing bad happens: nodes never decide different values
LivenessSomething good eventually happens: the group does decide
ProposerA node that suggests a value
AcceptorA node that votes on proposals
LearnerA node that is told the final decision
LeaderThe node that drives decisions for a term, so rounds are fast
Term / epoch / ballotA number that grows with each new leader election or attempt
FLP impossibilityA proof that perfect consensus is impossible in a fully asynchronous system with one crash
Byzantine faultA node that behaves in a wrong or lying way, not just crashing

09Pros, Cons and Trade-offs

βœ… Pros
  • Strong consistency: all nodes agree
  • No single point of failure
  • Survives a minority of crashes
  • A solid base for locks, leaders and metadata
  • Well-tested open-source implementations
⚠️ Cons
  • Every decision needs a round trip to a majority
  • Stops when the majority is lost
  • Throughput is limited by the leader
  • Hard to implement and test correctly
  • Latency grows across regions

Trade-offs

ChoiceWe gainWe lose
Bigger clusterSurvives more crashesMore messages and slower writes
Smaller cluster (3)Cheap and fastOnly one crash tolerated
Spread across regionsSurvives a region lossEvery write pays cross-region delay
Leader-based (Raft)Simple and fast in the common caseA leader failure causes a short pause for election
Leaderless / eventual consistencyAlways available, low latencyConcurrent writes and conflicts to resolve
BFT instead of CFTTolerates lying nodesMore nodes, more messages, more complexity

10Common Problems and Mistakes

Common mistakes

  1. Writing your own consensus. Tiny bugs in these protocols cause data loss that only appears in rare failures.
  2. Even-sized clusters. 4 nodes tolerate only 1 crash, the same as 3, and a 2-2 split has no majority at all.
  3. All nodes in one zone. One power failure takes the whole quorum down.
  4. Putting big data through it. The leader becomes a bottleneck.
  5. Reading from followers and expecting fresh data. A follower may be behind the leader.
  6. Timeouts that are too short. Normal delays trigger constant elections.
  7. Forgetting that consensus is not free. Every write costs at least a majority round trip.

Things to watch

πŸŒ—Split brain
Two sides each think they lead. A correct majority rule makes this impossible.
πŸ”Election storms
Leaders keep changing because of slow disks or bad timeouts.
πŸ’ΎDisk durability
Votes must be saved to disk before replying, or a restarted node can vote twice.
πŸ‘₯Membership changes
Adding or removing nodes must itself go through consensus, with care.

11Real-World Examples

☸️Kubernetes and etcd
Every object in a cluster is stored in etcd, which agrees on writes with Raft.
πŸ”’Google Chubby
A Paxos-based lock service that many Google systems depended on.
🌍Google Spanner
Uses Paxos groups to keep copies of data consistent across regions.
🐘Apache ZooKeeper
Provides leader election, configuration and locks to Hadoop, Kafka (older versions) and others.
πŸͺ³CockroachDB and TiDB
Split data into ranges, and each range runs its own Raft group.
⛓️Blockchains
Bitcoin uses proof of work. Tendermint-based chains use a BFT vote.
πŸ“Note
Implementation details change between versions. Read the current docs of each product for exact guarantees.
Mini case: a 3-node etcd cluster loses one node
πŸ–₯️Node 1leader
↔replicate
πŸ–₯️Node 2follower
↔lost
πŸ’₯Node 3down
Two of three is still a majority, so the cluster keeps working.

12Related Topics to Read Next

Paxos→

The classic consensus protocol, step by step.

Raft→

A consensus protocol designed to be easy to follow.

Leader Election→

The most common thing a cluster needs to agree on.

Split Brain Problem→

What goes wrong when two nodes think they lead.

CAP Theorem→

Consensus picks consistency over availability during a partition.

Network Partitions→

The failure that makes the majority rule matter.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: nodes agree on one value, despite crashes and lost messages.
  • βœ”Needs: agreement, validity, termination.
  • βœ”Core trick: a majority vote. Two majorities overlap, so no two answers win.
  • βœ”Size: 2f + 1 nodes survive f crashes. Use 3 or 5. Odd is best.
  • βœ”No majority: stop and wait. Safe but unavailable.
  • βœ”Algorithms: Paxos, Raft, ZAB (crash faults). PBFT, Tendermint (Byzantine).
  • βœ”Use for: leaders, locks, config, metadata. Not for big data.
  • βœ”One line: β€œMore than half must agree, so two answers can never both win.”
← Previous
TrueTime (Google Spanner)
Next β†’
Paxos