In distributed microservice clusters with background workers (e.g., scheduled cron runners, payment reconciliation workers, partition managers), running multiple concurrent active instances causes race conditions and data corruption. An automated Leader Election mechanism guarantees that exactly one active master executes work, with instant failover if the master crashes.\n\n### 1. Leader Election via Apache ZooKeeper (Ephemeral Sequential Nodes)\nZooKeeper maintains a hierarchical in-memory tree of nodes called znodes:\n\n1. Create Sequential Nodes: All candidate worker processes attempt to create an Ephemeral Sequential znode under a common parent path /election:\n /election/node-0000000001, /election/node-0000000002, /election/node-0000000003...\n2. Elect the Smallest Sequence: Each candidate queries children of /election. The node with the lowest sequence number is elected Leader.\n3. Avoid the Herd Effect (Watch Predecessor Only):\n * If node 2 is not the leader, it does *not* watch the leader node 1!\n * Instead, node 2 sets a Watch on its immediate predecessor: node 1.\n * Node 3 sets a Watch on node 2.\n * If the leader (node 1) dies, its ephemeral znode vanishes. Only node 2 is notified, promoting node 2 to leader without waking up all other hundred candidate nodes.\n\n### 2. Leader Election via etcd (Leases & Revision Watches)\netcd simplifies this using TTL Leases and atomic Key revisions:\n1. Grant Lease: Worker acquires an etcd lease with a 5-second TTL: etcdctl lease grant 5.\n2. Atomic Put with Lease: Worker attempts to create /services/leader attached to the lease using a transaction (Txn).\n3. Success: If successful, worker is Leader and continuously sends KeepAlive heartbeats to maintain the lease.\n4. Failover: If the leader crashes, heartbeats stop. After 5 seconds, etcd revokes the lease and deletes the key, triggering a Watch event on standby workers to elect a new leader.\n\n### Key Architectural Comparison\n| Coordination Engine | Node Primitive | Watch Model | Consensus Protocol | Production Tooling |
| :--- | :--- | :--- | :--- | :--- |
|---|---|---|---|---|
| etcd | Leases with atomic Compare-and-Swap | Revision stream watches | Raft consensus | Kubernetes Control Plane |
| HashiCorp Consul | Sessions with Key Locks | Long-polling HTTP blocking queries | Raft consensus | Nomad, Vault |
| Redis (Redlock) | Mutex keys with TTL (SET NX EX) | Polling / PubSub | Single-instance lock (No strict consensus) | Lightweight web application locks |\n