Skip to main content

Election algorithm need and example

Short answer

In a replicated database, if the primary server fails, an election algorithm quickly selects the highest-id backup as the new primary to maintain write availability. Bully algorithm: the detecting backup sends ELECTION to higher ids; receiving no reply, it becomes coordinator and broadcasts COORDINATOR. Example: servers 1–5; when 5 crashes, 4 wins and becomes primary after holding its own election.

Present a practical scenario where you need an election algorithm. Explain an election algorithm with example that is suitable to your scenario. (What is the need of an election algorithm; explain with few practical examples.)

Practical scenario

A distributed database with a primary server. Five replicated database servers (ids 1 to 5) serve a bank. All writes go to the primary (coordinator), which copies them to backups. If the primary crashes, the backups must choose a new primary quickly, otherwise no write is possible. Other examples: choosing a new master node in a Hadoop/Kafka/ZooKeeper cluster, a new time daemon in the Berkeley algorithm, and regenerating a lost token in a token ring.

Need of an election algorithm

  • Many algorithms need one coordinator (centralised mutual exclusion, time server, sequencer, primary of a replica group).
  • If the coordinator fails, the rest must agree on a single replacement automatically.
  • Election ensures exactly one coordinator, avoiding conflicts (two primaries = split brain) and giving high availability.

Bully algorithm for the scenario

The highest server id which is alive becomes the primary.

  1. A backup notices that the primary (5) does not answer heartbeat or request, and starts an election by sending ELECTION to servers with higher id.
  2. A higher server that is alive replies OK and takes over the election.
  3. If no one replies within the timeout, the initiator declares itself the primary and sends COORDINATOR to all.

Example: server 5 fails. Server 2 detects and sends ELECTION to 3, 4, 5. Servers 3 and 4 reply OK. Server 3 sends ELECTION to 4, 5; server 4 sends to 5. 4 receives no answer from 5, so 4 broadcasts COORDINATOR(4). Servers 1, 2, 3 now send writes to server 4. When server 5 is repaired, it starts an election, as it has the highest id, and becomes the primary again after getting the latest data.

 1  2  3  4  5(X)
    |--ELECTION-->3,4,5
    |<--OK-- 3,4
          4 --ELECTION--> 5 (no reply)
          4 --COORDINATOR(4)--> 1,2,3

✓ Answer checked by Claude Opus 5.5 (high effort)

All Distributed System chapter 6 questions →