๐Ÿ—๏ธ Architecture

Consensus

Consensus Algorithm / Consensus Algorithm

A mechanism by which multiple nodes in a distributed system agree on the same value or state. Guarantees consistency across the whole system even under network delays, message loss, and node failures. Raft, Paxos, and PBFT are representative algorithms, and it is a core technology for distributed databases, blockchains, and cluster coordination services.

๐Ÿ“– 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.

๐Ÿ“Š Algorithm Comparison

Comparison of Major Consensus Algorithms

Algorithm Failure Type Node Requirement Latency Primary Use
Raft CFT (Crash) 2f+1 1 RTT etcd, Consul, TiKV
Paxos CFT (Crash) 2f+1 2 RTT Google Chubby, Spanner
PBFT BFT (Byzantine) 3f+1 3 RTT Hyperledger Fabric
Tendermint BFT (Byzantine) 3f+1 2 RTT Cosmos, Binance Chain
HotStuff BFT (Byzantine) 3f+1 3 RTT (pipelined) Meta Diem (Libra)
Nakamoto BFT (probabilistic) >50% hash power ~10 minutes (6 confirmations) Bitcoin

Recommended Algorithms by Use Case

Use case Recommended Algorithm Reason
Distributed configuration store Raft Simple implementation, strong consistency
Distributed database Raft / Multi-Paxos Guaranteed transaction ordering
Permissioned blockchain PBFT / Tendermint Byzantine fault tolerance
Public blockchain PoW / PoS Trustless environment

โœ… Selection guide: For internal systems (trusted nodes), choose Raft; for public networks (untrusted), choose the BFT family. BFT has high node and communication overhead, so use it only when necessary.

๐Ÿ’ป 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.

๐Ÿ”— Related Terms

๐Ÿ“š Learn More