Skip to content
advancedPhase 48 · Distributed Systems

Leader Election

Elect a single leader for coordination using Raft or similar protocols.

45m
0 problems
Topic Progress0%

Why Leader Election

Why Leader Election

Leader election selects one node to coordinate distributed operations.

The Problem

Without Leader:

Node A: I'll handle this request
Node B: I'll handle this request  (duplicate work!)
Node C: I'll handle this request

Result: Confusion, duplicates, inconsistency

With Leader

With Leader:

Node A: Leader (coordinates)
Node B: Follower (waits)
Node C: Follower (waits)

Result:有序 coordination

Use Cases

Use Case Why Leader Needed
Database replication Single source of truth
Task coordination One coordinator
Configuration management Single authority
Lock management Centralized coordination
Shard assignment Consistent routing

Requirements

  1. Safety: Only one leader at a time
  2. Liveness: Eventually some node becomes leader
  3. Fault tolerance: Leader failure triggers re-election
  4. Performance: Election should be fast

Raft Protocol

Raft Protocol

Raft is a consensus algorithm for leader election and log replication.

Node States

Raft Node States:

1. Follower:
   - Passive state
   - Responds to leader
   - Counts heartbeat timeout

2. Candidate:
   - Active election
   - Requests votes
   - Becomes leader if majority votes

3. Leader:
   - Handles client requests
   - Replicates log
   - Sends heartbeats

Election Process

1. Follower timeout (no heartbeat)
2. Become candidate
3. Increment term
4. Vote for self
5. Request votes from others
6. If majority votes → become leader
7. Send heartbeats to establish authority

Log Replication

Leader receives command:
1. Append to local log
2. Send AppendEntries to followers
3. Followers append to their logs
4. Once majority confirm → commit
5. Apply to state machine
6. Respond to client

Term Concept

Term = logical clock

Term 1: Node A elected
Term 2: Node A fails, Node B elected
Term 3: Split vote, no leader
Term 4: Node C elected

Each term has at most one leader

Raft Safety

1. Election Safety: At most one leader per term
2. Leader Append-Only: Leader never overwrites logs
3. Log Matching: Same index + term = same command
4. Leader Completeness: Committed logs preserved
5. State Machine Safety: Applied in same order

ZooKeeper

ZooKeeper Leader Election

ZooKeeper Concepts

ZooKeeper:
- Distributed coordination service
- Maintains hierarchical namespace (znodes)
- Provides strong consistency
- Used for: leader election, config, locks

Leader Election with ZooKeeper

from kazoo.client import KazooClient
import uuid

class ZooKeeperLeaderElection:
    def __init__(self, zk_hosts, election_path):
        self.zk = KazooClient(hosts=zk_hosts)
        self.election_path = election_path
        self.node_path = None
        self.is_leader = False
    
    def start(self):
        self.zk.start()
        self.zk.ensure_path(self.election_path)
        self.register()
    
    def register(self):
        # Create ephemeral sequential node
        self.node_path = self.zk.create(
            f"{self.election_path}/candidate-",
            value=str(uuid.uuid4()).encode(),
            ephemeral=True,
            sequence=True
        )
        self.watch_predecessor()
    
    def watch_predecessor(self):
        # Get all candidates
        candidates = self.zk.get_children(self.election_path)
        candidates.sort()
        
        # Find my position
        my_index = candidates.index(self.node_path.split('/')[-1])
        
        if my_index == 0:
            # I'm the leader!
            self.become_leader()
        else:
            # Watch predecessor
            predecessor = candidates[my_index - 1]
            @self.zk.DataWatch(f"{self.election_path}/{predecessor}")
            def watch_predecessor(data, stat):
                if stat is None:  # Predecessor gone
                    self.watch_predecessor()
    
    def become_leader(self):
        self.is_leader = True
        print("I am the leader!")

ZooKeeper vs Raft

Aspect ZooKeeper Raft
Implementation Service Algorithm
Usage External service Embedded library
Consistency Strong Strong
Complexity Higher (service) Lower (library)

When to Use

Scenario Recommendation
Existing ZooKeeper Use ZooKeeper
Need embedded Use Raft library
Simple election Redis lock
Strong consistency ZooKeeper/Raft

Practice Problems

0/3solved
Design Leader Election System

Design a scalable Leader Election system. Cover high-level architecture, data model, and API design.

Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliability
Leader Election Scaling

How would you scale Leader Election to handle 10x the current load? Identify bottlenecks and solutions.

Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decomposition
Leader Election Failure Modes

Analyze potential failure modes for Leader Election and design mitigation strategies.

Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradation

Quiz

1. Why is leader election needed?

Question 1 options

2. What are the three Raft node states?

Question 2 options

3. What triggers a Raft election?

Question 3 options

4. What is a Raft term?

Question 4 options

5. What is ZooKeeper used for in leader election?

Question 5 options

Flashcards

Question

Why leader election?

Answer

Single authority for coordination, prevents duplicate work, ensures consistency across nodes

Question

Raft node states?

Answer

Follower (passive), Candidate (electing), Leader (coordinating)

Question

What is Raft term?

Answer

Logical clock that orders events; each term has at most one leader

Question

How Raft election works?

Answer

Follower timeout → Candidate → Request votes → Majority votes → Leader

Question

ZooKeeper leader election?

Answer

Uses ephemeral sequential nodes; candidate watches predecessor; lowest sequence becomes leader

Revision Notes

Key Takeaways

  • 1.Leader election provides single authority for coordination
  • 2.Raft uses terms (logical clocks) with at most one leader per term
  • 3.Election triggered by heartbeat timeout
  • 4.Majority vote required to become leader
  • 5.ZooKeeper uses ephemeral nodes for leader election

Interview Tips

  • Explain why leader election is needed
  • Describe Raft election process
  • Discuss term concept and safety guarantees
  • Compare ZooKeeper vs Raft approaches

Cheat Sheet

Cheat Sheet: Leader Election

Why Leader

  • Coordinate distributed ops
  • Single authority
  • Prevent duplicates

Raft Protocol

States: Follower → Candidate → Leader

  • Election on heartbeat timeout
  • Majority vote required
  • Term = logical clock

ZooKeeper

  • Ephemeral sequential nodes
  • Watch predecessor
  • Lowest sequence = leader

Safety

  • At most 1 leader per term
  • Log matching
  • State machine safety