System Design Academy

Saving…

Lesson 4 of 11 in Module 30 of 45 lessons complete

Singleton with sync.Once — and Why to Be Careful

Module 3, lesson 4Concept12 min

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.
GetCatalog safely initializes one shared catalogue.
Go
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.

Several callers share one initialized catalogue.

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.

Load the audio index once.
Go
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.

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

Why use sync.Once instead of if instance == nil { instance = load() }?
Main downside of singletons?

Takeaways

  • A singleton is one shared instance.
  • Use sync.Once for safe one-time setup.
  • Prefer passing a value from main over a global.

Try the quick check above whenever you feel ready.

Previous: Builder & Functional Options