Hot-Reload Config with atomic.Value

Swap immutable configuration snapshots atomically so readers never take a lock, while validating each new version first.

GoConfig Management

Code

gosnippet
100 lines
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

type Config struct {
	Environment string
	Timeout     time.Duration
	Features    []string
}

func (c Config) Validate() error {
	if c.Environment == "" {
		return fmt.Errorf("environment must not be empty")
	}
	if c.Timeout <= 0 {
		return fmt.Errorf("timeout must be positive")
	}
	return nil
}

func (c Config) clone() Config {
	copied := c
	copied.Features = append([]string(nil), c.Features...)
	return copied
}

type Store struct {
	current atomic.Value
}

func NewStore(initial Config) (*Store, error) {
	initial = initial.clone()
	if err := initial.Validate(); err != nil {
		return nil, err
	}
	store := &Store{}
	store.current.Store(initial)
	return store, nil
}

func (s *Store) Load() Config {
	return s.current.Load().(Config).clone()
}

func (s *Store) Update(next Config) error {
	next = next.clone()
	if err := next.Validate(); err != nil {
		return err
	}
	s.current.Store(next)
	return nil
}

func main() {
	store, err := NewStore(Config{
		Environment: "staging",
		Timeout:     2 * time.Second,
		Features:    []string{"beta"},
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		for i := 0; i < 3; i++ {
			snapshot := store.Load()
			fmt.Printf(
				"reader: env=%s timeout=%s features=%v\n",
				snapshot.Environment,
				snapshot.Timeout,
				snapshot.Features,
			)
			time.Sleep(10 * time.Millisecond)
		}
	}()

	time.Sleep(5 * time.Millisecond)
	if err := store.Update(Config{
		Environment: "production",
		Timeout:     time.Second,
		Features:    []string{"beta", "search"},
	}); err != nil {
		fmt.Println("update:", err)
	}
	invalid := Config{Environment: "", Timeout: time.Second}
	if err := store.Update(invalid); err != nil {
		fmt.Println("rejected:", err)
	}
	wg.Wait()
}

What the code does

Hot-Reload Config with atomic.Value is built around the functions Validate, clone, NewStore and Load.

Iteration happens inside for i := 0; i < 3; i++ — everything outside it runs once. err is inspected at 4 call sites before any result is trusted. The task is handed to a goroutine and runs concurrently. Whatever happens in the body, the defer-ed call runs last on the way out.

Watch out for

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
  • Handle err before the other return values; that ordering is the whole contract.

Applying it

Entry signature: func (c Config) Validate() error

The printed lines carry step labels — reader: env=, update:, rejected: — when the file runs.

There are 3 calls inside main — NewStore, Load and Update — executed top to bottom.

Statements that matter most here

return fmt.Errorf("environment must not be empty")
return fmt.Errorf("timeout must be positive")
func NewStore(initial Config) (*Store, error) {
	initial = initial.clone()
	if err := initial.Validate(); err != nil {
		return nil, err
	}
	store := &Store{}
	store.current.Store(initial)
	return store, nil
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
By return value: each fallible call hands back an `error`, checked at 4 places here.
What does Hot-Reload Config with atomic.Value print when run?
Invoke the file as-is — the `reader: env=`, `update:`, `rejected:` prefixes identify which step printed each line.