Why sync.OnceValues in Go Permanently Caches File Read ErrorsBrief · digest for November 28
Brief≈ 2 min

Why sync.OnceValues in Go Permanently Caches File Read Errors

Go 1.21 introduced a handy lazy-initialization wrapper, sync.OnceValues, which runs a function once and safely shares the result across goroutines. There is a catch: it works on any (T1, T2) pair, knows nothing about error, and caches both return values permanently.

If config.json wasn't on disk yet on the first call, the function locks in that error forever. Even after the file appears, the service keeps failing until restart. A panic inside behaves the same way: every later call panics with the same value.

When you need to recover from a transient failure, cache only a successful result:

// An error on the first read sticks until restart
readConfig := sync.OnceValues(func() ([]byte, error) {
  return os.ReadFile("config.json")
})

// Retryable: cache data only when err == nil
type Loader struct {
  mu   sync.Mutex
  data []byte
}

func (l *Loader) Load() ([]byte, error) {
  l.mu.Lock()
  defer l.mu.Unlock()
  if l.data != nil {
    return l.data, nil
  }
  b, err := os.ReadFile("config.json")
  if err != nil {
    return nil, err
  }
  l.data = b
  return l.data, nil
}

For immutable resources that must exist for a process to boot, sync.OnceValues is great. When a file, certificate, or database may appear later, guard the cache with sync.Mutex and store only successful reads.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2