grpcproc
Documentation

Leader election

Elect one node of a cluster to run a singleton, and carry its state from one leader to the next.

grpcproc/leader elects one node of a cluster and runs a singleton there: a child spec of yours, started when its node wins and told to exit when it loses, so no handler asks whether it still leads. It is a package of the core module.

Install and start

go get github.com/floatdrop/grpcproc # leader is a package of it
leader.Start(node, leader.Spec[*schedpb.State]{
	Cluster: "scheduler",
	Voters:  []string{"a", "b", "c"},
	Singleton: func(l *leader.Lease[*schedpb.State], last *schedpb.State) (actor.ChildSpec, error) {
		return actor.Child("scheduler", func() *Scheduler { return &Scheduler{lease: l, state: last} }), nil
	},
})

Every node of the cluster runs the same call. Cluster names the election, so one set of nodes can hold several; Singleton builds what runs on the leader, from the state the last leader checkpointed, the zero value before any has. The type parameter is that state: proto.Message for any, *emptypb.Empty for none. Start returns a supervisor, of the elector and, while the node leads, the singleton; leader.Child(name, spec) puts the same supervisor in a tree of yours.

The singleton's name is registered on the leader's node only. To reach it, ask any node that takes part where it runs:

info, err := leader.Status(ctx, node, "scheduler") // Role, Term, Leader, View, Quorum, Singleton
sched := grpcproc.Named[*schedpb.Msg](info.Leader, "scheduler")

A call to a node that no longer leads fails with grpcproc.ErrNoProc, and while no leader is known info.Leader is empty: ask again, or use leader.Call, which does.

The singleton

A node that wins an election starts the singleton, and a node that stops leading tells it to exit with reason demoted. Its Init is "became the leader", its context ending is "stopped being the leader", and its Terminate runs either way, in time to save its state. I/O it does with its process's context is cancelled on demotion.

a leader and a follower of one election
node a: the leadersupervisorsingletonyours: it runswhile a leadselectorleader/schedrelay crelay bnode b: a followersupervisorelectorleader/schedno singletonrelay arelay ca's relay for b carries a's heartbeats to b's elector; b's relay for a carries the acks backa relay also monitors its peer's elector, and waits for a dial that hangs, so the elector never does

A singleton that exits by itself, or cannot start, ends its node's leadership. The node steps down, and campaigns again only after a backoff that doubles with each failure in a row, while the others elect one of themselves. For restarts in place, make the singleton an actor.ChildSupervisor, whose own children restart as a supervisor's do.

Spec.Confirm, if set, runs after a win and before the singleton starts, with the term: an error withholds leadership, with the same backoff. Use it to wait for a lock outside the cluster, an etcd lease or a Kubernetes Lease.

The election

Each node runs an elector process, registered as leader/<cluster>. The election is Raft's without the log:

  • Terms order leaderships. A candidate starts a term and asks for votes, a node votes once in a term, and a majority makes a leader, which asserts itself with heartbeats. A follower that hears none for an election timeout campaigns.
  • Pre-votes come first: a node asks whether it would win before it starts a term, so a node cut off from the others does not raise its term alone and depose the leader once it is back.
  • A leader steps down once it has not heard from a majority for two election timeouts.
  • Followers stick to a leader they heard from within an election timeout, and ignore requests for votes, unless the leader handed over.
  • Sends go through relays, a process per peer, which also monitor the peer's elector. A send or a monitor that waits for a dial to a node that does not answer holds that relay, never the elector and its heartbeats. When a leader's elector exits, its followers see it at once, and campaign without waiting out a timeout.
Spec fieldDefault, and what it is
ElectionTimeout150ms. How long a follower goes without a heartbeat before it campaigns: a random time between it and twice it.
HeartbeatInterval50ms. How often a leader asserts itself; shorter than ElectionTimeout.
MinClusterSize3. The smallest view that elects, without Voters.
GhostTTL5s. How long a node that cannot be reached still counts, without Voters or Membership.

Who votes

With Voters, the view is that fixed set of nodes, and a majority of it elects, whether the others are up or not. Two majorities of one set share a node, so a partition never elects two leaders. Prefer it where the nodes that may lead are known.

Without Voters, the view is dynamic: this node, Peers, and the nodes a Membership reports up, the same one a node is configured with, on etcd say: left unset, it is the node's own. With a Membership, only those take part; without, on a node with none either, a node that talks to this one joins too. No leader is elected in a view smaller than MinClusterSize, and the relays' monitors keep the view current:

