Writing / September 26, 2026

A Lifecycle Core for Go Application Orchestration

A small Go lifecycle core for explicit startup, readiness, shutdown, and app-scoped dependencies.

gosoftware-engineeringlibraries

Go applications often grow a lifecycle framework inside main. It begins as a few constructors and defer calls, which is reasonable while every resource has a simple lifetime:

db := openDB()
defer db.Close()

nats := connectNATS()
defer nats.Close()

server := startHTTP(db, nats)
defer server.Shutdown(ctx)

The shape becomes harder to reason about when the database needs migrations before handlers use it, a subscription must drain during shutdown, and a worker needs app-wide cancellation. A CLI command may also need the same setup and cleanup as the service without blocking forever. Startup order becomes implicit, cleanup becomes a collection of unrelated operations, and dependencies are tempted into globals so runtime code can find values created in main.

I built go-app to make that application boundary explicit. It has four responsibilities:

  • Start components in a caller-defined shape.
  • Transfer lifecycle ownership after successful initialization.
  • Stop initialized components deterministically, using reverse registration order during normal shutdown.
  • Provide a typed app-scoped registry during assembly.

It is not a dependency injection container. It does not solve a graph or wire constructors through reflection, and it does not treat all operational readiness as a global startup barrier. The application still owns its architecture.

An open slate-blue control cabinet contains a central controller and four modules with green status lights, joined by neatly routed blue and amber wiring.
Independent components, one explicit lifecycle boundary.

The Lifecycle Boundary

A stateful part of the application exposes a component with explicit initialization and cleanup callbacks:

func (s *Store) Component() *app.Component {
	return app.NewComponent(
		app.WithName("store"),
		app.WithOnStart(s.Start),
		app.WithOnStop(s.Stop),
	)
}

Start(ctx) performs setup, starts any owned resources or runtime goroutines, and then returns. It is not the runtime loop. Long-running work belongs in a resource or goroutine that Stop(ctx) can shut down.

The return value determines lifecycle ownership. A nil result means the component initialized successfully and the app now owns calling Stop during normal shutdown or rollback. An error means ownership did not transfer, so Start must release anything it acquired before returning:

func (s *Server) Start(ctx context.Context) error {
	listener, err := net.Listen("tcp", s.addr)
	if err != nil {
		return err
	}

	if err := s.configure(listener); err != nil {
		_ = listener.Close()
		return err
	}

	s.listener = listener
	return nil
}

This cleanup rule matters because the app calls OnStop only for callbacks that returned nil. The compact contract is:

Lifecycle ownership contract
OnStart returned nil
Initialization succeeded and lifecycle ownership transferred to the app.
OnStart returned an error
Initialization failed and the callback cleans any partial acquisitions.
OnStop returned nil
App-owned cleanup completed.

The resulting lifecycle keeps assembly, runtime, and cleanup distinct:

go-app lifecycle
config WithDependency
->
store Registered
->
api Initialized
RuntimeContext is live. Handlers and workers use fields, not registry lookups.

Where The Design Comes From

The main influence is Stuart Sierra’s component library for Clojure. A database connection, server, scheduler, or cache differs from ordinary pure code because it has runtime state that must be initialized in relation to other resources and cleaned up in a deliberate order. That is the central idea go-app borrows.

The orchestration differs. Clojure Component records dependency relationships and starts a system in dependency order, while go-app leaves the startup shape at the call site. Sequential and concurrent groups are explicit, and the core does not construct or solve a dependency graph.

Martin Fowler’s article on dependency injection and service locators supplies another design constraint: separate service configuration from service use. Components can resolve dependencies at lifecycle boundaries, but handlers and domain logic should use ordinary fields and parameters after assembly.

Fowler’s Registry pattern also describes the risk. A registry used throughout the application becomes global state under another name, so go-app narrows the pattern in two ways:

  • The registry belongs to one app instance, not the process.
  • Lookup is intended for lifecycle boundaries, not arbitrary runtime code.

