Skip to content
GDP for Noobs
☰ All patterns
CreationalBeginner

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.

g1
g2
g3
g4
g5

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.

main.go
1package main
2
3import (
4 "fmt"
5 "sync"
6)
7
8// Config is something we only ever want ONE of in the whole program.
9type Config struct {
10 AppName string
11 Port int
12}
13
14var (
15 instance *Config
16 once sync.Once
17)
18
19// GetConfig returns the single shared Config.
20// sync.Once guarantees the setup runs exactly once,
21// even if many goroutines call GetConfig at the same time.
22func GetConfig() *Config {
23 once.Do(func() {
24 fmt.Println("Loading config... (you will see this only once)")
25 instance = &Config{AppName: "noob-app", Port: 8080}
26 })
27 return instance
28}
29
30func main() {
31 var wg sync.WaitGroup
32 for i := 0; i < 5; i++ {
33 wg.Add(1)
34 go func() {
35 defer wg.Done()
36 GetConfig()
37 }()
38 }
39 wg.Wait()
40
41 a := GetConfig()
42 b := GetConfig()
43 fmt.Println("a and b are the same instance?", a == b)
44 fmt.Printf("App %q runs on port %d\n", a.AppName, a.Port)
45}
terminal
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