Skip to content

About

`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.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

4 Commits

Folders and files

Repository files navigation

go-shutdown

Official go-shutdown logo

Dependency-aware lifecycle coordination for production Go applications.

CI status Go Reference MIT License Go 1.24 or later

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.

Install

go get github.com/magnexis/go-shutdown

What it provides

  • 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.

Basic application

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)
}

Dependency ordering

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.

Component metadata and graph inspection

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.

Lifecycle events

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.

Readiness and liveness

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.

Maintenance and shutdown diagnostics

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.

Restartable workers

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.

Lifecycle contract

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.

Kubernetes

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 }

Development

go test ./...
go test -race ./...
go vet ./...
npm run check:pages # Node.js 24, for GitHub Pages source validation

The 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.

Status and scope

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.

About

`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.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages