Thread-Safe Design Checklist
Definition
Thread-safe
- In plain English
- Code is thread-safe when it behaves correctly no matter how concurrent goroutines interleave.
- Think of it like
- It is like a revolving door that works however many people push it.
Confinement
- In plain English
- Confinement means only one goroutine ever touches a piece of data, so it needs no lock.
- Think of it like
- It is like giving each child their own colouring book instead of sharing one.
Why it exists
A device total needs no mutex when only its owner touches it. Unnecessary sharing creates unnecessary failure paths.
Choose ownership before choosing a lock. Then review every shared update and every goroutine exit.
sync.Map
- In plain English
- A sync.Map is a specialised concurrent map for entries written once or separate key sets accessed by different goroutines.
- Think of it like
- Like separate labelled drawers staff can use without one shared key.
Snapshot
- In plain English
- A snapshot is a complete view of data captured at one moment.
- Think of it like
- Like a photograph that stays unchanged while the scene moves on.
How it works
Immutable data
- In plain English
- Immutable data never changes after it's created, so any goroutine can read it safely.
- Think of it like
- Like a printed timetable everyone can read at once.
errgroup
- In plain English
- errgroup, from golang.org/x/sync, runs a group of goroutines, waits for them, and cancels the rest when one fails.
- Think of it like
- Like a climbing team roped together: if one falls, everyone stops.
Own data leads to Confine; otherwise consider immutable publication, then Atomic, then measured RWMutex or Mutex.
- Prefer one owner or pass values over channels.
- Publish immutable configuration safely and never mutate a published snapshot.
- Use one lock for each rule involving related values; agree on an order for multiple locks.
- Give every goroutine an exit, pass context, and run go test -race in automated checks.
- Use sync.Map only for its documented access patterns; otherwise prefer a typed map protected by a mutex.
sync.Once
- In plain English
- A sync.Once runs its supplied function at most once, even when several goroutines call Do.
- Think of it like
- Like a single-use switch that everyone can press but only one person activates.
package main
import (
"context"
"fmt"
"sync"
)
func control(ctx context.Context, id int) error {
if id == 0 {
return fmt.Errorf("controller 0 failed")
}
<-ctx.Done()
return nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
var once sync.Once
var first error
for id := 0; id < 4; id++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
if err := control(ctx, id); err != nil {
once.Do(func() { first = err; cancel() })
}
}(id)
}
wg.Wait()
fmt.Println(first)
}
// Import golang.org/x/sync/errgroup in the surrounding file.
group, ctx := errgroup.WithContext(parent)
for id := 0; id < 4; id++ {
group.Go(func() error { return control(ctx, id) })
}
err := group.Wait()
Examples
Own each device total
A device owner receives step updates. Other goroutines cannot edit its total.
package main
import (
"fmt"
)
func main() {
updates := make(chan int)
go func() { defer close(updates); updates <- 300; updates <- 200 }()
total := 0
for steps := range updates {
total += steps
}
fmt.Println(total)
}
Repeat this ownership shape for each device. Values can cross the channel without exposing the private running total.
The insight
Confinement removes the need for locks on private data.
Replace access rules whole
Many readers need door rules. An updater builds a new snapshot and publishes its pointer.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type Rules struct{ door string }
func main() {
var current atomic.Pointer[Rules]
current.Store(&Rules{door: "lobby"})
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); fmt.Println(current.Load().door) }()
current.Store(&Rules{door: "lobby and gym"})
wg.Wait()
}
A reader sees either complete snapshot; output order can vary. Publish before reading, and never mutate published snapshots or their referenced maps.
The insight
Immutable snapshots permit reads without a mutex.
Stop related controllers together
Four controllers start as a group. Controller zero fails, so the others stop.
package main
import (
"context"
"fmt"
"sync"
)
func control(ctx context.Context, id int) error {
if id == 0 {
return fmt.Errorf("controller 0 failed")
}
<-ctx.Done()
return nil
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
var once sync.Once
var first error
for id := 0; id < 4; id++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
if err := control(ctx, id); err != nil {
once.Do(func() { first = err; cancel() })
}
}(id)
}
wg.Wait()
fmt.Println(first)
}
// Import golang.org/x/sync/errgroup in the surrounding file.
group, ctx := errgroup.WithContext(parent)
for id := 0; id < 4; id++ {
group.Go(func() error { return control(ctx, id) })
}
err := group.Wait()
sync.Once permits one failure writer; Wait finishes before main reads first. errgroup cancels peers when created with WithContext.
The insight
Related tasks need shared cancellation and a final wait.
Trade-offs
Pros
- Fewer shared writes need protection.
- Ownership makes responsibilities visible.
Cons
- Ownership may require more message code.
- New snapshots copy changed data.
Use when
- Design a component that runs concurrent tasks.
- Review shared data and shutdown paths.
Avoid when
- A single goroutine already owns all work.
- Extra concurrency adds no useful overlap.
Quick check
Takeaways
- Prefer confinement, communication or safely published immutable data.
- Choose atomics or locks for the remaining shared state.
- Exercise concurrent paths with go test -race.