π 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()