Singleton Pattern Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Singleton Pattern runs in O(1) time and O(1) space, in Go as in every other language.
- ✓A package-level variable is already process-wide, and sync.Once provides the lazy, exactly-once initialisation.
- ✓Use sync.OnceValue for a lazily built singleton and a plain package-level var for one that is cheap to construct.
- ✓The Go trap: Initialisation inside func init() runs before main and its order across packages is determined by the import graph, so a singleton in package A that depends on one in package B works or panics with a nil dereference depending on an import edge somebody may add later.
- ✓sync.Once.Do has a fast path that is a single atomic load and a branch after the first call, and it is inlined.
What Singleton Pattern actually is
Singleton Pattern in Go: what you actually reach for
Go implementation
package registry
import (
"os"
"sync"
)
type Config struct {
Endpoint string
}
// Go 1.21+: lazy, exactly-once, no package-level var to leak.
var Load = sync.OnceValue(func() *Config {
endpoint := os.Getenv("ENDPOINT")
if endpoint == "" {
endpoint = "localhost"
}
return &Config{Endpoint: endpoint}
})
// The pre-1.21 shape, still everywhere:
var (
once sync.Once
pool *ConnectionPool
)
func Pool() *ConnectionPool {
once.Do(func() {
pool = &ConnectionPool{Size: 10}
})
return pool
}
type ConnectionPool struct{ Size int }
// Avoid func init() for this: its cross-package ordering follows the
// import graph, so a new import edge elsewhere can reorder it under you.Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Singleton Pattern?
A package-level variable is already process-wide, and sync.Once provides the lazy, exactly-once initialisation. Since Go 1.21 there is also sync.OnceValue, which wraps the common "initialise and return a value" shape into a single call and removes the package-level variable entirely.
What is the most common Go mistake when implementing Singleton Pattern?
Initialisation inside func init() runs before main and its order across packages is determined by the import graph, so a singleton in package A that depends on one in package B works or panics with a nil dereference depending on an import edge somebody may add later. The testing consequence is the bigger cost: a package-level singleton makes tests share mutable state, and go test runs the tests within a package sequentially but packages in PARALLEL, so a global backed by a shared external resource produces flakes that never reproduce alone.
How does Singleton Pattern actually perform in Go?
sync.Once.Do has a fast path that is a single atomic load and a branch after the first call, and it is inlined. sync.OnceValue costs the same plus a closure. Neither allocates after initialisation. A singleton guarded by a Mutex for mutation becomes a contention point across every goroutine in the process, which is usually the real scalability limit rather than the initialisation. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.