πŸ—οΈ Architecture

Leader Election

Leader Election / Leader Selection

An algorithm that elects one node as leader in a distributed system. The leader handles roles such as coordinating tasks, determining request processing order, and managing data replication. Implemented through Raft consensus, the Bully Algorithm, distributed locks via ZooKeeper/etcd, and more, it is central to distributed databases, message queues, and cluster coordination.

πŸ“– Detailed Explanation

Leader Election is one of the most fundamental problems in distributed systems. When multiple nodes perform the same task at the same time, conflicts occur, so one node is elected as the leader to coordinate the work. The leader receives and processes client requests and replicates the results to the other nodes.

There are broadly three reasons why leader election is needed. First, write ordering guarantees. When concurrent write requests come in, the leader determines the order to maintain consistency. Second, replication coordination. The leader propagates data changes to followers to synchronize the state of all nodes. Third, failure recovery. If the leader fails, a new leader is elected to ensure service continuity.

A representative leader election algorithm is Raft. Raft elects a leader through heartbeat timeouts and majority voting, and is used in etcd, Consul, TiKV, and others. Another approach is to use ephemeral nodes and distributed locks in ZooKeeper/etcd. The node that acquires the lock first becomes the leader, and if it loses the lock, another node becomes the leader.

In practice, leader election is used in Kafka's partition leaders, the Kubernetes controller manager, the Primary node of distributed databases, the master of schedulers, and more. The choice of leader election algorithm is determined by failover time, network topology, and consistency requirements.

Scenarios Requiring Leader Election

Database Primary

Handles write requests and replicates them to Replicas. MySQL Group Replication, PostgreSQL Patroni.

Message Queue Partitions

One Leader broker per Kafka partition handles Producer/Consumer requests.

Distributed Job Scheduler

Only one master assigns jobs. Prevents duplicate execution. Kubernetes controller-manager.

Distributed Lock Service

Coordinates access to global resources. Only one client at a time enters the critical section.

πŸ’» Code Example

Leader Election with etcd (Go)

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"

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

func main() {
    nodeID := os.Getenv("NODE_ID")
    if nodeID == "" {
        nodeID = "node-1"
    }

    // etcd ν΄λΌμ΄μ–ΈνŠΈ μ—°κ²°
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{"localhost:2379"},
        DialTimeout: 5 * time.Second,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer cli.Close()

    // μ„Έμ…˜ 생성 (TTL 10초 - 리더 μž₯μ•  감지 μ‹œκ°„)
    session, err := concurrency.NewSession(cli, concurrency.WithTTL(10))
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()

    // Election 객체 생성
    election := concurrency.NewElection(session, "/leader/scheduler")

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // μ‹œκ·Έλ„ 핸듀링
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

    go func() {
        <-sigCh
        fmt.Printf("[%s] μ’…λ£Œ μ‹ ν˜Έ μˆ˜μ‹ , 리더 μ‚¬μž„\n", nodeID)
        election.Resign(ctx)
        cancel()
    }()

    // 리더 μ„ μΆœ μ‹œλ„ (λΈ”λ‘œν‚Ή)
    fmt.Printf("[%s] 리더 μ„ μΆœ λŒ€κΈ° 쀑...\n", nodeID)
    if err := election.Campaign(ctx, nodeID); err != nil {
        log.Fatal(err)
    }

    // λ¦¬λ”λ‘œ μ„ μΆœλ¨!
    fmt.Printf("πŸ‘‘ [%s] λ¦¬λ”λ‘œ μ„ μΆœλ¨!\n", nodeID)

    // 리더 μž‘μ—… μˆ˜ν–‰
    for {
        select {
        case <-ctx.Done():
            return
        case <-time.After(1 * time.Second):
            // ν˜„μž¬ 리더 확인
            resp, _ := election.Leader(ctx)
            if resp != nil && len(resp.Kvs) > 0 {
                fmt.Printf("[%s] ν˜„μž¬ 리더: %s (Lease: %d)\n",
                    nodeID, string(resp.Kvs[0].Value), resp.Kvs[0].Lease)
            }

            // 리더 μž‘μ—… (예: μŠ€μΌ€μ€„λ§)
            fmt.Printf("[%s] πŸ”§ 리더 μž‘μ—… μˆ˜ν–‰ 쀑...\n", nodeID)
        }
    }
}

