Leader election, in distributed computing, is the process of designating a single process as the organizer of some task distributed among several computers (nodes). Before the task has began, all network nodes are either unaware which node will serve as the “leader” (or coordinator) of the task, or unable to communicate with the current coordinator. After a leader election algorithm has been run, however, each node throughout the network recognizes a particular, unique node as the task leader.

There are various algorithms for leader election, and they’ve been encoded in multiple projects like Zookeeper, Consul, Redis and many others. What I wanted was to create a good-enough leader election for some services that I was writing, that already used MySQL InnoDB tables. Fortunately, I found this really helpful gist that did almost that. What I did not like was the use of a go ORM and wanted something simpler that used the standard library’s database/sql package directly. The code in the gist was built to support leadership elections in shell scripts, but I what I needed was something that could be used as part of long running services. My solution to that was a MysqlLeader library that is small enough to be added to my gotools project on GitHub. This particular leader election works well enough given one caveat: the duration of the tasks controlled by the leader should not exceed the lifetime of the leader election, and preferably the interval between one election and another.

Hope this helps you as much as it has helped me.