Leader election is the process of designating a single node as the organizer of some task distributed among several nodes. The leader will be responsible for managing the others and coordinate the actions performed by other nodes. If for any reason the leader fails, other nodes will elect another leader and so on. This can help to ensure that nodes don’t conflict with each other.

Implementing the leader election algorithm with consul is quite easy:

  • Register the node as a service on Consul.
  • Create a session.
  • Try to put a Lock on that session. If you succeed you are leader if not… well you are not the leader.
  • Renew the session

It is just a naive implementation So do NOT use this in production.

Step 1: Download Consul and run on dev mode

$ ./consul agent -dev

**Step 2: **Register the node as a service on Consul

import (

// configs to connect to consul
client, err := api.NewClient(&api.Config{
    Address: "",
    Scheme:  "http",

if err != nil {

err = client.Agent().ServiceRegister(&api.AgentServiceRegistration{
    Address: "",
    ID:      "node01_monitoring", // Unique for each node
    Name:    "monitoring", // Can be service type
    Tags:    []string{"monitoring"},
    Check: &api.AgentServiceCheck{
        HTTP:     "",
        Interval: "10s",

if err != nil {

#consul #golang #microservices #consul #leader-election

Leader Election with Consul and Golang
14.75 GEEK