🏗️ Architecture

Raft

Raft Consensus Algorithm

An algorithm for reaching consensus among nodes in a distributed system. Designed by Diego Ongaro and John Ousterhout in 2013 to address the complexity of Paxos. With "Understandability" as its top goal, it consists of three core mechanisms: Leader Election, Log Replication, and Safety. Used in etcd, Consul, TiKV, CockroachDB, NATS JetStream, and more.

📖 Detailed Explanation

Raft is an abbreviation of "Reliable, Replicated, Redundant, And Fault-Tolerant", an algorithm that allows multiple nodes in a distributed system to reach agreement on the same state. It was published in 2013 by Dr. Diego Ongaro of Stanford University in the paper "In Search of an Understandable Consensus Algorithm".

Before Raft, Paxos was the standard consensus algorithm, but its complexity made correct implementation difficult. While guaranteeing the same safety, Raft decomposed the problem into three independent subproblems to make it easier to understand: Leader Election, Log Replication, and Safety.

Each node in a Raft cluster is in one of three states: Leader, Follower, or Candidate. Under normal circumstances, a single Leader manages all log entries and replicates them to Followers. If the Leader fails, one of the Followers becomes a Candidate and elects a new Leader. This process is carried out by majority (Quorum) vote.

In practice, Raft is used in core infrastructure such as etcd (Kubernetes' configuration store), Consul (service discovery), CockroachDB, TiDB (distributed SQL), HashiCorp Vault, and NATS JetStream. It is configured with an odd number of nodes (3, 5, or 7) and tolerates f node failures (2f+1 nodes required).

Core Mechanisms of Raft

Leader Election

When the heartbeat times out, a Follower transitions to Candidate, and a Leader is elected by majority vote. Leader terms are managed by Term numbers.

Log Replication

The Leader appends client requests to its log and replicates them to Followers. Once replicated to a majority, the entry is committed (applied).

Safety

Only the node with the most up-to-date log can become Leader. Committed logs are never overwritten.

Term

A logical unit of time. It increases with each election. Messages from stale Terms are ignored.

Node State Transition Diagram

┌─────────────┐
│  Follower   │◄──────────────────────────────────┐
└──────┬──────┘                                   │
       │ 타임아웃 (Leader heartbeat 없음)            │
       ▼                                          │
┌─────────────┐  과반수 득표   ┌─────────────┐      │
│  Candidate  │──────────────►│   Leader    │──────┤
└──────┬──────┘              └──────┬──────┘      │
       │                            │              │
       │ 더 높은 Term 발견            │ 더 높은 Term   │
       │ 또는 새 Leader 발견           │  Leader 발견   │
       └──────────────────────────────┴──────────────┘

💻 Code Example

Go - Raft Node Structure (Simplified Implementation)

package raft

import (
    "sync"
    "time"
)

type NodeState int

const (
    Follower NodeState = iota
    Candidate
    Leader
)

type LogEntry struct {
    Term    int
    Index   int
    Command interface{}
}

type RaftNode struct {
    mu sync.Mutex

    // 영속 상태 (모든 서버)
    currentTerm int        // 현재 Term
    votedFor    string     // 현재 Term에서 투표한 후보
    log         []LogEntry // 로그 엔트리

    // 휘발 상태 (모든 서버)
    commitIndex int // 커밋된 최고 로그 인덱스
    lastApplied int // State Machine에 적용된 최고 인덱스

    // 휘발 상태 (Leader만)
    nextIndex  map[string]int // 각 Follower에게 보낼 다음 로그 인덱스
    matchIndex map[string]int // 각 Follower가 복제 완료한 인덱스

    // 노드 메타데이터
    id      string
    peers   []string
    state   NodeState
    leader  string

    // 타이머
    electionTimeout  time.Duration
    heartbeatTimeout time.Duration
    lastHeartbeat    time.Time
}

// RequestVote RPC - 선거 시 투표 요청
type RequestVoteArgs struct {
    Term         int    // 후보의 Term
    CandidateID  string // 후보 ID
    LastLogIndex int    // 후보의 마지막 로그 인덱스
    LastLogTerm  int    // 후보의 마지막 로그 Term
}

type RequestVoteReply struct {
    Term        int  // 현재 Term (후보가 업데이트용)
    VoteGranted bool // 투표 승인 여부
}

func (n *RaftNode) RequestVote(args *RequestVoteArgs, reply *RequestVoteReply) {
    n.mu.Lock()
    defer n.mu.Unlock()

    reply.Term = n.currentTerm
    reply.VoteGranted = false

    // 후보의 Term이 오래되었으면 거부
    if args.Term < n.currentTerm {
        return
    }

    // 더 높은 Term이면 Follower로 전환
    if args.Term > n.currentTerm {
        n.currentTerm = args.Term
        n.state = Follower
        n.votedFor = ""
    }

    // 아직 투표 안했고, 후보의 로그가 최신이면 투표
    if n.votedFor == "" || n.votedFor == args.CandidateID {
        if n.isLogUpToDate(args.LastLogIndex, args.LastLogTerm) {
            n.votedFor = args.CandidateID
            reply.VoteGranted = true
            n.resetElectionTimer()
        }
    }
}

// 후보의 로그가 내 로그보다 최신인지 확인
func (n *RaftNode) isLogUpToDate(lastIndex, lastTerm int) bool {
    myLastIndex := len(n.log) - 1
    if myLastIndex < 0 {
        return true
    }
    myLastTerm := n.log[myLastIndex].Term

    // Term이 더 크거나, Term 같고 Index가 같거나 크면 최신
    return lastTerm > myLastTerm ||
           (lastTerm == myLastTerm && lastIndex >= myLastIndex)
}

// AppendEntries RPC - 로그 복제 및 Heartbeat
type AppendEntriesArgs struct {
    Term         int        // Leader의 Term
    LeaderID     string     // Leader ID
    PrevLogIndex int        // 새 로그 직전 인덱스
    PrevLogTerm  int        // 직전 로그의 Term
    Entries      []LogEntry // 복제할 로그 (Heartbeat 시 빈 배열)
    LeaderCommit int        // Leader의 commitIndex
}

type AppendEntriesReply struct {
    Term    int  // 현재 Term
    Success bool // 로그 일치 여부
}

func (n *RaftNode) AppendEntries(args *AppendEntriesArgs, reply *AppendEntriesReply) {
    n.mu.Lock()
    defer n.mu.Unlock()

    reply.Term = n.currentTerm
    reply.Success = false

    // 오래된 Leader의 요청은 거부
    if args.Term < n.currentTerm {
        return
    }

    // 유효한 Leader를 발견하면 Follower로 전환
    if args.Term >= n.currentTerm {
        n.currentTerm = args.Term
        n.state = Follower
        n.leader = args.LeaderID
    }
    n.resetElectionTimer()

    // 로그 일관성 검사
    if args.PrevLogIndex >= 0 {
        if args.PrevLogIndex >= len(n.log) ||
           n.log[args.PrevLogIndex].Term != args.PrevLogTerm {
            return // 로그 불일치
        }
    }

    // 로그 추가 (충돌 시 덮어쓰기)
    for i, entry := range args.Entries {
        idx := args.PrevLogIndex + 1 + i
        if idx < len(n.log) {
            if n.log[idx].Term != entry.Term {
                n.log = n.log[:idx] // 충돌 이후 삭제
            }
        }
        if idx >= len(n.log) {
            n.log = append(n.log, entry)
        }
    }

    // commitIndex 업데이트
    if args.LeaderCommit > n.commitIndex {
        lastNewIndex := args.PrevLogIndex + len(args.Entries)
        if args.LeaderCommit < lastNewIndex {
            n.commitIndex = args.LeaderCommit
        } else {
            n.commitIndex = lastNewIndex
        }
        n.applyCommittedEntries()
    }

    reply.Success = true
}

etcd Client (Go)

package main

import (
    "context"
    "fmt"
    "time"

    clientv3 "go.etcd.io/etcd/client/v3"
)

func main() {
    // etcd 클러스터 연결 (3노드 Raft)
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{"localhost:2379", "localhost:2380", "localhost:2381"},
        DialTimeout: 5 * time.Second,
    })
    if err != nil {
        panic(err)
    }
    defer cli.Close()

    ctx := context.Background()

    // 키-값 저장 (Raft로 복제됨)
    _, err = cli.Put(ctx, "/services/api/config", `{"port": 8080}`)
    if err != nil {
        panic(err)
    }
    fmt.Println("✅ 설정 저장 완료 (Raft 합의 완료)")

    // 키-값 조회
    resp, _ := cli.Get(ctx, "/services/api/config")
    for _, kv := range resp.Kvs {
        fmt.Printf("📦 Key: %s, Value: %s\n", kv.Key, kv.Value)
    }

    // Leader 정보 확인
    status, _ := cli.Status(ctx, "localhost:2379")
    fmt.Printf("🎯 Leader ID: %d\n", status.Leader)
    fmt.Printf("📊 Raft Term: %d\n", status.RaftTerm)
    fmt.Printf("📝 Raft Index: %d\n", status.RaftIndex)

    // Watch (변경 감지)
    watchCh := cli.Watch(ctx, "/services/", clientv3.WithPrefix())
    go func() {
        for wresp := range watchCh {
            for _, ev := range wresp.Events {
                fmt.Printf("🔔 [%s] %s = %s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
            }
        }
    }()
}

