System Design Academy

Saving…

Lesson 10 of 10 in Module 40 of 45 lessons complete

Thread-Safe Design Checklist

Module 4, lesson 10Concept12 min

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.

Choose ownership before shared-state protection.

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.
After: capture the first failure, cancel peers, and join all four controllers.
Go
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)
}
Optional fragment: errgroup.WithContext from golang.org/x/sync; external module required.
Go
// 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.

After: only the receiving goroutine touches total.
Go
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.

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

Each device's data is touched only by its own goroutine. What protection does that data need?
Best way to let many goroutines read config that changes rarely?

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.

Try the quick check above whenever you feel ready.

Previous: Worker Pools, context & Cancellation