grpcproc
Documentation

Running in production

What a deployment should set that the defaults do not, and what goes wrong without it.

A node's defaults suit a program on one machine. Configuration has every field; this page says which to set for a deployment.

Checklist

SetOr else
Admit: grpcproc.AdmitTLS(…), mTLS on the server, ServerName per peerWhoever reaches the server may stand in for a node and exit any process.
Keepalive on the server and on every dialA peer that dies silently is not declared down for minutes, and its monitors do not fire.
A Membership (etcd)A crashed peer behind a half-open connection lingers until keepalive notices it.
MaxQueued, WithMailboxLimit where load is not shed by the processA slow peer or process holds what is sent to it in memory, without bound.
MaxMessageSize no larger than every peer's grpc.MaxRecvMsgSizeThe default, 4 MiB on both, already agrees; raised on one side only, links break.
Incarnations that grow across restartsA restarted node is refused as older than itself.
A shutdown in orderPeers see noconnection rather than shutdown, and a leader's state since its last checkpoint is lost.
Alerts on the signals belowA link that keeps breaking, or a mailbox that keeps growing, goes unseen.

Admission

A node's service is mounted on the program's gRPC server, which may be reachable by more than the cluster, and a peer is who its stream's metadata says it is. So Config.Admit is required: with grpcproc.AdmitAll, anyone who reaches the server may claim a node's name, with a newer incarnation that keeps the real node out, and exit any process. Use mutual TLS and grpcproc.AdmitTLS, which admits a peer whose verified client certificate names its node exactly, as a DNS subject alternative name, or an IP one of the address the name is. A wildcard names no node.

creds := credentials.NewTLS(&tls.Config{
	Certificates: []tls.Certificate{cert}, // its SAN is this node's name
	ClientCAs:    pool,
	ClientAuth:   tls.RequireAndVerifyClientCert,
})
srv := grpc.NewServer(grpc.Creds(creds), /* keepalive, below */)

node, err := grpcproc.NewNode(grpcproc.Config{
	Name:  "orders-1",
	Admit: grpcproc.AdmitTLS(nil),
	DialOptionsFor: func(peer string) []grpc.DialOption {
		// The server dialed must present a certificate naming the node meant.
		return []grpc.DialOption{grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{
			Certificates: []tls.Certificate{cert}, RootCAs: pool, ServerName: peer,
		}))}
	},
	// …
})

Each node's certificate is used both ways, as the server's and as the client's when it dials, so it needs both the serverAuth and the clientAuth extended key usage; a server certificate with the first alone fails every dial. Admit checks who dialed this node; the ServerName checks the node this one dials, which otherwise is whoever answers at the address the resolver gave. A node of another installation gets a Policy instead of everything: grpcproc.Export lets it send to, call and monitor the names listed, and exit nothing (Security).

The Inspector, if the node serves one, is a second service on the same server, and it can send, call and exit too. Guard it with the server's interceptors, or build it with inspect.ReadOnly(), which refuses all three.

Failure detection

A peer is declared down when its link to this node ends, and only then do monitors of its processes fire noconnection and calls to it fail. A peer that crashes cleanly closes its connections, and that is seen at once. One that loses power, or is cut off by the network, closes nothing: its link ends only when something notices. gRPC keepalive is what notices, in seconds, and it has two halves. The dial's pings end this node's link to the peer; the server's end the peer's link to this node, the one whose end declares the peer down. Without the server's half, only the operating system's TCP timeouts, which take minutes, or a Membership end it.

kp := keepalive.ClientParameters{Time: 10 * time.Second, Timeout: 5 * time.Second}
dial := grpc.WithKeepaliveParams(kp) // in DialOptions

srv := grpc.NewServer(
	grpc.KeepaliveParams(keepalive.ServerParameters{Time: 10 * time.Second, Timeout: 5 * time.Second}),
	// Accept the dials' pings: by default a server allows one every 5 minutes,
	// and answers more with GOAWAY "too_many_pings", ending the connection.
	grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{MinTime: 5 * time.Second, PermitWithoutStream: true}),
)

With these, a silent peer is down within about fifteen seconds. A Membership is the second opinion, the cluster's rather than one link's: grpcprocetcd reports a node down when its lease ends, ten seconds after it last renewed by default (WithTTL), and every node then drops its links to it. It also catches what keepalive cannot, a peer that answers pings but has been replaced.

A dial is bounded by DialTimeout, 5 s by default. After a dial fails, sends to the peer fail at once with ErrNoConnection for a while, doubling up to DialBackoff, 5 s, rather than each waiting for a dial of its own; so does a link that ends within DialTimeout of coming up. Lower them for a cluster that must notice a peer coming back sooner; raise DialTimeout across slow networks.

Limits

Everything a node holds for others is unbounded by default, as Erlang's is: a send never waits and never fails for a slow receiver, and if the receiver falls behind for good, memory grows. Three bounds refuse instead. A call always learns of a refusal; a send learns of a link's and a message's, while a full mailbox makes it a dead letter on the receiver's node, as a send to a missing process is.

BoundWhen it is reached
MaxQueued, MaxQueuedBytes: a peer's linkSends and calls to that peer fail at once with ErrLinkBusy, as Unsent: safe to send again later. Other peers are not affected.
WithMailboxLimit(n): a processA message to it is a dead letter, mailbox full; a call fails with ErrMailboxFull, never handled. Downs and exits always get in.
MaxMessageSize: one messageA send or a call to another node that encodes larger fails with ErrTooLarge, never sent; a reply that large reaches its caller as that error.

Bound a process's mailbox when it cannot shed load itself, a writer to a database that may stall, say; a process that answers from memory rarely needs one. Size a link's bound for a burst, not for steady load: it is what the node may hold for a peer that stopped reading.

MaxMessageSize must not exceed any peer's grpc.MaxRecvMsgSize: a peer ends a link that sends it more, with every call and monitor on it. Both are 4 MiB by default. Nothing tells a node its peers' limits, so to carry larger messages, raise MaxRecvMsgSize on every server first, and MaxMessageSize after, in a second rollout. A message that large holds up everything behind it on its link, Downs included; for blobs, send a reference to where they are stored instead.

Names and restarts

A node's name is its address and must be unique in the cluster. Two programs started with one name are taken as two incarnations of one node: the newer one replaces the older on every peer that hears from both, and the older one's links are refused. A second replica given the same name by mistake does the same to the first.

The incarnation must grow with each start. The default is the start time in nanoseconds, which it does as long as clocks agree to within the time between two starts; a node whose clock went back is refused as older than itself, until its peers forget the newer one: Membership reports it gone, or Disconnect. Where clocks cannot be trusted, give Config.Incarnation from a counter that outlives the program: a generation in the orchestrator, or a number kept on disk.

Incarnations fence grpcproc's traffic only. A replaced node that still runs may still write to a database; fence that with Lease.Term (below) or a global name's Claim.Revision (Addresses).

Leader election

Voters is a fixed set of nodes; a majority of it elects, and two majorities of one set always share a node, so no partition elects two leaders. Use it where the nodes that may lead are known. Without it, the view is Peers and whatever Membership reports, which follows a cluster that scales, at the cost of a view that can change under an election; MinClusterSize, 3 by default, keeps a fragment of it from electing.

ElectionTimeout, 150 ms by default, suits nodes on one network. Raise it where a pause, a slow round trip, or a slow disk under Store can approach it: saves hold up the elector's heartbeats. Give every node a Store (leader.File), so that a cluster that restarts whole goes on from its last checkpoint, and its terms go on growing.

Two nodes can briefly both believe they lead: a leader cut off from the others leads until it notices, at most two election timeouts, while they elect another. Pass Lease.Term to anything the singleton writes to, which keeps the highest term it has seen and refuses lower ones. Where leadership must wait for an external lock, an etcd lease or a Kubernetes Lease, take it in Confirm.

To work on a host, leader.Cordon it: it campaigns no more, and hands over if it leads, across its own restarts, until Uncordon. grpcprocctl leader does both from a terminal (Leader election).

Shutdown

A node that stops tells its peers: processes exit with reason shutdown, their watchers get Down{shutdown} over links that are still up, every link flushes before it closes, and the Registrar's record is withdrawn last. That needs Stop to run before the gRPC server stops, and a few steps before it:

ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()

// 1. A leader hands over, so the next one starts from the singleton's last state.
if err := leader.Resign(ctx, node, "billing"); err != nil && !errors.Is(err, leader.ErrNotLeader) {
	log.Warn("resign", "err", err)
}
// 2. The top supervisor stops its children in reverse order of their start.
_ = node.Exit(ctx, root, grpcproc.ReasonShutdown)
_, _ = node.Wait(ctx, root) // its exit reason, ErrNoProc once it is gone, or ctx's error
// 3. Every process left exits, links flush and close, the record is withdrawn.
_ = node.Stop(ctx)
// 4. Only now the server.
srv.GracefulStop()

Stop alone asks every process to exit at once, so a supervisor cannot stop its children one by one, the last started first; stopping the top supervisor first lets it. grpcproc does not handle signals: the program decides when this runs, on SIGTERM usually, and its orchestrator's grace period bounds the ctx.

Monitoring

grpcprocotel exports the metrics below. A node's snapshots, which grpcprocctl and the Inspector read, hold the totals, the mailboxes and each link's state, and Node.Subscribe streams the events behind them (Observability). The signals worth an alert:

SignalWhat it means
grpcproc.links.down rising for one peer; LinkInfo.Sessions growingIts links keep breaking: keepalive refused (too_many_pings), a proxy cutting streams, a message over its server's limit. The link-down event (Hooks.OnLinkDown, grpcprocctl watch) carries why; LinkInfo.LastError does for a link that ended young.
grpcproc.dead_letters by reasonmailbox full: a process is overloaded. denied: an export list is wrong. noconnection: messages lost to broken links. type: two versions disagree on a message.
grpcproc.mailbox.oldest by labelA process falling behind, before its mailbox fills.
grpcproc.call.duration with error.typebusy and mailbox_full: overload. noconnection: a peer gone. timeout: a callee too slow for its callers.
grpcproc.processes.exited with reason panic, error, max restartsCrashes, and a supervisor that gave up.
grpcproc.leader.term rising, from ObserveLeaderElections keep happening: ElectionTimeout too low for the network, or a node flapping. grpcprocctl leader shows each node's view.