Leader election
Выбор лидера
Nodes in a distributed system agree on which one should do work that only one node should handle at a time. If that node stops responding, the group can choose a replacement.
Also known as: Raft, Paxos, консенсус
Why elect a leader?
Running several copies of a service helps it survive failures, but some work needs a single coordinator. Take a job scheduler: if every copy dispatches the same scheduled job, workers may run it several times. Electing a leader lets one scheduler dispatch jobs while the others stand by. The role has a scope: a database can have a separate leader for each shard rather than one for the whole database.
How a Raft election works
In Raft, the leader coordinates log replication and sends regular messages called heartbeats. If a follower goes too long without hearing from a leader, it starts an election in a new numbered term and asks the other nodes to vote. A timeout is a reason to try an election, not proof that the old leader crashed. It might just be slow or cut off from part of the network.
Each node can vote for at most one candidate per term, and it won't vote for a candidate whose log is less up to date than its own. A candidate wins with a majority of all voting members, not just a majority of the replies. Any two majorities share at least one voter, so two candidates can't both win in the same term. Randomized election timeouts make it less likely that several candidates will start at once and split the vote.
What happens when the network splits?
Suppose a five-node cluster splits into groups of three and two, with the old leader on the two-node side. The three-node side can elect a replacement. The old leader may still think it's in charge, but it can't commit new log entries without a majority. Once it learns about the higher term, it steps down. The key distinction is between a node believing it's the leader and being able to make progress as one.
Where it fits
Replicated databases can use a leader to coordinate writes. Kubernetes controllers can use a Lease so that one instance actively runs the controller while others stand by. Leader election isn't synonymous with consensus: election decides who coordinates, while consensus establishes agreement on a value or a sequence of operations. Raft includes leader election. Basic Paxos doesn't need a permanent leader for safety, but Multi-Paxos typically uses a stable leader to make progress efficiently.
What interviewers look for
A common follow-up is: “What if the old leader pauses, loses leadership, and then resumes?” A lease alone doesn't stop a delayed request from reaching an external store. One remedy is a fencing token: give each new leader a higher number and have the store reject requests with a number lower than one it has already accepted. The protection comes from the store checking the token, not from the old leader noticing that its lease expired.