shutdown

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

shutdown

Go Reference CI Go Report Card Coverage

Declarative graceful shutdown orchestrator for Go microservices.

Every Go microservice needs graceful shutdown. The standard approach is 50+ lines of boilerplate with signal.NotifyContext, sync.WaitGroup, and manual error handling scattered across main(). Existing libraries like ory/graceful only work with HTTP servers. shutdown works with any component — HTTP, gRPC, database pools, message consumers, background workers, cron jobs.

Features

  • Universal — works with any component implementing a simple Close(ctx) error interface
  • Priority groups — components with the same priority shut down in parallel; groups execute sequentially
  • Per-component timeouts — override the global timeout for individual components
  • Thread-safe — concurrent Register and Shutdown calls are safe
  • Idempotent — calling Shutdown multiple times is safe; closers execute exactly once
  • Double-signal force exit — first signal starts graceful shutdown, second forces os.Exit(1)
  • Structured logging — built-in log/slog progress logging
  • Zero dependencies — only Go standard library

Installation

go get github.com/krus210/shutdown

Requires Go 1.21+ (for log/slog).

Quick Start

package main

import (
    "context"
    "log/slog"
    "net/http"
    "time"

    "github.com/krus210/shutdown"
)

func main() {
    httpServer := &http.Server{Addr: ":8080"}
    go httpServer.ListenAndServe()

    s := shutdown.New(shutdown.WithTimeout(15 * time.Second))

    s.RegisterFunc("http-server", httpServer.Shutdown)

    if err := s.Listen(context.Background()); err != nil {
        slog.Error("shutdown completed with errors", "error", err)
    }
}

Priority Groups

Components with different priorities shut down sequentially (lowest first). Components with the same priority shut down in parallel.

s := shutdown.New()

// Priority 0: stop accepting requests
s.RegisterFunc("http-server", httpServer.Shutdown, shutdown.WithPriority(0))
s.RegisterFunc("grpc-server", grpcServer.Shutdown, shutdown.WithPriority(0))

// Priority 1: drain in-flight work
s.RegisterFunc("worker", worker.Stop, shutdown.WithPriority(1))

// Priority 2: close infrastructure last
s.RegisterFunc("pg-pool", func(ctx context.Context) error {
    db.Close()
    return nil
}, shutdown.WithPriority(2))

Execution timeline:

Group 0:  |--- http ---|
          |--- grpc ---|
                        Group 1:  |--- worker ---|
                                                   Group 2:  |--- pg-pool ---|

If no priority is set, components shut down in registration order (each gets a unique auto-incremented priority).

Timeouts

The global timeout (default: 30s, matching Kubernetes terminationGracePeriodSeconds) applies to the entire shutdown process. Per-component timeouts can make individual components fail faster, but never exceed the global timeout.

s := shutdown.New(shutdown.WithTimeout(15 * time.Second))

// This component gets 5s max, even though global is 15s
s.RegisterFunc("cache", redisClient.Close,
    shutdown.WithComponentTimeout(5 * time.Second),
)

// This component inherits the global 15s timeout
s.RegisterFunc("database", func(ctx context.Context) error {
    db.Close()
    return nil
})

Custom Logger

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelDebug,
}))

s := shutdown.New(shutdown.WithLogger(logger))

Example log output during shutdown:

level=INFO msg="shutdown started" timeout=15s
level=INFO msg="closing component" name=http-server priority=0
level=INFO msg="component closed" name=http-server elapsed=12ms
level=INFO msg="closing component" name=pg-pool priority=1
level=INFO msg="component closed" name=pg-pool elapsed=3ms
level=INFO msg="shutdown completed successfully" elapsed=18ms

Error Callback

Handle individual component errors as they occur:

s := shutdown.New(shutdown.WithOnError(func(name string, err error) {
    slog.Error("component shutdown failed", "name", name, "error", err)
    // Send to Sentry, increment metric, etc.
}))

All errors are also aggregated and returned from Shutdown() / Listen().

The Closer Interface

Any type implementing Close(ctx context.Context) error works directly:

type Closer interface {
    Close(ctx context.Context) error
}

For types that don't match the interface, use CloserFunc or RegisterFunc:

// pgxpool.Pool.Close() has no context and no error
s.RegisterFunc("pg-pool", func(ctx context.Context) error {
    pool.Close()
    return nil
})

// http.Server.Shutdown matches the Closer interface
s.Register("http", shutdown.CloserFunc(httpServer.Shutdown))

Comparison

Feature shutdown ory/graceful Manual approach
Any component type Yes HTTP only Yes
Priority ordering Yes No Manual
Parallel within group Yes No Manual
Per-component timeouts Yes No Manual
Idempotent shutdown Yes No Manual
Double-signal exit Yes No Manual
Structured logging Yes No Manual
Error aggregation Yes No Manual
Lines of code needed ~10 ~5 50+

API Reference

Full documentation is available on pkg.go.dev.

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure go test -race ./... passes
  5. Submit a pull request

License

MIT

Documentation

Overview

Package shutdown provides a declarative graceful shutdown orchestrator for Go microservices.

It works with any component that implements the Closer interface — HTTP servers, gRPC servers, database pools, message consumers, background workers, and more.

Components are organized into priority groups. Groups execute sequentially (lowest priority number first), while components within the same group shut down in parallel.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Closer

type Closer interface {
	Close(ctx context.Context) error
}

Closer is the interface that any managed component must implement. Close should gracefully shut down the component, respecting the provided context for cancellation and deadlines.

Many Go types already satisfy this interface or can be easily adapted. For example, *http.Server has a Shutdown(ctx) method that matches the signature.

