Raft Election Timeouts

medium · distributed-systems, consensus, raft, timers

Raft Election Timeouts

A Raft follower starts an election if it does not receive a heartbeat within a fixed timeout.

Given sorted heartbeat times, an election timeout, and an end time, return the times when an election starts. The follower starts counting from time 0.

Rules:

  • Let lastHeartbeat start at 0.
  • Between heartbeats, an election triggers at lastHeartbeat + timeout, and again every timeout after that until the next heartbeat arrives.
  • A heartbeat resets the timer.

Function signature

func ElectionTimeouts(heartbeats []int, timeout int, end int) []int

Example

heartbeats = [5, 40]
timeout = 10
end = 50

Gap [0,5): no election (10 is after 5)
Gap [5,40): elections at 15, 25, 35
Gap [40,50]: elections at 50

output = [15,25,35,50]

Constraints

  • 0 <= len(heartbeats) <= 100000
  • 0 <= heartbeat time <= 1_000_000
  • 1 <= timeout <= 1_000_000
  • 0 <= end <= 1_000_000

Notes

  • Heartbeats are strictly increasing.
  • Elections at time end should be included.
Run tests to see results
No issues detected