Skip to content

Go Config Watch

DodaTech 1 min read

In this tutorial, you'll learn about Go Config: Hot Reload. We cover key concepts, practical examples, and best practices.

Config hot reload -- Watch configuration files for changes and reload without restarting the application.

The Problem

Restarting the application on every config change causes downtime. Use fsnotify or viper.WatchConfig to detect file changes and reload configuration live.

Wrong

func readConfig() Config {
    // Read once at startup
    var cfg Config
    yaml.Unmarshal(data, &cfg)
    return cfg
}

Output:

// Config changes require app restart
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
    slog.Info("config changed", "file", e.Name)
    applyConfig(viper.AllSettings())
})
// Or with fsnotify directly:
watcher, _ := fsnotify.NewWatcher()
go func() {
    for event := range watcher.Events {
        if event.Op&fsnotify.Write == fsnotify.Write {
            reloadConfig(event.Name)
        }
    }
}()

Output:

// Config changes applied without restart

Prevention

  • Use viper.WatchConfig() for Viper-based hot reload
  • Use fsnotify for custom config reload logic
  • Use atomic.Value for thread-safe config swap
  • Signal old connections to refresh with new config
  • Test config reload under load

Common Mistakes with config watch

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Is hot reload safe?**

For most config. Be careful with credentials and TLS certs.

How to handle partial writes?

Write to temp file, then rename. fsnotify sees single event.

What about database connections?

Use connection pool close/reopen. Do this in OnConfigChange.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro