grpcproc
Documentation

Supervision

How a supervisor restarts the processes under it, which ones and when, and what happens when it gives up.

Let it crash

A process that meets a state it cannot handle returns an error, and a supervisor above it starts a new one from a known good state: the bug is logged, and it costs one process its state rather than leaving one running with a corrupted map. The actor model has the reasoning. It is a rule about the unexpected, not a licence to skip validation: a bad message from another service is expected input, answered with a refusal, as the tutorial's contracts do.

Supervisors

A supervisor is a process built on monitors and links. It has a list of children, each described by how to start it and when to restart it. It starts them in order, monitoring each from before it runs, with SpawnMonitor, so no exit is missed or misreported as noproc. Each child is also linked to it, with LinkParent, so a supervisor that is gone takes its children with it. Then it waits for Down messages.

When one arrives, the supervisor reads the reason and the child's restart type, and either starts the child again, and perhaps its siblings, or counts one failure too many and exits itself. A supervisor holds no application state and answers no application calls.

sup, err := actor.Supervise(node, actor.Spec{
	Strategy: actor.OneForOne,
	Children: []actor.ChildSpec{
		actor.Child("inventory", func() *Inventory { return &Inventory{ledger: ledger} }),
		actor.Child("pricing", func() *Pricing { return &Pricing{table: table} }),
	},
}, grpcproc.WithName("shop"))

actor.Child takes a name and a function that builds the actor. The supervisor calls the function at every start, so a restart begins from a fresh struct, not from the one that crashed. actor.ChildFunc does the same for a plain process function, and actor.ChildSupervisor makes a child that is itself a supervisor. Supervisors has the API in full.

State across restarts

A restarted actor is a new struct, and whatever the old one held in its fields is gone. What must outlive a crash lives outside the actor, in something the actor loads when it starts and writes to as it goes. In the example that is a Ledger, a stand-in for a database:

examples/supervisor/main.go
// Ledger stands for a database. What must outlive a crash lives outside the
// actor, and the actor loads it when it starts.
type Ledger struct {
	mu   sync.Mutex
	left map[string]int64
}

func (l *Ledger) Load() map[string]int64 {
	l.mu.Lock()
	defer l.mu.Unlock()
	return maps.Clone(l.left)
}

func (l *Ledger) Save(sku string, left int64) {
	l.mu.Lock()
	defer l.mu.Unlock()
	l.left[sku] = left
}

// Inventory is the supervised actor.
type Inventory struct {
	ledger *Ledger
	left   map[string]int64
}

func (i *Inventory) Init(*grpcproc.Process[*shoppb.Stock]) error {
	i.left = i.ledger.Load()
	return nil
}

The actor's Init runs before its first message and loads the levels back; the supervisor built the actor around the same Ledger it built the last one around. So an actor may hold what is cheap to rebuild in Init, a cache, a cursor, a connection, and never the one copy of an order.

Strategies

When a child exits, the supervisor's Strategy says who else is affected. Children that share state or a protocol with the one that failed cannot be trusted to carry on with a fresh replacement; children that only share a supervisor can.

the three strategies, when the middle child exits
OneForOneonly the one that exitedsupervisorw1untouchedw2exitedrestartedw3untouchedOneForAllevery childsupervisorw1restartedw2exitedrestartedw3restartedRestForOneit, and those started after itsupervisorw1untouchedw2exitedrestartedw3restarteda dashed box is the child that exited; a filled one comes back new
StrategyRestarts
OneForOneOnly the child that exited. The default, and right for children that do not depend on each other: the services of a node.
OneForAllEvery child. The others are stopped, in reverse order, then all are started again, in order. For children that share fate: a connection and the session that speaks over it.
RestForOneThe child and every child started after it. For children that depend on the ones before them: a store, then the workers that use it.

Only children that were running come back with their group. A transient child that had finished stays finished.

Restart types

Each child has a Restart type, which says whether an exit calls for a restart at all. The question is whether the exit was abnormal: normal and shutdown are not, and every other reason is, an error's text, a panic, noconnection, max restarts.

RestartStarted again
PermanentAlways, however it exited. The default: a service that should be running as long as the program is.
TransientAfter an abnormal exit only. A job that should run to completion: a normal end is success, a crash is not.
TemporaryNever. A one-off; the supervisor forgets it once it ends.
actor.Child("importer", newImporter).WithRestart(actor.Transient)
actor.ChildFunc("", oneOff).WithRestart(actor.Temporary) // anonymous: no name

