Restart Failed Workers With Supervisor Loop

A supervisor loop respawns a worker goroutine after each recovered panic, stops once the worker completes, and gives up after a fixed attempt budget.

GoResilience

Code

gosnippet
35 lines
package main

import "fmt"

// worker 前两次尝试会 panic 崩溃,监督循环捕获后重新拉起
func worker(attempt int) {
	if attempt < 3 {
		panic(fmt.Sprintf("worker crashed on attempt %d", attempt))
	}
	fmt.Println("worker healthy on attempt", attempt)
}

func main() {
	maxAttempts := 5
	for attempt := 1; attempt <= maxAttempts; attempt++ {
		result := make(chan string, 1)
		go func(a int) {
			defer func() {
				if r := recover(); r != nil {
					result <- fmt.Sprintf("restarted: %v", r)
				}
			}()
			worker(a)
			result <- "ok"
		}(attempt)

		if msg := <-result; msg != "ok" {
			fmt.Println("supervisor:", msg)
			continue // 崩溃后重启 worker
		}
		fmt.Println("supervisor: worker stable")
		return
	}
	fmt.Println("supervisor: gave up after", maxAttempts, "attempts")
}

How it works

Restart Failed Workers With Supervisor Loop reduces to the functions worker and main.

The file repeats itself only inside for attempt := 1; attempt <= maxAttempts; attempt++. Execution fans onto a goroutine and re-converges through a channel handoff. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Caveats

  • Self-contained — imports go no further than what the runtime provides.

Using it

Signature: func worker(attempt int)

The output comes back labeled — worker healthy on attempt, supervisor:, supervisor: worker stable — when the file runs.

main sequences worker; executing the file runs that flow once.

The key statements that remain

panic(fmt.Sprintf("worker crashed on attempt %d", attempt))
result <- fmt.Sprintf("restarted: %v", r)
if msg := <-result; msg != "ok" {
	fmt.Println("supervisor:", msg)
	continue // 崩溃后重启 worker
}

Interactive Tools for This Topic

FAQ

What does Restart Failed Workers With Supervisor Loop print when run?
The script runs standalone; its 4 labeled outputs include `worker healthy on attempt`, `supervisor:`, `supervisor: worker stable`.