Dependency-aware lifecycle coordination for production Go applications.
go-shutdown is a lightweight, standard-library-first Go module for coordinating startup, readiness, graceful draining, shutdown, and runtime recovery. It never calls os.Exit or log.Fatal; your application retains control of the process.
go get github.com/magnexis/go-shutdown- Explicit component registration with dependency validation and cycle detection.
- Parallel startup for independent components and reverse dependency shutdown.
- Readiness and liveness HTTP handlers for orchestration platforms.
- Graceful drain and stop timeouts with aggregated component errors.
- HTTP listener, SQL database, worker, contextual closer, and generic closer adapters.
- Optional signal waiting without package-level signal state or process termination.
- Opt-in worker restart policies, fixed or exponential backoff, and crash-loop detection.
- Immutable status snapshots and shutdown reports safe to inspect concurrently.
app := shutdown.New(
shutdown.WithDefaultSignals(),
shutdown.WithShutdownTimeout(30*time.Second),
)
if err := app.ManageCloser("database", db); err != nil { return err }
if err := app.ManageWorker("jobs", runJobs, shutdown.DependsOn("database")); err != nil { return err }
if err := app.Run(context.Background()); err != nil {
return fmt.Errorf("lifecycle failed: %w", err)
}Dependencies start before dependents and stop after them:
app.Manage("database", database)
app.Manage("api", api, shutdown.DependsOn("database"))The database starts before the API. During shutdown, the API drains and stops before the database is closed. Independent branches can start concurrently.
Attach tags and a group to make operational selection explicit:
app.Manage("worker-1", worker,
shutdown.WithTags("worker", "email"),
shutdown.WithGroup("email-workers"),
)
workers := app.Components(shutdown.MatchTag("worker"))
layers := app.StartupLayers()Dependencies, Dependents, StartupLayers, and ShutdownLayers return defensive copies suitable for diagnostics and administrative UIs.
The coordinator keeps a bounded in-memory event history for lightweight diagnostics:
app := shutdown.New(shutdown.WithEventHistory(256))
for _, event := range app.Events() {
fmt.Println(event.Sequence, event.Type, event.Component, event.To)
}Events are copied on read and never block lifecycle execution. Set the history limit to 0 to disable retention.
Mount these handlers on your existing administrative mux:
mux.Handle("/ready", app.ReadinessHandler())
mux.Handle("/live", app.LivenessHandler())Readiness becomes false as soon as shutdown begins, giving load balancers time to withdraw traffic before components drain.
Use maintenance mode for planned work without making the process unhealthy:
if err := app.EnterMaintenance(ctx, "database migration", shutdown.DrainDuringMaintenance()); err != nil { return err }
defer app.ExitMaintenance(ctx)Components can optionally implement Pauser and Resumer (or provide Hooks.Pause and Hooks.Resume). If graceful stopping times out, an optional ForceStopper or Hooks.ForceStop is invoked. Inspect app.Report() or errors.As(err, *shutdown.ShutdownError) to identify cleanup failures and components that did not stop.
Restarts are always opt-in. This worker can restart after transient runtime failures, with a bounded exponential delay and a restart budget:
app.ManageWorker("notifications", runNotifications,
shutdown.RestartPolicy(
shutdown.OnFailure(),
shutdown.MaxRestarts(5),
shutdown.RestartWindow(time.Minute),
shutdown.Backoff(shutdown.ExponentialBackoff(500*time.Millisecond, 15*time.Second)),
),
)If the budget is exhausted, the component enters crash_loop. A critical component requests an orderly application shutdown; it still does not terminate the process directly.
Implement Component directly, or use Hooks for functions:
type Component interface {
Start(context.Context) error
Stop(context.Context) error
}Optional capabilities are discovered through Drainer, ReadinessProvider, and Runner. Components must honor cancellation; Go cannot safely force arbitrary goroutines to stop.
Set the application shutdown timeout below terminationGracePeriodSeconds, and route your readiness probe to /ready:
terminationGracePeriodSeconds: 40
readinessProbe:
httpGet: { path: /ready, port: 8080 }
livenessProbe:
httpGet: { path: /live, port: 8080 }go test ./...
go test -race ./...
go vet ./...
npm run check:pages # Node.js 24, for GitHub Pages source validationThe CI workflow runs these checks on supported hosted runners. GitHub Pages deploys the docs/ site after main changes once Pages is configured to use GitHub Actions.
The module is in active pre-1.0 development. The lifecycle kernel and initial restart supervision are implemented. Optional integrations such as gRPC, tracing, metrics, durable journals, and remote control APIs are intentionally not included in the core package yet.