The peer’s electorThe peer
exits (shutdown, a crash), or never ran (noproc)Leaves the view at once.
cannot be reached (noconnection)Stays, as a ghost, until Membership reports it gone, or for GhostTTL without one.
is heard from againIs back.

A dynamic view trades safety for availability: nodes whose views differ can each count a majority of their own.

State and checkpoints

The singleton checkpoints its state through its Lease:

err := lease.Checkpoint(ctx, state) // returns once a majority of the cluster holds it
lease.Save(state)                   // the same, without the wait

The leader sends the state to its followers with its heartbeats, and a follower votes only for a candidate whose state is at least as recent as its own. So whichever node leads next starts its singleton from every checkpoint that returned, or a later one. Once the lease's term is over, Checkpoint fails with leader.ErrNotLeader, and nothing a demoted singleton saves reaches anyone.

leader.Resign(ctx, node, cluster) hands over. The leader stops its singleton, whose Terminate can still save; waits for the follower with the latest state to hold the leader's; and has it campaign at once. Call it before stopping a leader's node, and the next leader starts from what Terminate saved rather than the last checkpoint. On a node that does not lead it is ErrNotLeader, and on a leader alone, ErrNoSuccessor.

Keep the state to what the next leader needs to carry on, the jobs a scheduler ran last, not the data they worked on: every checkpoint carries all of it.

Without a Store, the state lives in memory, as do the terms: a cluster that loses a majority of its nodes at once loses them, and a cluster of one loses them at every restart. With one on each node, each keeps its term, its vote and the state, and saves them before it tells anyone of them, as Raft does. A cluster that restarts whole starts its singleton from the last checkpoint that returned, and its terms go on growing.

Store: leader.File("/var/lib/app/cron.election"), // each node its own, on its own disk

A Store shared by nodes breaks the election, and so does a file restored from a backup, which has forgotten the votes cast since: delete it instead, and the node starts afresh.

Calling the leader

leader.Call calls the process registered under a name on whichever node leads, from a node or from inside a process, and follows leadership as it moves. This singleton, from examples/singleton, hands out numbers that never repeat: each is checkpointed to a majority before it is handed out, so whichever node leads next starts past it.

examples/singleton/ids_test.go
func ids(l *leader.Lease[*wrapperspb.UInt64Value], last *wrapperspb.UInt64Value) (actor.ChildSpec, error) {
	next := last.GetValue()
	return actor.ChildFunc("ids", func(p *grpcproc.Process[*emptypb.Empty]) error {
		for {
			m, err := p.Receive()
			if err != nil {
				return err
			}
			next++
			if err := l.Checkpoint(p.Context(), wrapperspb.UInt64(next)); err != nil {
				// No longer the leader: the call goes unanswered, and the
				// caller's leader.Call asks the next one.
				return err
			}
			_ = m.Reply(wrapperspb.UInt64(next), nil)
		}
	}), nil
}

Any node that takes part asks for one the same way:

examples/singleton/ids_test.go
func nextID(t *testing.T, from grpcproc.Caller) uint64 {
	id, err := leader.Call[*wrapperspb.UInt64Value](t.Context(), from, "ids", "ids", &emptypb.Empty{})
	if err != nil {
		t.Fatal(err)
	}
	return id.GetValue()
}

The example's test asks from every node, kills the leader, and asks again: the numbers run on from where they were. Call asks again, for as long as its context allows, only when the call cannot have reached the singleton:

The callAsked again?
No leader is known yet.Yes.
The node named has no such process: it no longer leads, or has not started its singleton yet.Yes.
It never left this node: a *grpcproc.LinkError whose Unsent is set.Yes.
It left, and its link broke, or its context ended, while it waited.No: it may have been handled.
It was answered with an error.No: that is the answer.

Repeating a call that may have been handled is the caller's choice: fine for a read, or for a request the singleton de-duplicates. For the numbers, a repeat can only skip one, never hand one out twice.

Transfer and cordon

leader.Transfer(ctx, node, "scheduler", "b") // b leads next; "" for the most up-to-date follower
leader.Cordon(ctx, node, "scheduler", "c")   // c may not lead: for work on its host
leader.Uncordon(ctx, node, "scheduler", "c")

