Golang / GoLang System Architecture and Testing Interview Questions
How do you manage the full lifecycle of a Go microservice from startup to shutdown?
A production Go service follows a structured lifecycle: configuration validation, dependency initialisation, readiness signalling, traffic serving, graceful shutdown on signal, and cleanup. Each phase must handle failures correctly.
func main() {
// Phase 1: load and validate config — fail fast
cfg, err := config.Load()
if err != nil { log.Fatalf("invalid config: %v", err) }
// Phase 2: initialise dependencies
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: cfg.LogLevel,
}))
slog.SetDefault(logger)
db, err := database.Open(cfg.Database)
if err != nil { log.Fatalf("database: %v", err) }
defer db.Close()
// Phase 3: build services
userRepo := postgres.NewUserRepository(db)
userSvc := service.NewUserService(userRepo)
router := api.NewRouter(userSvc)
// Phase 4: start server
srv := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
errCh := make(chan error, 1)
go func() {
slog.Info("server starting", "port", cfg.Port)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
}()
// Phase 5: wait for shutdown or error
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
select {
case err := <-errCh:
slog.Error("server error", "err", err)
case sig := <-sigCh:
slog.Info("shutdown signal", "signal", sig)
}
// Phase 6: graceful shutdown
shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown error", "err", err)
}
slog.Info("service stopped cleanly")
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