go-app puts a small Go-shaped boundary around these system-design ideas while keeping the application architecture visible.

The project now has a deliberate scope split. go-app is the stable lifecycle core, while go-toolbelt is the faster-moving companion for concrete components, delivery adapters, and recipes. This article stays with the core contract because those companion packages can evolve without changing lifecycle ownership.

The Caller Owns Startup Shape

Most applications can state their startup order sequentially:

a := app.New(ctx,
	app.WithDependency(cfg),
	app.WithSequentialStartup(
		app.Registered(store),
		app.Registered(server),
	),
)

app.Registered(store) adds the provider to lifecycle management and registers the concrete store value for typed lookup. app.Managed(component) manages lifecycle without registering the provider value. Registration happens during app assembly, before startup callbacks run.

Independent components can initialize in one concurrent group before the app advances to the next group:

a := app.New(ctx,
	app.WithConcurrentStartup(
		app.Registered(store),
		app.Registered(nats),
		app.Registered(model),
	),
	app.WithSequentialStartup(
		app.Registered(api),
	),
)

The call site states a coarse startup shape directly:

Concurrent group, then API
store
nats
model
after every OnStart returns nil
api

For a concurrent group, every OnStart callback runs and the next group begins only after all callbacks return nil. This is an initialization barrier, not proof that every provider is operationally ready. A consumer that needs a stronger guarantee must opt into the provider’s readiness contract.

Readiness Belongs To The Provider

Starting a goroutine is not the same as being ready, and go-app does not pretend otherwise. Returning nil from OnStart says initialization completed and ownership transferred to the app. Operational readiness remains a contract defined by the provider.

Sometimes initialization itself can provide the required guarantee. A store can open and verify its database before returning:

func (s *Store) Start(ctx context.Context) error {
	db, err := sql.Open("sqlite", s.dsn)
	if err != nil {
		return err
	}

	if err := db.PingContext(ctx); err != nil {
		_ = db.Close()
		return err
	}

	s.db = db
	return nil
}

For consumers whose contract only requires a successful ping, this store is ready when Start returns. If readiness must emerge asynchronously, the provider exposes a shared signal instead of asking the lifecycle core to wait for it automatically:

type Database struct {
	ready chan struct{}
}

func NewDatabase() *Database {
	return &Database{ready: make(chan struct{})}
}

func (d *Database) Ready() <-chan struct{} { return d.ready }

func (d *Database) Start(ctx context.Context) error {
	runtime := app.MustGet[app.RuntimeContext](ctx)
	go d.probeUntilReady(runtime)
	return nil
}

Only consumers that need that stronger guarantee wait for it, and they do so from their own Start(ctx):

