Singleton with sync.Once — and Why to Be Careful
Definition
Singleton
- In plain English
- A singleton is a type that has exactly one shared instance for the whole program.
- Think of it like
- It is like a building having one fire alarm control panel.
Why it exists
Loading a 200 MB catalogue for every audio request wastes memory and time. You want one shared copy.
Creating it once can help. Letting callers find it implicitly can hide important dependencies.
How it works
Goroutine
- In plain English
- A goroutine is a lightweight task Go runs at the same time as others — covered fully in Module 4.
- Think of it like
- Like a kitchen helper working alongside you.
sync.Once
- In plain English
- sync.Once is a Go tool that runs a function exactly once, even if many goroutines call it at the same time.
- Think of it like
- Like a "first one in turns the lights on" rule.
package main
import (
"fmt"
"sync"
)
type Catalog struct{ tracks int }
var (
catalog *Catalog
once sync.Once
)
func GetCatalog() *Catalog {
once.Do(func() { catalog = &Catalog{tracks: 2000} })
return catalog
}
func main() { fmt.Println(GetCatalog() == GetCatalog()) }
AudioRequest and SearchRequest read Catalog, while GetCatalog initializes that single shared value.
- Two goroutines can both observe nil with an unprotected check. They may create two values and race on assignment.
- Once waits for the setup function to finish before returning to other callers. It does not protect later mutations.
- Once does not retry a function that panics or records a loading error. Decide how startup failures should be handled.
- GetCatalog shares one value. Go still allows other Catalog values; using the accessor is an application rule.
Global state
- In plain English
- Global state is data any part of the program can read or change.
- Think of it like
- Like a whiteboard in the hallway anyone can scribble on.
Examples
Load the audio index once
Your 200 MB audio index loads on first use. Later requests reuse that index.
package main
import (
"fmt"
"sync"
)
type Catalog struct{ tracks int }
var (
catalog *Catalog
once sync.Once
)
func GetCatalog() *Catalog {
once.Do(func() { catalog = &Catalog{tracks: 2000} })
return catalog
}
func main() { fmt.Println(GetCatalog() == GetCatalog()) }
This small stand-in stores a track count instead of 200 MB. Its private data stays unchanged after initialization.
The insight
sync.Once makes lazy, one-time setup safe.
Pass startup configuration down
Your loyalty configuration loads once at startup. The app can receive that value directly.
package main
import "fmt"
type Config struct{ Tier string }
var config = Config{Tier: "silver"}
func GetConfig() Config { return config }
type App struct{}
func (App) Tier() string { return GetConfig().Tier }
func main() { fmt.Println((App{}).Tier()) }
package main
import "fmt"
type Config struct{ Tier string }
type App struct{ cfg Config }
func NewApp(cfg Config) App { return App{cfg: cfg} }
func (a App) Tier() string { return a.cfg.Tier }
func main() { cfg := Config{Tier: "silver"}; fmt.Println(NewApp(cfg).Tier()) }
The insight
“Only one” does not have to mean “global”.
Give each test its own store
Two pickup tests share a global database. The second test sees the first test’s booking.
package main
import "fmt"
type Store struct{ pickups int }
var database = &Store{}
func Book() { database.pickups++ }
func main() { Book(); fmt.Println(database.pickups); Book(); fmt.Println(database.pickups) }
package main
import "fmt"
type Store struct{ pickups int }
type App struct{ store *Store }
func NewApp(s *Store) App { return App{store: s} }
func (a App) Book() { a.store.pickups++ }
func main() {
first, second := &Store{}, &Store{}
a, b := NewApp(first), NewApp(second)
a.Book()
b.Book()
fmt.Println(first.pickups, second.pickups)
}
These examples run sequentially. Sharing a mutable store across goroutines would require additional protection.
The insight
Hidden globals make tests interfere with each other.
Trade-offs
Pros
- Shares an expensive resource.
- Once makes initialization safe across goroutines.
Cons
- Hides dependencies.
- Tests can share unwanted data.
- Hard to reset between tests.
Use when
- A read-only resource belongs to the whole process.
- Loading once saves substantial work.
Avoid when
- You can pass a startup value instead.
- Tests need different configurations or stores.
Quick check
Takeaways
- A singleton is one shared instance.
- Use sync.Once for safe one-time setup.
- Prefer passing a value from main over a global.