Leader Election with ZooKeeper (Java)

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class LeaderElectionExample extends LeaderSelectorListenerAdapter {
    private final String nodeId;
    private final LeaderSelector leaderSelector;

    public LeaderElectionExample(CuratorFramework client, String path, String nodeId) {
        this.nodeId = nodeId;
        this.leaderSelector = new LeaderSelector(client, path, this);
        // 리더 μ’…λ£Œ ν›„ μžλ™ μž¬μ„ κ±° μ°Έμ—¬
        this.leaderSelector.autoRequeue();
    }

    public void start() {
        leaderSelector.start();
    }

    @Override
    public void takeLeadership(CuratorFramework client) throws Exception {
        // λ¦¬λ”λ‘œ μ„ μΆœλ¨ - 이 λ©”μ„œλ“œκ°€ λ°˜ν™˜λ˜λ©΄ 리더십 상싀
        System.out.println("πŸ‘‘ [" + nodeId + "] λ¦¬λ”λ‘œ μ„ μΆœλ¨!");

        try {
            while (true) {
                // 리더 μž‘μ—… μˆ˜ν–‰
                System.out.println("[" + nodeId + "] πŸ”§ 리더 μž‘μ—… μˆ˜ν–‰ 쀑...");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("[" + nodeId + "] 리더십 μ’…λ£Œ");
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) throws Exception {
        String nodeId = System.getenv().getOrDefault("NODE_ID", "node-1");

        CuratorFramework client = CuratorFrameworkFactory.newClient(
            "localhost:2181",
            new ExponentialBackoffRetry(1000, 3)
        );
        client.start();

        LeaderElectionExample example = new LeaderElectionExample(
            client, "/leader/scheduler", nodeId
        );
        example.start();

        System.out.println("[" + nodeId + "] 리더 μ„ μΆœ λŒ€κΈ° 쀑...");
        Thread.currentThread().join();
    }
}

Kubernetes Leader Election (Go)

package main

import (
    "context"
    "fmt"
    "os"
    "time"

    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/leaderelection"
    "k8s.io/client-go/tools/leaderelection/resourcelock"
)

func main() {
    nodeID := os.Getenv("POD_NAME")
    namespace := os.Getenv("POD_NAMESPACE")

    // ν΄λŸ¬μŠ€ν„° λ‚΄λΆ€ μ„€μ •
    config, _ := rest.InClusterConfig()
    clientset, _ := kubernetes.NewForConfig(config)

    // Lease 기반 λ¦¬μ†ŒμŠ€ 락
    lock := &resourcelock.LeaseLock{
        LeaseMeta: metav1.ObjectMeta{
            Name:      "my-controller-leader",
            Namespace: namespace,
        },
        Client: clientset.CoordinationV1(),
        LockConfig: resourcelock.ResourceLockConfig{
            Identity: nodeID,
        },
    }

    ctx := context.Background()

    // Leader Election μ‹€ν–‰
    leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
        Lock:            lock,
        LeaseDuration:   15 * time.Second,
        RenewDeadline:   10 * time.Second,
        RetryPeriod:     2 * time.Second,
        Callbacks: leaderelection.LeaderCallbacks{
            OnStartedLeading: func(ctx context.Context) {
                // 리더가 λ˜μ—ˆμ„ λ•Œ μ‹€ν–‰
                fmt.Printf("πŸ‘‘ [%s] λ¦¬λ”λ‘œ μ„ μΆœλ¨!\n", nodeID)
                runController(ctx)
            },
            OnStoppedLeading: func() {
                // 리더십을 μžƒμ—ˆμ„ λ•Œ
                fmt.Printf("πŸ˜” [%s] 리더십 상싀\n", nodeID)
                os.Exit(0)
            },
            OnNewLeader: func(identity string) {
                if identity != nodeID {
                    fmt.Printf("πŸ“’ μƒˆ 리더 μ„ μΆœ: %s\n", identity)
                }
            },
        },
    })
}

func runController(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            return
        case <-time.After(1 * time.Second):
            fmt.Println("πŸ”§ 컨트둀러 μž‘μ—… μˆ˜ν–‰ 쀑...")
        }
    }
}

Simple Leader Election with Redis

import redis
import time
import uuid
import signal
import sys