func (a *API) Start(ctx context.Context) error {
	database := app.MustGet[*Database](ctx)
	select {
	case <-database.Ready():
		a.database = database
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

The database owns what closing Ready() means, and multiple consumers can wait on the same signal. Unrelated components do not wait, while the startup timeout still bounds a consumer’s wait through its startup context.

Startup Time Is Not Runtime Time

Start(ctx) receives a startup control context carrying registry values and startup cancellation or deadline. It is appropriate for migrations, connection checks, model loading, subscription setup, and consumer readiness waits. It should not be retained by app-lifetime goroutines.

Runtime work resolves the separately registered app.RuntimeContext during startup and passes it to the owned goroutine:

func (w *Worker) Start(ctx context.Context) error {
	runtime := app.MustGet[app.RuntimeContext](ctx)
	go w.run(runtime)
	return nil
}

This separation allows the whole startup phase to time out without imposing that same deadline on a successfully initialized application’s runtime. RuntimeContext carries app-lifetime cancellation and the app-scoped registry values available when it is created.

A component that needs to request app-wide cancellation later can resolve app.RequestShutdownFunc during startup and store the function, as a TUI quit command or HTTP shutdown endpoint might. Calling it only cancels the app runtime context. Run observes that cancellation and cleans up, a RunOnce callback must return before RunOnce closes the app, and manually controlled code must call Close or request shutdown before calling Stop.

Normal Shutdown Reverses Registration

For a simple sequential registration, shutdown reverses the same order:

Deterministic reverse order
Startup
  1. store
  2. server
Shutdown
  1. server
  2. store

During normal shutdown, the exact rule is reverse registration order rather than reverse callback completion order. Groups stop in reverse group order, and components inside a concurrent group stop in reverse item order. This keeps normal shutdown deterministic even when concurrent OnStart callbacks finish in a different order on each run.

Only initialized components whose OnStart returned nil are stopped. Startup rollback has one additional case: the app first rolls back components already known to be initialized, then waits for outstanding start callbacks within the shutdown bound and stops any pending callback that returned nil during that wait. Those late completions are handled after the initial rollback, so a failed concurrent startup does not guarantee one strict reverse-registration stop sequence across both phases. A callback that returns an error remains responsible for its own partial acquisitions.

The shutdown operations have intentionally different meanings:

  • RequestShutdown() cancels runtime but does not stop components.
  • Stop(ctx) stops components but does not cancel runtime.
  • Close(ctx) requests shutdown, stops components, and waits for startup callbacks.

Run starts the app, waits for app cancellation or a handled signal, then stops components and waits for start callbacks. RunOnce starts the app, invokes a function with the app context, closes the app, and joins callback and shutdown errors. Lifecycle methods are not safe to call concurrently on the same app.

Direct Stop(ctx) and Close(ctx) use the caller’s context to control cleanup. Their stop callbacks still receive app-scoped registry values after runtime cancellation, so cleanup can resolve lifecycle dependencies without reviving runtime work.

The Registry Stops At The Boundary

The typed registry exists for application assembly and lifecycle boundaries:

func (s *Server) Start(ctx context.Context) error {
	s.store = app.MustGet[*Store](ctx)
	return nil
}

Values are keyed by their exact Go type, and registering the same type again replaces the value returned by later lookups. After startup, handlers and domain code use fields and ordinary parameters instead of reaching back into the registry.

If registry lookups spread through request handlers, stores, and deep helpers, the registry has become a service locator. The core cannot prevent that mistake, but its intended boundary is narrow: resolve dependencies during lifecycle assembly, store them on the component, then return to ordinary Go.

Why There Is No Graph Solver

A dependency graph could let components declare requirements while a framework sorts them, detects cycles, and starts independent branches concurrently. It would also change go-app from a lifecycle core into a dependency injection container, introducing dependency metadata and graph semantics that the current contract does not need.

The caller already knows that a store must initialize before an API can consume it. Writing that coarse order at the assembly boundary, then putting any stronger readiness wait in the consumer, keeps both the topology and the operational contract visible.

Services And Commands Use The Same Model

A long-running service can hand the complete lifecycle to Run:

if err := a.Run(); err != nil {
	log.Fatal(err)
}

A short-lived CLI command can use the same managed dependencies without waiting indefinitely:

return a.RunOnce(cmd.Context(), func(ctx context.Context) error {
	return runCommand(store.DB())
})

This is one of the shapes I wanted from the core. A command can initialize a database, run migrations, execute ordinary business logic, and clean everything up through the same lifecycle contract as a service. Code that needs custom control can call Start and later Close; direct Stop is narrower because it does not request shutdown or cancel RuntimeContext.

The Intended Boundary

go-app does not provide configuration, metrics, tracing, health checks, restart semantics, reflection wiring, or a global mutable app. The caller still decides:

  • What startup order means.
  • Which components can start concurrently.
  • What readiness means for each provider.
  • Which values belong in app scope.
  • How runtime concerns are represented.

Those constraints are the design rather than gaps to hide. go-app should make lifecycle ownership predictable without making application architecture disappear.