Leader Election & Coordination

Coordinating distributed processes in practice — leader election with etcd and ZooKeeper, leases and fencing tokens, distributed locks (and why Redis locks are subtle), service discovery, configuration, and membership via gossip.

Advanced 4 min readLesson 6 of 9

Many systems need exactly one node to do something: run a scheduled job, own a shard, write to a resource, act as the primary database. Others need nodes to find each other and agree on configuration. Rather than implementing consensus yourself, you build these on a coordination service — etcd, ZooKeeper or Consul — that runs Raft or Zab internally.

Leases: time-bounded ownership

A lease is a lock with an expiry. The holder must renew it before it expires; if the holder crashes, the lease lapses and someone else can take over — no permanent deadlock.

Node ACoordinatorNode Bacquire lease 'scheduler' (TTL 10 s)grantedrenew every 3 scrashes ✗TTL expiresacquire leasegranted — B is leader

Leader election recipes

etcd (keys with leases + compare-and-swap + watches):

Go
// Using etcd's concurrency package (Go)
session, _ := concurrency.NewSession(client, concurrency.WithTTL(10))
election := concurrency.NewElection(session, "/services/scheduler/leader")

if err := election.Campaign(ctx, nodeID); err != nil { ... }   // blocks until elected
runAsLeader(ctx)                       // when the session's lease is lost, ctx should be cancelled

ZooKeeper (ephemeral sequential znodes):

  1. Each candidate creates an ephemeral sequential node: /election/n_0000000017. Ephemeral nodes vanish when the creator's session dies.
  2. The candidate with the lowest sequence number is the leader.
  3. Every other candidate watches the node just before its own (not the leader — avoiding a thundering herd when the leader dies).
  4. When that node disappears, re-check: if you're now the lowest, you're the leader.

Kubernetes controllers use Lease objects in the API server (backed by etcd) for the same purpose; libraries like Spring Integration, Apache Curator and client-go provide ready-made election.

The hard part: knowing you're still the leader

A leader can be paused (GC, VM stall) or partitioned long enough for its lease to expire and a new leader to be elected — while it still believes it's in charge. If both write to shared storage, data is corrupted.

Distributed locks

A distributed lock is a lease used for mutual exclusion. Two very different purposes:

PurposeIf the lock fails occasionally…Requirement
Efficiency (avoid doing the same work twice, e.g. a cron job)Some duplicate work — annoying but harmlessA simple lock is fine (single Redis SET NX PX)
Correctness (two holders would corrupt data)Data corruptionConsensus-based lock (etcd/ZooKeeper) plus fencing tokens
Python
# Simple Redis lock for efficiency purposes
import uuid, redis
r = redis.Redis()
token = str(uuid.uuid4())

if r.set("lock:daily-report", token, nx=True, px=30_000):   # only if not held; 30 s expiry
    try:
        generate_report()
    finally:
        # release only if we still own it (atomic check-and-delete)
        r.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0",
               1, "lock:daily-report", token)

Redlock (acquiring the lock on a majority of independent Redis nodes) has been debated: it relies on bounded clock drift and process pauses and provides no fencing token, so it's unsuitable for correctness-critical locking. Use it, if at all, only for efficiency.

Better still: avoid distributed locks when you can — use database constraints and transactions, conditional writes (UPDATE … WHERE version = 7), idempotent operations, or partition work so each item has a single owner (e.g. Kafka partitions assigned to consumers).

Service discovery and configuration

Coordination services also store small, critical metadata:

  • Service discovery: instances register themselves (with leases, so dead instances disappear); clients watch the registry for changes. Consul, etcd, ZooKeeper, Eureka; Kubernetes Services/Endpoints do this for you.
  • Dynamic configuration and feature flags: change a key, every watcher reacts within milliseconds.
  • Cluster metadata: which node owns which shard, the current primary.

Keep them for metadata only: they're optimised for small values and consistency, not high-volume data.

Membership without a coordinator: gossip

Large clusters (thousands of nodes) often track membership with gossip protocols instead: every second, each node exchanges state with a few random peers. Information spreads like an epidemic — reaching all N nodes in about O(log N) rounds — with no central point of failure.

ABCDEF
Round 1: A tells C and E. Round 2: they tell B and F. Round 3: D hears it.
  • Failure detection: SWIM-style protocols ping random members, ask others to ping indirectly before declaring a node suspect, and gossip the result. The phi accrual detector (Cassandra, Akka) outputs a suspicion level based on heartbeat inter-arrival history instead of a fixed timeout.
  • Used by Cassandra, DynamoDB internals, Consul (Serf), Redis Cluster, and HashiCorp's memberlist.
  • Gossip gives eventual agreement — fine for membership and load information, not for decisions needing a single answer.
Key takeaways
  • Use a coordination service (etcd, ZooKeeper, Consul) instead of implementing consensus.
  • Leases give time-bounded ownership that recovers automatically when the holder dies.
  • A paused or partitioned leader may still act: fencing tokens checked by the resource prevent damage.
  • Distinguish locks for efficiency (simple Redis lock) from locks for correctness (consensus + fencing).
  • Prefer avoiding locks: conditional writes, idempotency, partitioned ownership.
  • Gossip spreads membership and failure information in O(log N) rounds without a central coordinator.