class RedisLeaderElection:
    def __init__(self, redis_client, lock_name, ttl=10):
        self.redis = redis_client
        self.lock_name = lock_name
        self.ttl = ttl
        self.node_id = str(uuid.uuid4())[:8]
        self.is_leader = False

    def try_become_leader(self):
        """리더 되기 μ‹œλ„ (SET NX EX)"""
        acquired = self.redis.set(
            self.lock_name,
            self.node_id,
            nx=True,  # ν‚€κ°€ 없을 λ•Œλ§Œ μ„€μ •
            ex=self.ttl  # TTL μ„€μ •
        )
        self.is_leader = bool(acquired)
        return self.is_leader

    def renew_leadership(self):
        """리더십 κ°±μ‹  (TTL μ—°μž₯)"""
        if not self.is_leader:
            return False

        # Lua 슀크립트둜 μ›μžμ  κ°±μ‹  (μ†Œμœ κΆŒ 확인 + TTL μ—°μž₯)
        script = """
        if redis.call('get', KEYS[1]) == ARGV[1] then
            return redis.call('expire', KEYS[1], ARGV[2])
        else
            return 0
        end
        """
        result = self.redis.eval(script, 1, self.lock_name, self.node_id, self.ttl)
        self.is_leader = bool(result)
        return self.is_leader

    def resign(self):
        """리더십 μ‚¬μž„"""
        script = """
        if redis.call('get', KEYS[1]) == ARGV[1] then
            return redis.call('del', KEYS[1])
        else
            return 0
        end
        """
        self.redis.eval(script, 1, self.lock_name, self.node_id)
        self.is_leader = False

    def get_current_leader(self):
        """ν˜„μž¬ 리더 확인"""
        return self.redis.get(self.lock_name)


def main():
    redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
    election = RedisLeaderElection(redis_client, "leader:scheduler")

    def signal_handler(sig, frame):
        print(f"[{election.node_id}] μ’…λ£Œ μ‹ ν˜Έ μˆ˜μ‹ ")
        election.resign()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    print(f"[{election.node_id}] 리더 μ„ μΆœ μ‹œμž‘")

    while True:
        if election.is_leader:
            # 리더십 κ°±μ‹ 
            if election.renew_leadership():
                print(f"πŸ‘‘ [{election.node_id}] 리더 μž‘μ—… μˆ˜ν–‰ 쀑...")
            else:
                print(f"πŸ˜” [{election.node_id}] 리더십 상싀")
        else:
            # 리더 되기 μ‹œλ„
            if election.try_become_leader():
                print(f"πŸ‘‘ [{election.node_id}] λ¦¬λ”λ‘œ μ„ μΆœλ¨!")
            else:
                leader = election.get_current_leader()
                print(f"[{election.node_id}] λŒ€κΈ° 쀑... (ν˜„μž¬ 리더: {leader})")

        time.sleep(1)


if __name__ == "__main__":
    main()

πŸ“Š Algorithm Comparison

Comparison of Leader Election Methods

Method Failure Detection Election Time Dependency Use case
Raft Consensus Heartbeat timeout ~1-2 seconds None (custom implementation) etcd, Consul, TiKV
ZooKeeper Ephemeral Session timeout ~5-10 seconds ZooKeeper cluster Kafka, HBase
etcd Lease Lease TTL ~TTL etcd cluster Kubernetes controller
Redis SET NX Key TTL ~TTL Redis Simple distributed lock
Bully Algorithm Message timeout O(n) messages None Educational, small-scale

βœ… Selection Guide: If you need strong consistency, use a Raft-based option (etcd, Consul); if you are leveraging existing infrastructure, use ZooKeeper/Redis; and in a Kubernetes environment, use the Lease API.

πŸ—£οΈ Examples of Practical Conversations

πŸ’¬ In an Architecture Review

"To make the scheduler HA, we need leader election. If we elect a leader using an etcd Lease and only the leader schedules jobs, we can prevent duplicate execution. Setting the TTL to 10 seconds also gives reasonable failure detection."

πŸ’¬ In Failure Analysis

"The cause of the leader election flapping is network jitter. The Lease TTL is 5 seconds, but renewals were intermittently delayed, so the leader repeatedly lost leadership and was re-elected. If we increase the TTL to 15 seconds and set the renewal interval to 5 seconds, it should stabilize."

πŸ’¬ In a technical interview

"How do we prevent Split Brain? The key is a majority (Quorum). During a network partition, only the partition that secures a majority can elect a leader. If both partitions are below a majority, there will be no leader, but that is safer than having two leaders at the same time."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

❌ Split Brain: If two leaders exist during a network partition, data inconsistency occurs. Be sure to use majority-based election and implement fencing.

❌ Leader Flapping: If the TTL is too short or the network is unstable, the leader changes frequently. Set the TTL to at least 10 times the network RTT and the renewal interval to at most 1/3 of the TTL.

❌ Single Point of Failure: If the external service used for leader election (etcd, ZooKeeper) fails, the entire system is affected. Configure that service for HA as well.

βœ… The Right Approach: Implement a graceful handoff that completes or rolls back in-progress work when the leader changes. When leadership is lost, stop work immediately and hand it over to the new leader.

πŸ”— Related Terms

πŸ“š Learn More