📊 Performance & Comparison

Raft vs Other Consensus Algorithms

Characteristics Raft Paxos PBFT Zab (ZooKeeper)
Understandability High ⭐ Low Medium Medium
Fault Tolerance f (2f+1 nodes) f (2f+1 nodes) f (3f+1 nodes) f (2f+1 nodes)
Byzantine Faults ❌ Not supported ❌ Not supported ✅ Supported ❌ Not supported
Leader-Based ✅ Strong leader △ Multiple proposers ✅ Primary ✅ Leader
Latency 1 RTT (leader→follower) 2 RTT 3 RTT 1 RTT
Major Implementations etcd, Consul, TiKV Chubby, Spanner Tendermint, Hyperledger ZooKeeper

Characteristics by Raft Cluster Size

Number of Nodes Majority (Quorum) Tolerated Failures Recommended Use Cases
3 2 1 Development/testing, small-scale production
5 3 2 Production recommended
7 4 3 Global distribution, high availability

✅ Practical tip: We recommend a 5-node cluster in production. A 3-node cluster tolerates only 1 failure, so if an additional failure occurs during a rolling update, the service will go down.

🗣️ Examples of Practical Conversations

💬 In a Kubernetes operations meeting

"Our etcd cluster has 3 nodes, and I think we should expand it to 5. It currently tolerates only 1 node failure, and if an additional failure occurs during a rolling update, we lose the Raft majority and the whole cluster becomes read-only."

💬 In a technical interview

"The principle for preventing split brain in Raft? Majority (Quorum) voting. Even if a network partition occurs, only the partition that holds a majority can elect a Leader. The existing Leader in the minority partition can't receive Heartbeat responses, so it is demoted to Follower."

💬 In a Failure Analysis Meeting

"The cause of the etcd latency spike is a disk I/O bottleneck. Raft must fsync the WAL (Write-Ahead Log) to disk before committing, and on a slow disk the Leader waits for Follower responses and times out. You need to replace it with an NVMe SSD or allocate a dedicated disk for etcd."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

❌ Even-numbered node clusters: A 4-node cluster has the same fault tolerance as a 3-node cluster (1 failure). It only adds cost with no benefit, so configure with an odd number (3, 5, 7).

❌ Slow disks: Raft requires a WAL fsync before commit. Slow disks cause Leader election failures, increased latency, and cluster instability. SSDs are required.

❌ Network latency imbalance: The Raft Leader waits for the fastest majority of responses. If latency varies widely between nodes, some nodes keep falling behind and Leader election becomes unstable.

✅ Correct approach: For etcd, monitor cluster health with etcdctl endpoint health, and sync Followers with a large Raft index gap using a snapshot.

🔗 Related Terms

📚 Learn More