A child that is stopped by its supervisor, with StopChild or when the supervisor ends, is not restarted whatever its type: the supervisor asked for that exit.

Restart intensity and escalation

A child that keeps failing has a deterministic bug, or depends on something that is down, and a fresh struct fixes neither. So a supervisor keeps count. More than MaxRestarts restarts within Within, 3 in 5 seconds by default, and it stops trying: it stops its other children and exits with reason max restarts.

That reason is abnormal. A supervisor is usually a child of another supervisor, and to that one, max restarts is a Down like any other: it restarts the child supervisor, which starts its whole subtree again from scratch. If that fails too, the failure moves up one more level. At the top it reaches the root, and a root that gives up means the program has given up; the tutorial's platform stops the program then, for whatever runs it to start it again.

a failure moving up the tree
rootOneForOneinventorystockpaymentscashierordersdesk1. cashier fails 4 times in 5s2. payments gives up: exit reason "max restarts"3. root sees an abnormal exit and starts payments again, with a new cashierinventory and orders run on throughout: OneForOne at the root

Each level restarts what it can and passes on what it cannot, so a restart widens as the failure persists: one actor, then one service, then the program.

Stopping children

A supervisor that ends, because it was told to or because it gave up, stops its children first, in reverse order of their start, so a child never outlives one it was started after and might depend on. Each child gets an Exit with reason shutdown and a time to go: Spec.Shutdown, 5 seconds by default, or its own WithShutdown. A child that is itself a supervisor gets as long as it takes, actor.Infinity, since it has a subtree of its own to stop in order.

A goroutine cannot be killed, so a child that ignores its exit request and outlives its Shutdown is logged and left behind. A named child keeps its name until it exits, and nothing is started under a name an old process still holds: the supervisor monitors the stubborn child and starts its replacement, and the children after it, only once it is gone, handling its mailbox meanwhile. Its own end waits the same way. A child that never exits therefore holds its restart for good.

So a process function must return when Receive returns an error, and a handler must not block forever.

Names across restarts

A child with a name is registered under it on the node, at every start. The processes that call it hold an address made from the node's name and that name, and the address reaches whichever process runs the child right now. A caller does not learn that the child was restarted, other than by a call that failed while it was down, which fails with ErrNoProc and can be tried again.

The example has one child, restarted alone when it exits, up to 3 times a minute:

examples/supervisor/main.go
// tree is the supervision tree: one child, restarted alone when it exits,
// up to 3 times a minute.
func tree(ledger *Ledger) actor.Spec {
	return actor.Spec{
		Strategy:    actor.OneForOne,
		MaxRestarts: 3,
		Within:      time.Minute,
		Children: []actor.ChildSpec{
			actor.Child("inventory", func() *Inventory { return &Inventory{ledger: ledger} }),
		},
	}
}

The program restocks, reserves, then sends a restock of zero, which the actor treats as a bug and exits on. The supervisor starts a new actor under the same name; the next call by that name reaches it, with levels loaded back from the ledger:

output
reserved, left: 3
inventory exited: bad restock of 0 apple
inventory started again
reserved, left: 2
supervisor restarts: 1/3 in 1m0s

Significant children

A job made of several processes is done when its processes are done, and the supervisor over them should end then. WithSignificant(true) marks the children whose end counts, and Spec.AutoShutdown says how many: AnySignificant ends the supervisor when the first of them ends by itself, AllSignificant when the last does. A child the supervisor stopped does not count, and a permanent child cannot be significant, since it is never allowed to end.

The supervisor exits with shutdown, which is not abnormal: its own supervisor restarts it only if it is permanent there, which a job's supervisor is not.

Designing a tree

  • One supervisor per service, under a root with OneForOne. A service that gives up is restarted alone, and the others keep serving. That is the shape the tutorial's platform builds from the services' modules.
  • Group by fate. Children that cannot work with a fresh replacement of one another go under a supervisor of their own, with OneForAll or RestForOne. A supervisor is cheap; a wrong strategy over unrelated children restarts what did not fail.
  • Pools are anonymous children. A OneForOne supervisor with no children in its spec, and workers added with actor.StartChild as they are needed, each with an empty name. Once one ends for good the supervisor forgets it, so the pool does not grow with its history.
  • Keep state out of actors and logic out of supervisors. The first makes restarts safe; the second keeps supervisors from failing themselves.
  • Set the intensity for the failure you expect. A dependency that comes back in a minute wants a wider window and more restarts than the default 3 in 5 seconds; a child whose crash means a bug wants to escalate fast.