Squad manages a group of named components that start together and stop together. Startup and shutdown ordering is derived from the dependency graph declared between components, so a service can guarantee that an HTTP server drains inflight requests before the database connection pool it depends on is destroyed.
A component bundles three optional functions:
init— runs during startup, before any goroutine starts;run— the component's background goroutine, started after all inits succeed;close— runs during the shutdown walk.
Components declare dependencies on other component handles. The graph is
built and validated by New:
- Startup runs in two phases. First, init functions run in topological order — a component's init starts only after every dependency init completes — with parallelism within each dependency level. Only after every init succeeds do the component goroutines start. A failed init rolls back the already-initialized components in reverse dependency order and returns the joined errors; no goroutine starts.
- Shutdown runs close functions in reverse topological order — a
component's close runs only after all its dependents' closes complete — again
with parallelism within each level. The whole walk is bounded by a single
global graceful-period deadline (
WithGracefulPeriod, default 30s), so a slow close reduces the budget left for the remaining levels. - The walk continues on error: a failing close does not stop or cancel the
deadline; all close errors are wrapped with the component name and aggregated
with
errors.Join. - Goroutines still running when the deadline expires are abandoned, and
context.DeadlineExceededis joined into the result.
The shutdown walk starts when any of the following occurs: the first OS
signal, Stop(), or the exit of any component goroutine — clean or with an
error. Call Wait() promptly after New().
package main
import (
"context"
"log"
"net/http"
"time"
"github.com/moeryomenko/squad/v2"
)
func main() {
// A database component: init opens the pool, close destroys it. The
// run goroutine keeps the component alive until shutdown.
db := squad.NewComponent("db",
func(ctx context.Context) error {
log.Printf("opening connection pool")
return nil
},
func(ctx context.Context) error {
<-ctx.Done()
return nil
},
func(ctx context.Context) error {
log.Printf("closing connection pool")
return nil
},
)
// An HTTP server that depends on the database: startup initializes the
// DB first, shutdown drains the server before the pool closes.
srv := &http.Server{Addr: ":8080", ReadHeaderTimeout: 5 * time.Second}
httpServer := squad.NewHTTPServer("http", srv, db)
s, err := squad.New(
squad.WithComponents(httpServer),
squad.WithGracefulPeriod(5 * time.Second),
)
if err != nil {
log.Fatalf("startup failed: %v", err)
}
// Blocks until a signal, Stop(), or a component goroutine exit, then
// runs the shutdown walk.
if err := s.Wait(); err != nil {
log.Fatalf("shutdown error: %v", err)
}
}s, err := squad.New(opts ...Option)New builds and validates the dependency graph from the registered
components, runs the init phase in topological order, starts the component
goroutines only after every init succeeds, and installs the signal handler.
If any init fails, the successfully initialized components are rolled back in
reverse dependency order and the joined error is returned.
| Symbol | Description |
|---|---|
NewComponent(name string, init, run, close func(ctx) error, deps ...*Component) *Component |
Creates a component handle. All function parameters are optional (nil allowed); deps declare the handles this component depends on and are auto-registered. The name must be non-empty (validated by New). |
NewHTTPServer(name string, srv *http.Server, deps ...*Component) *Component |
Creates a component whose run calls srv.ListenAndServe() and whose close calls srv.Shutdown(ctx) — stops accepting new connections and waits for inflight requests, bounded by the walk deadline. http.ErrServerClosed counts as a clean exit. |
WithComponents(comps ...*Component) Option |
Registers components for the graph. Nil components are skipped; dependency handles are auto-registered. |
WithGracefulPeriod(d time.Duration) Option |
Sets the single global graceful shutdown deadline for the whole walk. Default: 30s. |
WithSignals(sigs ...os.Signal) Option |
Overrides the default signal set (SIGINT, SIGTERM, SIGHUP). |
WithSecondSignalHandler(fn func()) Option |
Overrides the default second-signal behaviour (os.Exit(1)). |
| Method | Description |
|---|---|
Wait() error |
Drives the shutdown walk on the first trigger (signal, Stop(), or any goroutine exit), runs closes in reverse dependency order under the global deadline, waits for straggler goroutines, and returns the joined errors. Single-use. |
Stop() |
Cancels the squad context, triggering the shutdown walk once Wait is called. Idempotent. |
Done() <-chan struct{} |
Returns a channel that is closed when shutdown begins (the squad context is cancelled). |
Go(fn func()) |
Starts a tracked fire-and-forget goroutine; panics are recovered, and the goroutine's exit triggers the walk like any component run. |
Cause() error |
Returns the error that triggered shutdown: the first goroutine error, context.Canceled if a signal or Stop triggered it, or nil for a clean goroutine exit. Valid after Wait. |
Squad installs a signal handler for SIGINT, SIGTERM, and SIGHUP by
default (configurable via WithSignals). The handler starts only after the
init phase succeeds.
- First signal: cancels the squad context, triggering the shutdown walk.
- Second signal (within graceful period + 5s): forces an immediate exit —
by default
os.Exit(1), overridable withWithSecondSignalHandler.
First trigger (signal / Stop() / goroutine exit)
|
v
Wait() detects trigger -> walk starts
|
v
close functions run in REVERSE topological order
(dependents first, parallel within each level)
all bounded by ONE global graceful-period deadline
failing closes do not stop the walk
|
v
straggler goroutines wait under the same deadline
|
v
Wait() returns errors.Join(walk errors, goroutine errors, deadline error?)
For db := NewComponent("db", initDB, nil, closeDB) and
http := NewHTTPServer("http", srv, db), shutdown runs srv.Shutdown — the
server stops accepting connections and drains inflight requests — before
closeDB runs. This is the ordering the old flat lifecycle could not express.
The module path changed to github.com/moeryomenko/squad/v2, and the flat
lifecycle API was replaced by the dependency graph. The removed symbols:
Run, RunGracefully, RunServer, WithBootstrap, WithCloses,
WithSubsystem.
import "github.com/moeryomenko/squad"
s, err := squad.New(
squad.WithGracefulPeriod(5 * time.Second),
squad.WithBootstrap(func(ctx context.Context) error {
return initDB(ctx) // no ordering: HTTP may start before the DB
}),
squad.WithCloses(func(ctx context.Context) error {
return closeDB(ctx)
}),
)
if err != nil {
log.Fatal(err)
}
s.RunServer(&http.Server{Addr: ":8080"}) // deadlock risk on signal
s.Run(func(ctx context.Context) error { /* worker */ return nil })
if err := s.Wait(); err != nil {
log.Fatal(err)
}import "github.com/moeryomenko/squad/v2"
db := squad.NewComponent("db", initDB, nil, closeDB)
srv := &http.Server{Addr: ":8080", ReadHeaderTimeout: 5 * time.Second}
httpServer := squad.NewHTTPServer("http", srv, db) // depends on db
s, err := squad.New(
squad.WithComponents(httpServer),
squad.WithGracefulPeriod(5 * time.Second),
)
if err != nil {
log.Fatal(err)
}
if err := s.Wait(); err != nil {
log.Fatal(err)
}The DB initializes before the server starts, and on shutdown the server drains inflight requests before the DB pool closes.
| Removed (v1) | Replacement (v2) |
|---|---|
Run(fn) |
NewComponent(name, nil, fn, nil) registered via WithComponents |
RunGracefully(background, onDown) |
NewComponent(name, nil, background, onDown) |
RunServer(srv) |
NewHTTPServer(name, srv) |
WithBootstrap(fns ...) |
init functions on components: NewComponent(name, fn, ...) — now ordered by the graph |
WithCloses(fns ...) |
close functions on components: NewComponent(name, nil, nil, fn) — now ordered by the graph |
WithSubsystem(init, close) |
NewComponent(name, init, nil, close) |
- Ordering is now guaranteed: bootstraps/closes no longer run concurrently; they run in topological order, parallel only within levels.
- Init failure rolls back: already-initialized components are closed in
reverse dependency order before
Newreturns; v1 left them behind. - Goroutine exit triggers shutdown: any component goroutine exiting — cleanly or with an error — starts the walk (v1 only shut down on signal or error). A worker that returns early therefore stops the whole service.
- Global deadline: the graceful period bounds the entire walk plus the straggler wait, not each close individually.
- Go 1.25+
make fmt— format code with gofmt, golines, and goimports.make lint— run golangci-lint.make test— run tests with race detector and coverage.
Dual-licensed under Apache 2.0 and MIT.