Chaturmind
LearnDSASystem DesignDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Low-Level Design & Design Patterns

OOP Fundamentals & SOLID Principles

  • Object-Oriented Design Refresher
  • Single Responsibility & Open/Closed
  • Liskov Substitution & Interface Segregation
  • Dependency Inversion

Creational Design Patterns

  • Singleton Pattern
  • Factory & Abstract Factory
  • Builder Pattern
  • Prototype Pattern

Structural Design Patterns

  • Adapter & Facade
  • Decorator Pattern
  • Composite & Proxy
  • Bridge & Flyweight

Behavioral Design Patterns

  • Strategy Pattern
  • Observer Pattern
  • Command Pattern
  • Template Method
  • State Pattern
  • Chain of Responsibility
  • Iterator & Mediator
  • Visitor Pattern

Machine Coding Exercises

  • Parking Lot — Requirements & Class Design
  • Parking Lot — Implementation
  • Elevator System — Requirements & Class Design
  • Elevator System — Implementation & Scheduling
  • Library Management System
  • Tic-Tac-Toe / Board Game Design
  • Chess Engine Design
  • Vending Machine Design
  • ATM System Design
  • In-Memory Rate Limiter
  • Thread-Safe LRU Cache
  • Connection Pool Design
  • Producer-Consumer Class Design
  • Movie Ticket Booking System
  • Hotel Reservation System
  • Airline Booking / Seat Selection System
  • Splitwise / Expense Sharing System
  • Design a Logging Framework
  • Design a Notification/Observer-Based Pub-Sub
  • Design a Cache with Pluggable Eviction Policy
  • Design Snake and Ladder
  • Design a Card Game Framework
  • Design an Inventory Management System
  • Restaurant Management System
  • Food Delivery Order Matching
  • Design a Shopping Cart & Checkout Flow
  • Design a Recommendation Engine
  • Design a Job Scheduler
  • Design a Circuit Breaker
  • Design a Distributed ID Generator
  • Design a Pub-Sub Message Broker
  • Design Twitter/X
  • Multi-Pattern Problem: Design a Ride Booking Class Model
  • Multi-Pattern Problem: Design a Food Ordering Class Model
  • Design an Authentication/Authorization Module
  • Design a Form/Survey Builder
  • Design a Meeting Room / Calendar Booking System
  • Design a Search/Filter Engine for an E-Commerce Catalog
  • Design a Voting/Polling System
  • Design a Retry Mechanism with Backoff
  • Design a Health Check Aggregator
  • Design a Feature Flag System
  • Design a Config Management Client
  • Design a Leader Election Algorithm
  • Design a Distributed Counter
  • Design a Bloom Filter
  • Design a Consistent Hashing Ring
  • Design a Distributed Tracing Library
  • Design a Metrics Collection Library
  • Design an Audit Logging Framework
  • Design a Plugin/Extension System
  • Design a Workflow Engine
  • Multi-Pattern Capstone: Design a Food Delivery App
Chaturmind
← Low-Level Design & Design Patterns

OOP Fundamentals & SOLID Principles

  • Object-Oriented Design Refresher
  • Single Responsibility & Open/Closed
  • Liskov Substitution & Interface Segregation
  • Dependency Inversion

Creational Design Patterns

  • Singleton Pattern
  • Factory & Abstract Factory
  • Builder Pattern
  • Prototype Pattern

Structural Design Patterns

  • Adapter & Facade
  • Decorator Pattern
  • Composite & Proxy
  • Bridge & Flyweight

Behavioral Design Patterns

  • Strategy Pattern
  • Observer Pattern
  • Command Pattern
  • Template Method
  • State Pattern
  • Chain of Responsibility
  • Iterator & Mediator
  • Visitor Pattern

Machine Coding Exercises

  • Parking Lot — Requirements & Class Design
  • Parking Lot — Implementation
  • Elevator System — Requirements & Class Design
  • Elevator System — Implementation & Scheduling
  • Library Management System
  • Tic-Tac-Toe / Board Game Design
  • Chess Engine Design
  • Vending Machine Design
  • ATM System Design
  • In-Memory Rate Limiter
  • Thread-Safe LRU Cache
  • Connection Pool Design
  • Producer-Consumer Class Design
  • Movie Ticket Booking System
  • Hotel Reservation System
  • Airline Booking / Seat Selection System
  • Splitwise / Expense Sharing System
  • Design a Logging Framework
  • Design a Notification/Observer-Based Pub-Sub
  • Design a Cache with Pluggable Eviction Policy
  • Design Snake and Ladder
  • Design a Card Game Framework
  • Design an Inventory Management System
  • Restaurant Management System
  • Food Delivery Order Matching
  • Design a Shopping Cart & Checkout Flow
  • Design a Recommendation Engine
  • Design a Job Scheduler
  • Design a Circuit Breaker
  • Design a Distributed ID Generator
  • Design a Pub-Sub Message Broker
  • Design Twitter/X
  • Multi-Pattern Problem: Design a Ride Booking Class Model
  • Multi-Pattern Problem: Design a Food Ordering Class Model
  • Design an Authentication/Authorization Module
  • Design a Form/Survey Builder
  • Design a Meeting Room / Calendar Booking System
  • Design a Search/Filter Engine for an E-Commerce Catalog
  • Design a Voting/Polling System
  • Design a Retry Mechanism with Backoff
  • Design a Health Check Aggregator
  • Design a Feature Flag System
  • Design a Config Management Client
  • Design a Leader Election Algorithm
  • Design a Distributed Counter
  • Design a Bloom Filter
  • Design a Consistent Hashing Ring
  • Design a Distributed Tracing Library
  • Design a Metrics Collection Library
  • Design an Audit Logging Framework
  • Design a Plugin/Extension System
  • Design a Workflow Engine
  • Multi-Pattern Capstone: Design a Food Delivery App
HomeLearnSystem DesignLow-Level Design & Design PatternsMachine Coding Exercises
✓ FreeAdvanced· 9 min read

Design a Leader Election Algorithm

A simplified term/heartbeat leader election model, split-brain risk and why quorum-based majority voting prevents it, worked through with a concrete N=5/W=3/R=3 example, and Raft vs Paxos at the awareness level.

Published September 23, 2026


Design a Leader Election Algorithm

Distributed Lock Service and Distributed Task Scheduler both assumed leader election as a building block; this exercise implements a SIMPLIFIED core of it — not full Raft, but the essential term/heartbeat idea that underlies it.

A simplified term/heartbeat model

class Node {
    int currentTerm = 0;
    String votedFor = null;
    NodeState state = FOLLOWER; // FOLLOWER, CANDIDATE, LEADER
    Instant lastHeartbeatReceived;

    void onElectionTimeout() {
        currentTerm++;
        state = CANDIDATE;
        votedFor = this.id;
        int votes = 1; // votes for itself
        for (Node peer : cluster) {
            if (peer.requestVote(currentTerm, this.id)) votes++;
        }
        if (votes > cluster.size() / 2) { // MAJORITY required, not just "most votes"
            state = LEADER;
            startSendingHeartbeats();
        }
    }

    boolean requestVote(int term, String candidateId) {
        if (term > currentTerm && votedFor == null) {
            currentTerm = term; votedFor = candidateId; return true;
        }
        return false; // already voted this term, or the requester's term is stale
    }
}

A term is a logical, monotonically-increasing "election period" — every node tracks the highest term it's seen, and a vote request from an OLDER term is automatically rejected, which is what prevents a node that's been partitioned away and out of date from winning an election with stale information once it reconnects. A node becomes leader ONLY by winning a MAJORITY of votes in a term — not simply the most votes among several candidates, a distinction that matters enormously for correctness (see split-brain, next).

Split-brain risk and why majority specifically matters

With 5 nodes split into a 3-node partition and a 2-node partition by a network issue:
  3-node side: CAN reach majority (3 > 5/2) -> can elect a leader
  2-node side: CANNOT reach majority (2 is not > 5/2) -> cannot elect a leader
  -> only ONE leader can ever exist at a time, even during a partition