All three go to whichever node leads, found through node's elector, from any node that takes part. Transfer hands over as Resign does, to the node it names: it is refused for a node that leads already, is not in the view, or is cordoned, and ends with ErrNoSuccessor if that follower cannot be reached.

Cordon keeps a node from leading until Uncordon: it campaigns no more, voters refuse it, and if it leads, it hands over. The cordoned nodes are part of the state the leader replicates, and Cordon returns once a majority holds it, so a cordon outlasts the cordoned node's restarts, and the leader's. A cordoned node still votes, so the cluster keeps its quorum while its host is worked on. A cordon that would leave no node of the view to lead is refused.

From a terminal, grpcprocctl does the same three through the Inspector: leader move, with --to a node, leader cordon and leader uncordon. It prints what every node's elector believes once they agree:

grpcprocctl --plaintext leader cordon scheduler b   # b led: it hands over
output
NODE  ROLE      TERM  LEADER  VIEW   STATE  CORDONED  UNREACHABLE  SINGLETON  BACKOFF  ERROR
a     leader    2     a       a,b,c  2.3    b                      <a.1.11>
b     follower  2     a       a,b,c  2.3    b                      none       200ms
c     follower  2     a       a,b,c  2.3    b                      none

A node that restarts holds no state, and voters refuse a candidate whose state is older than theirs; so a voter that refuses one sends its own with the refusal, and the candidate campaigns again with it. A restarted node catches up even when no leader is left to send it anything, as when every other node is cordoned.

Split leadership

Two nodes can both believe they lead for a while: a leader cut off from the others leads until it notices, two election timeouts at most, and they elect another meanwhile. Its singleton is told to exit then, but what it did before is done. Lease.Term grows with every election: a database or a queue that remembers the highest term it has seen can refuse a deposed leader's writes. The other way is to have leadership wait for an external lock, in Confirm.

Cron as the singleton

grpcproc/cron as the singleton: the leader runs a cron process, which reports each job's last run as its state, and the next leader's resumes from it, catching up on a run it missed within each job's StartingDeadline. From examples/singleton, where every node runs this:

examples/singleton/singleton_test.go
func election(jobs []cron.Job) leader.Spec[*cronv1.State] {
	return leader.Spec[*cronv1.State]{
		Cluster: "cron",
		Voters:  []string{"a", "b", "c"},
		Singleton: func(l *leader.Lease[*cronv1.State], last *cronv1.State) (actor.ChildSpec, error) {
			return cron.Child("cron", cron.Spec{Jobs: jobs, Resume: last, OnState: l.Save})
		},
	}
}

The example's test crashes the leader a moment before 10:10, and checks that every minute ran exactly once, on the old leader before 10:10 and on the new one from then, the minute of the election included:

examples/singleton/singleton_test.go
// The leader crashes a moment before 10:10: the next is elected
// once that minute has begun, and starts the run it owes.
sleepUntil("10:09:59.9")
info, err := leader.Status(t.Context(), c.Node("a"), "cron")
if err != nil {
	t.Fatal(err)
}
first := info.Leader
c.Kill(first)
sleepUntil("10:12:30")

It runs in a testing/synctest bubble over a grpcproctest cluster, on a fake clock: the minutes pass at once, and an election's timeouts are the same on every run.

Inspecting an election

The elector publishes what it believes on every node: grpcprocctl inspect leader/scheduler shows one node's, and grpcprocctl leader and the Web UI compare them, which is how a split view shows up.

KeyWhat it says
roleleader, candidate, follower, or unclustered in a view smaller than MinClusterSize.
term, leader, voted_forThe current term, the leader known in it, and whom this node voted for.
view, quorumThe nodes whose majority elects, and how many that is.
unreachableNodes of the view not heard from since their link broke, or their elector exited.
stateThe version of the state this node holds: the term of the leader that made it, and its sequence.
cordonedThe nodes that may not lead.
checkpoints_waitingOn the leader: checkpoints a majority does not hold yet.
singletonIts PID on the leader, or none, starting, stopping.
backoffHow long a node waits before it campaigns again: after its singleton failed, or after it handed over.

The elector's helpers are its children in the process list: its relays, labelled leader relay; the process that starts the singleton, leader starter; and the watch of a Membership, leader membership.

grpcproc/otel's ObserveLeader turns what every node's elector publishes into gauges, to alert on: no leader or two, a singleton that runs nowhere, a view one node short of losing its majority.