☰ All patterns
Singleton
Exactly one instance, shared by everyone, created safely.
01
Explain it like I'm new
Real-life analogy
The office coffee machine
An office has ONE coffee machine. Nobody buys their own; everybody walks to the same one. The first person in the morning switches it on, and everyone after just uses it.
😩 The problem
Some things should exist only once: app config, a logger, a database pool. If every part of your code creates its own, you waste memory and get inconsistent state. With goroutines, two of them might even create it at the same moment.
💡 The pattern
Keep a package-level variable and guard its creation with sync.Once. The setup function runs exactly once, no matter how many goroutines race to call it.
02
Play with it
An interactive model of the pattern. Click around, nothing can break.
Config instances in memory
nothing created yet
💡 Switch to the naive version and run it a few times. Goroutines that check instance == nil at the same moment each create their own copy. sync.Once makes that impossible.
03
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press ▶ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
04
When should I use it?
✅ Reach for it when…
- •Truly global, read-mostly resources: config, loggers, connection pools.
- •Expensive setup you want to delay until first use (lazy init).
🚫 Skip it when…
- •You need to swap the thing in tests. Prefer passing dependencies in as parameters.
- •You're tempted to use it as a global variable to dodge passing arguments around.
🐹 Go tip
Go 1.21 added sync.OnceValue: var getConfig = sync.OnceValue(loadConfig) gives you a lazy singleton in one line.
🌍 You've already seen it in
http.DefaultClient, slog.Default() and the sync.Once inside many database drivers.
05
Quick check
One question. No pressure.
Why use sync.Once instead of `if instance == nil { instance = ... }`?
Related: Factory, Functional Options