type CloserFunc

type CloserFunc func(ctx context.Context) error

CloserFunc is an adapter that allows ordinary functions to be used as Closer. It follows the same pattern as net/http.HandlerFunc.

func (CloserFunc) Close

func (f CloserFunc) Close(ctx context.Context) error

Close calls f(ctx).

type ComponentOption

type ComponentOption func(*componentConfig)

ComponentOption configures a single registered component.

func WithComponentTimeout

func WithComponentTimeout(d time.Duration) ComponentOption

WithComponentTimeout overrides the global timeout for this component. If the component timeout is longer than the remaining global timeout, the global timeout takes precedence (context deadlines propagate).

func WithPriority

func WithPriority(p int) ComponentOption

WithPriority sets the shutdown priority for a component. Lower numbers shut down first. Components with the same priority shut down in parallel. The default priority is assigned based on registration order (first registered = lowest priority = shuts down first).

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager orchestrates graceful shutdown of all registered components.

Components are shut down in priority order: lower priority numbers shut down first. Components with the same priority shut down in parallel. If no priority is set, components shut down in registration order.

Manager is safe for concurrent use.

Example (Basic)
package main

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"time"

	"github.com/krus210/shutdown"
)

func discardLogger() *slog.Logger {
	return slog.New(slog.NewTextHandler(io.Discard, nil))
}

func main() {
	mgr := shutdown.New(
		shutdown.WithTimeout(5*time.Second),
		shutdown.WithLogger(discardLogger()),
	)

	mgr.RegisterFunc("http-server", func(_ context.Context) error {
		fmt.Println("http server stopped")
		return nil
	})

	mgr.RegisterFunc("database", func(_ context.Context) error {
		fmt.Println("database connection closed")
		return nil
	})

	_ = mgr.Shutdown(context.Background())
}
Output:
http server stopped
database connection closed
Example (CloserInterface)
package main

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"time"

	"github.com/krus210/shutdown"
)

func discardLogger() *slog.Logger {
	return slog.New(slog.NewTextHandler(io.Discard, nil))
}

// DBConn demonstrates implementing the Closer interface.
type DBConn struct{}

// Close implements shutdown.Closer.
func (d *DBConn) Close(_ context.Context) error {
	fmt.Println("db connection closed")
	return nil
}

func main() {
	mgr := shutdown.New(
		shutdown.WithTimeout(5*time.Second),
		shutdown.WithLogger(discardLogger()),
	)

	mgr.Register("database", &DBConn{})

	_ = mgr.Shutdown(context.Background())
}
Output:
db connection closed
Example (Priority)
package main

import (
	"context"
	"fmt"
	"io"
	"log/slog"
	"time"

	"github.com/krus210/shutdown"
)

func discardLogger() *slog.Logger {
	return slog.New(slog.NewTextHandler(io.Discard, nil))
}

func main() {
	mgr := shutdown.New(
		shutdown.WithTimeout(5*time.Second),
		shutdown.WithLogger(discardLogger()),
	)

	mgr.RegisterFunc("http-server", func(_ context.Context) error {
		fmt.Println("1: http server stopped")
		return nil
	}, shutdown.WithPriority(0))

	mgr.RegisterFunc("worker", func(_ context.Context) error {
		fmt.Println("2: worker stopped")
		return nil
	}, shutdown.WithPriority(1))

	mgr.RegisterFunc("database", func(_ context.Context) error {
		fmt.Println("3: database closed")
		return nil
	}, shutdown.WithPriority(2))

	_ = mgr.Shutdown(context.Background())
}
Output:
1: http server stopped
2: worker stopped
3: database closed

func New

func New(opts ...Option) *Manager

New creates a new shutdown Manager with the given options.

func (*Manager) Listen

func (m *Manager) Listen(ctx context.Context) error

Listen blocks until an OS signal is received (SIGINT and SIGTERM by default), then initiates graceful shutdown. A second signal forces immediate exit via os.Exit(1).

Listen also triggers shutdown if the provided context is cancelled.

Returns an aggregated error if any component failed to shut down.

func (*Manager) Register

func (m *Manager) Register(name string, closer Closer, opts ...ComponentOption) *Manager

Register adds a component to the shutdown manager. Components are stopped in reverse registration order by default, or by explicit priority (lower number = stops first).

Register returns the Manager to allow method chaining.

Register panics if closer is nil.

func (*Manager) RegisterFunc

func (m *Manager) RegisterFunc(name string, fn func(ctx context.Context) error, opts ...ComponentOption) *Manager

RegisterFunc is a convenience method that registers a function as a Closer. It wraps fn in a CloserFunc and delegates to Manager.Register.

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown initiates graceful shutdown of all registered components. Components are stopped according to their priority: lower priority numbers first. Components with the same priority are stopped in parallel.

Shutdown is idempotent — calling it multiple times is safe. Subsequent calls block until the first invocation completes and return the same error.

type Option

type Option func(*managerConfig)

Option configures the Manager.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets a custom *slog.Logger for structured shutdown logging. The default is slog.Default.

func WithOnError

func WithOnError(fn func(name string, err error)) Option

WithOnError sets a callback that is invoked when a component fails to shut down. The callback receives the component name and the error.

func WithSignals

func WithSignals(signals ...os.Signal) Option

WithSignals sets the OS signals that trigger graceful shutdown. The default signals are SIGINT and SIGTERM.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the global shutdown timeout. The default is 30 seconds. This timeout is applied as a context deadline wrapping the parent context passed to Manager.Shutdown or Manager.Listen.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL