๐ Detailed Explanation
Consensus is a fundamental problem in distributed computing. In a system where multiple nodes are connected by a network, all nodes must reach the same decision even when node failures or network partitions occur. As proven by the FLP Impossibility result in 1985, this is theoretically impossible in asynchronous systems, but several algorithms solve it under practical assumptions.
The history of consensus algorithms begins with Paxos, published by Leslie Lamport in 1989. Paxos is mathematically sound but was very difficult to understand and implement. In 2013, Diego Ongaro published Raft, which guarantees the same safety as Paxos while being easier to understand, and it has since been widely adopted in etcd, Consul, and others.
Consensus algorithms are broadly divided into CFT (Crash Fault Tolerant) and BFT (Byzantine Fault Tolerant). CFT handles only failures in which nodes simply stop (Raft, Paxos), while BFT also handles Byzantine failures in which nodes behave maliciously (PBFT, Tendermint). BFT is mainly used in blockchains and requires more nodes (3f+1 vs 2f+1) and more communication overhead than CFT.
In practice, consensus algorithms are at the core of distributed databases (CockroachDB, TiDB), messaging systems (Kafka KRaft, NATS JetStream), service discovery (Consul, etcd), and blockchains (Ethereum, Tendermint). Choosing an algorithm that fits the system requirements determines performance and stability.
Key Properties of Consensus Algorithms
Safety
No incorrect results occur. No nodes agree on different values. Committed values are permanent.
Liveness
The system eventually makes progress. Consensus is reached without waiting indefinitely. Guaranteed when the network is stable.
Fault Tolerance
Operates even when some nodes fail. CFT tolerates f nodes, and BFT tolerates f malicious nodes.
Agreement
All correct nodes agree on the same value. Prevents Split Brain. Guarantees strong consistency.
๐ป Code Example
Raft Consensus Process Simulation (Python)
import random
import time
from enum import Enum
from dataclasses import dataclass
class NodeState(Enum):
FOLLOWER = "follower"
CANDIDATE = "candidate"
LEADER = "leader"
@dataclass
class LogEntry:
term: int
command: str
class RaftNode:
def __init__(self, node_id: str, peers: list):
self.id = node_id
self.peers = peers
self.state = NodeState.FOLLOWER
self.current_term = 0
self.voted_for = None
self.log = []
self.commit_index = 0
def request_vote(self, candidate_term: int, candidate_id: str) -> tuple:
"""ํฌํ ์์ฒญ ์ฒ๋ฆฌ"""
# ํ๋ณด์ Term์ด ์ค๋๋์์ผ๋ฉด ๊ฑฐ๋ถ
if candidate_term < self.current_term:
return self.current_term, False
# ๋ ๋์ Term์ด๋ฉด Follower๋ก ์ ํ
if candidate_term > self.current_term:
self.current_term = candidate_term
self.state = NodeState.FOLLOWER
self.voted_for = None
# ์์ง ํฌํ ์ํ์ผ๋ฉด ํฌํ
if self.voted_for is None or self.voted_for == candidate_id:
self.voted_for = candidate_id
return self.current_term, True
return self.current_term, False
def start_election(self) -> bool:
"""์ ๊ฑฐ ์์"""
self.state = NodeState.CANDIDATE
self.current_term += 1
self.voted_for = self.id
votes = 1 # ์๊ธฐ ์์ ํฌํ
print(f"๐ณ๏ธ [{self.id}] ์ ๊ฑฐ ์์ (Term {self.current_term})")
# ๋ค๋ฅธ ๋
ธ๋์๊ฒ ํฌํ ์์ฒญ (์๋ฎฌ๋ ์ด์
)
for peer in self.peers:
# ์ค์ ๋ก๋ RPC ํธ์ถ
vote_granted = random.random() > 0.3 # 70% ํ๋ฅ ๋ก ํฌํ
if vote_granted:
votes += 1
print(f" โ
{peer}๋ก๋ถํฐ ํฌํ ํ๋")
else:
print(f" โ {peer} ํฌํ ๊ฑฐ๋ถ")
# ๊ณผ๋ฐ์ ๋ํ ์ Leader
quorum = (len(self.peers) + 1) // 2 + 1
if votes >= quorum:
self.state = NodeState.LEADER
print(f"๐ [{self.id}] Leader ๋น์ ! ({votes}/{len(self.peers)+1})")
return True
else:
self.state = NodeState.FOLLOWER
print(f"๐ [{self.id}] ๋์ ({votes}/{len(self.peers)+1})")
return False
def append_entries(self, leader_term: int, entries: list) -> tuple:
"""๋ก๊ทธ ๋ณต์ ์์ฒญ ์ฒ๋ฆฌ"""
if leader_term < self.current_term:
return self.current_term, False
self.current_term = leader_term
self.state = NodeState.FOLLOWER
self.log.extend(entries)
return self.current_term, True
# ์๋ฎฌ๋ ์ด์
์คํ
if __name__ == "__main__":
nodes = {
"node-1": RaftNode("node-1", ["node-2", "node-3", "node-4", "node-5"]),
"node-2": RaftNode("node-2", ["node-1", "node-3", "node-4", "node-5"]),
"node-3": RaftNode("node-3", ["node-1", "node-2", "node-4", "node-5"]),
}
print("=== Raft ํฉ์ ์๋ฎฌ๋ ์ด์
(5๋
ธ๋ ํด๋ฌ์คํฐ) ===\n")
# ๋ฌด์์ ๋
ธ๋๊ฐ ์ ๊ฑฐ ์์
candidate = random.choice(list(nodes.values()))
candidate.start_election()
Checking etcd Cluster Status
# etcd ํด๋ฌ์คํฐ ์ํ ํ์ธ
etcdctl endpoint status --cluster -w table
# ์ถ๋ ฅ ์์:
# +------------------+------------------+---------+---------+-----------+
# | ENDPOINT | ID | VERSION | DB SIZE | IS LEADER |
# +------------------+------------------+---------+---------+-----------+
# | 192.168.1.1:2379 | 8e9e05c52164694d | 3.5.12 | 20 MB | true |
# | 192.168.1.2:2379 | 91bc3c398fb3c146 | 3.5.12 | 20 MB | false |
# | 192.168.1.3:2379 | fd422379fda50e48 | 3.5.12 | 20 MB | false |
# +------------------+------------------+---------+---------+-----------+
# Raft ์ํ ํ์ธ
etcdctl endpoint status -w json | jq '.[] | {endpoint, raftTerm, raftIndex, isLeader}'
# Leader ์ด์ (์ ์ง๋ณด์์ฉ)
etcdctl move-leader 91bc3c398fb3c146
๐ฃ๏ธ Examples of Practical Conversations
๐ฌ In a System Design Interview
"The relationship between the CAP Theorem and consensus? In CAP, P (Partition Tolerance) is mandatory, so you must choose between C (Consistency) and A (Availability). Consensus algorithms like Raft choose CP, and since a majority of nodes must respond to make progress, the minority partition becomes unavailable during a network partition."
๐ฌ In an Architecture Review
"The reason Kafka moved from ZooKeeper to KRaft is to remove the dependency and simplify operations. Previously, ZooKeeper handled broker metadata and Leader election, but in KRaft mode, Kafka itself runs the controller quorum with Raft."
๐ฌ In a Blockchain Project
"It's a permissioned blockchain, so we're using Tendermint, which is PBFT-based. It tolerates fewer than 33% malicious nodes, and because it has instant finality, transaction confirmation is fast. However, as the number of nodes grows, O(nยฒ) communication overhead becomes a problem, so we operate with fewer than 100 nodes."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
โ ๏ธ Cautions
โ Misjudging network partitions: If you misjudge a temporary network delay as a partition, unnecessary Leader elections occur. Set the election timeout to at least 10 times the network RTT.
โ Split Brain: If two Leaders exist at the same time due to incorrect configuration, data inconsistency occurs. Always configure an odd number of nodes (3, 5, 7) and set the quorum to a majority.
โ Confusing CFT with BFT: Applying BFT unnecessarily to an internal system degrades performance. In a trusted environment, Raft (CFT) is sufficient.
โ
The right approach: Place the nodes of a consensus cluster in physically separate Availability Zones (AZs), and monitor disk I/O and network latency. etcd requires p99 fsync to be 10 ms or less.