Requiring a STRICT MAJORITY (not just "more votes than any other candidate") is what makes it MATHEMATICALLY IMPOSSIBLE for two different partitions to simultaneously elect two different leaders in the same term — with 5 nodes, at most ONE side of any partition can ever contain 3+ nodes. This is the actual mechanism that prevents split-brain (two leaders simultaneously believing they're authoritative, each accepting writes independently) — not a heuristic or best-effort protection, but a hard mathematical guarantee following directly from requiring > N/2 votes.

Quorum consensus, formalized: W + R > N

For N replicas: requiring (write quorum W) + (read quorum R) > N guarantees
every read quorum overlaps with every possible write quorum by at least one node
  -> that overlapping node always has the most recent write
  -> every read is guaranteed to see the latest write

Concrete example — N=5, W=3, R=3: 3 + 3 = 6 > 5 ✓. This tolerates up to 2 node failures (you can still reach a quorum of 3 out of the remaining 3+ available nodes) while STILL guaranteeing read-your-writes consistency — any 3-node write quorum and any 3-node read quorum, chosen from the same 5 nodes, are mathematically guaranteed to share at least one node in common (by the pigeonhole principle), and that shared node has the latest write.

Why Kafka, ZooKeeper, and etcd all need leader election internally

Every one of these systems needs exactly ONE node to be authoritative for certain decisions at a time (Kafka: one leader per partition, from Messaging Technology Choices; ZooKeeper/etcd: one leader for the whole coordination cluster) — without leader election, there'd be no principled way to pick, and safely REPLACE, that authoritative node when it fails, which is precisely the coordination problem this lesson's term/heartbeat model solves in miniature.

Raft and Paxos, at the awareness level

Raft: leader-based log replication — a single elected leader handles all writes and replicates them to followers in order; explicitly designed to be more UNDERSTANDABLE than Paxos, with leader election (as shown above) as one of its three core sub-problems (alongside log replication and safety). Paxos: the older, foundational consensus algorithm — theoretically equivalent in what it guarantees, but notoriously harder to reason about and implement correctly due to its more abstract, multi-role formulation. You don't need to implement either from scratch for this exercise or, realistically, ever in production (use ZooKeeper/etcd, which implement this correctly already) — but recognizing both names and the general problem they solve (safe, fault-tolerant consensus/log replication) is a real, expected interview-level signal.

Follow-up questions this topic invites — and their answers

Q: What happens if two candidates request votes in the SAME term simultaneously? A: Whichever candidate's vote request reaches a given follower FIRST wins that follower's vote (since votedFor is set once per term and subsequent requests in the same term are rejected) — it's possible NEITHER candidate reaches a majority if votes split evenly, in which case the term simply fails and a new election (a new, higher term) starts after another timeout, which is why election timeouts are typically RANDOMIZED per node to reduce the chance of repeated split votes.

Q: Why does an even N (like 4 nodes) create a real problem for quorum-based systems? A: With N=4, a majority requires 3 nodes — the SAME requirement as N=5 would need, meaning the 4th node adds cost (another replica to maintain) without improving fault tolerance at all; this is why production quorum-based clusters are conventionally sized as ODD numbers (3, 5, 7) — every node added should genuinely improve the fault-tolerance math, and even-sized clusters don't achieve that.

Q: How does heartbeat frequency affect this design's failure-detection speed vs overhead trade-off? A: More frequent heartbeats detect a failed leader faster (shorter time before followers time out and start a new election) but add more constant network overhead; this is directly the same latency-vs-cost tuning knob as Kubernetes' liveness probe interval (Probes & Autoscaling), applied to leader-liveness detection instead of container-liveness detection.

Q: Does W+R > N guarantee strong consistency for EVERY operation, or just reads-after-writes? A: Specifically read-your-writes / linearizable-style consistency for individual key reads relative to the most recent write to that SAME key — it doesn't, by itself, provide multi-key transactional guarantees across several keys simultaneously, which would need additional coordination (like the two-phase-commit alternative Distributed Lock Service's saga discussion explicitly steers away from) beyond simple per-key quorum reads/writes.

Previous

Design a Config Management Client

Next

Design a Distributed Counter

AI Tutor

Lesson: Design a Leader Election Algorithm

Quick actions

AI responses can be inaccurate. Verify critical information.