Application Wiring
What you will learn
By the end of this lesson, you will be able to:
- keep process wiring separate from application behaviour;
- use constructors to enforce required dependencies;
- choose between concrete dependencies and interfaces;
- distinguish liveness, readiness, and startup checks;
- clean up partially created resources safely.
Mental model: one place builds the object graph
The composition root is the outermost code that knows concrete implementations. In a Go service, this normally lives under cmd/<name>.
main
├── load configuration
├── configure logger
├── open database pool
├── create repositories
├── create services
├── create HTTP handlers and server
└── run and shut everything down
Business packages should not open their own databases, read process environment variables, or construct global loggers behind the caller's back.
Constructors make requirements explicit
type LessonService struct {
repository LessonRepository
clock Clock
}
func NewLessonService(repository LessonRepository, clock Clock) (*LessonService, error) {
if repository == nil {
return nil, errors.New("lesson repository is required")
}
if clock == nil {
return nil, errors.New("clock is required")
}
return &LessonService{repository: repository, clock: clock}, nil
}
Constructors are ordinary functions. Use one when values need validation, defaults, invariants, or unexported fields. A plain struct literal is fine for simple data.
Prefer concrete dependencies until abstraction helps
A constructor can accept *sql.DB or *slog.Logger directly when the package genuinely depends on that concrete API. Introduce a small interface at the consumer when substituting behaviour creates a useful boundary.
Avoid large “service container” interfaces that expose every dependency to every package.
Build in stages
func buildApplication(ctx context.Context, config Config, logger *slog.Logger) (_ *Application, err error) {
database, err := sql.Open(config.Database.Driver, config.Database.DSN)
if err != nil {
return nil, fmt.Errorf("open database handle: %w", err)
}
defer func() {
if err != nil {
_ = database.Close()
}
}()
pingCtx, cancel := context.WithTimeout(ctx, config.Database.StartupTimeout)
defer cancel()
if err := database.PingContext(pingCtx); err != nil {
return nil, fmt.Errorf("ping database: %w", err)
}
repository := postgres.NewLessonRepository(database)
service, err := lesson.NewService(repository)
if err != nil {
return nil, fmt.Errorf("create lesson service: %w", err)
}
return NewApplication(config, logger, database, service), nil
}
sql.Open may not establish a connection immediately, so a bounded PingContext checks startup connectivity when the service requires the database before serving traffic.
Whether startup should fail during a temporary dependency outage is an operational choice. Some systems fail fast and let an orchestrator retry; others start unready and reconnect. Document the policy.
Health endpoints have different meanings
- Liveness: Is the process responsive, or should it be restarted? Avoid making it fail solely because a downstream dependency is temporarily unavailable.
- Readiness: Can this instance safely receive normal traffic now? Dependency or migration state may matter.
- Startup: Has slow initialisation finished? Some orchestrators support a separate startup probe.
Keep responses small and avoid exposing dependency addresses, credentials, build internals, or stack traces.
Avoid global mutable dependencies
Package globals make test order significant and prevent multiple differently configured instances in one process.
var database *sql.DB // avoid as hidden shared state
Pass dependencies through constructors and receiver fields instead.
Common mistakes
- A constructor that performs unlimited network work: startup can hang without a caller-controlled context or timeout.
- Interfaces owned by implementations: they grow to expose every method rather than the consumer's need.
- One giant dependency struct passed everywhere: dependencies remain hidden, only behind a different name.
- Readiness that always returns success: traffic reaches an instance unable to perform its main function.
- Liveness tied to every remote dependency: one outage causes restart storms.
- Forgetting partial cleanup: a later constructor failure leaks resources opened earlier.
Practice
Design the composition root for a lesson API with configuration, logger, database, repository, service, handler, and HTTP server. Add a bounded startup database check and separate liveness and readiness handlers.
func run(ctx context.Context, config Config) error {
logger := newLogger(config.Log)
database, err := openDatabase(ctx, config.Database)
if err != nil {
return err
}
defer database.Close()
repository := postgres.NewLessonRepository(database)
service, err := lesson.NewService(repository, time.Now)
if err != nil {
return fmt.Errorf("create lesson service: %w", err)
}
readiness := NewReadiness()
handler := httpapi.New(service, logger, readiness)
server := newHTTPServer(config.HTTP, handler)
readiness.SetReady(true)
return serveUntilCancelled(ctx, server, logger)
}
The outline makes lifetime ownership visible: run opens and closes the database, owns server shutdown, and marks readiness only after construction succeeds. Production code should make readiness state concurrency-safe and decide how loss of a required dependency changes that state.
Summary
- Build concrete dependencies in one outer composition root.
- Constructors enforce required inputs and invariants.
- Prefer narrow consumer-owned interfaces where substitution is useful.
- Bound startup I/O and clean up resources when later construction fails.
- Give liveness, readiness, and startup checks distinct operational meanings.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.