Manage resource lifecycle and shutdown
Manage resource lifecycle and shutdown
The composition root connects resources and decides who closes them. Acquire in dependency order and release in reverse order. On initialization failure, release resources already acquired. During shutdown, stop accepting work, cancel and join owned workers, then close dependencies. Cancellation alone is not proof of completion.
package main
import ( "errors" "fmt" "io")
type Resource struct { Name string Log *[]string}
func (r Resource) Close() error { *r.Log = append(*r.Log, r.Name); return nil }func closeAll(rs []io.Closer) error { var err error for i := len(rs) - 1; i >= 0; i-- { err = errors.Join(err, rs[i].Close()) } return err}func main() { var events []string rs := []io.Closer{Resource{"store", &events}, Resource{"worker", &events}} err := closeAll(rs) fmt.Println(events, err)}Each resource is closed once by this call, in reverse order. errors.Join preserves multiple cleanup failures and returns nil when all are nil. Here names only illustrate order; a real worker must finish before the store closes. Do not assume every io.Closer supports repeated Close calls.
Expected output:
[worker store] <nil>Cancel and wait for an owned worker
package main
import ( "context" "fmt")
func main() { ctx, cancel := context.WithCancel(context.Background()) done := make(chan struct{}) go func() { defer close(done); <-ctx.Done() }() cancel() <-done fmt.Println("worker stopped", ctx.Err())}The worker acknowledges completion by closing done. Receiving after cancellation establishes that its work has finished. Production shutdown needs a deadline and a policy for unfinished work; never close shared dependencies while workers still use them. Coordinate HTTP Server.Shutdown with background workers.
Expected output:
worker stopped context canceledTry it locally
Invoke two cleanup callbacks in reverse order even if the second fails, and join their errors. Print order and errors.Is for the failure.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Professional architecture 06: Manage resource lifecycle and shutdown
Check the lesson objective before moving on.
Why close resources in reverse acquisition order?
What does calling cancel guarantee?