Skip to main content

sync, atomic & context

Learning objectives
  • Pick the right primitive — Mutex, RWMutex, atomics, sync.Map, channels — for a given sharing pattern and defend the choice.
  • Avoid deadlocks with lock ordering, and avoid the classic WaitGroup, Once and Pool misuses.
  • Propagate cancellation and deadlines with context across goroutines and services, and know what belongs in context values.
  • Coordinate parallel work with errgroup and bound it with semaphores.

TL;DR​

  • sync.Mutex protects invariants that span several fields. Keep critical sections short; never hold a lock across I/O. Lock multiple objects in a global order (e.g. by account ID).
  • RWMutex only pays off when reads vastly outnumber writes and critical sections are non-trivial; otherwise a plain Mutex is as fast or faster.
  • Atomic types (atomic.Int64, atomic.Bool, atomic.Pointer[T], Go 1.19+) for counters, flags and copy-on-write config. One atomic per invariant — two atomics can't express "A and B change together".
  • sync.OnceValue/OnceValues (Go 1.21) for lazy init; sync.WaitGroup.Go (Go 1.25) removes the Add/Done boilerplate; sync.Pool reuses short-lived buffers but is emptied by GC.
  • context.Context carries cancellation, deadlines and request-scoped metadata — not optional parameters, not dependencies, not business data. Always defer cancel().
  • errgroup.WithContext = parallel calls + first-error cancellation + wait. SetLimit or semaphore.Weighted bounds concurrency to protect downstream systems.

Why it matters​

  • Concurrent transfers A→B and B→A deadlock if each locks "from" first. The same lock-ordering rule applies to SELECT ... FOR UPDATE in Locking & Concurrency Control.
  • Deadline budgets: the mobile app gives checkout 3 s. If your PSP call uses context.Background() with its own 30 s timeout, you keep working (and possibly charging) long after the client gave up and retried.
  • Downstream protection: a core-banking host may accept only 20 concurrent sessions. Without a semaphore, a payroll batch opens 2,000 and gets everyone rate-limited — including ATM traffic.
  • Hot counters: approval/decline counters updated by thousands of goroutines per second — a mutex there shows up in the mutex profile; atomics don't.

Core concepts​

Mutex​

type Account struct {
mu sync.Mutex
id string
balance int64 // guarded by mu
}
  • The zero value is an unlocked mutex. Never copy a mutex after first use — go vet's copylocks check reports it.
  • Not reentrant: locking twice in the same goroutine deadlocks.
  • defer mu.Unlock() right after Lock() keeps every return path correct; the defer cost is negligible since Go 1.14 (open-coded defers).
  • Fairness: if a waiter has waited more than ≈1 ms, the mutex switches to starvation mode and hands ownership directly to waiters in FIFO order, trading throughput for bounded latency.
  • TryLock (Go 1.18) exists; legitimate uses are rare. If you need it, the design usually wants a channel or a different ownership model.

Lock ordering prevents deadlock when one operation needs two locks:

// Transfer moves amount between two in-memory accounts.
// Locks are always taken in ID order, so A→B and B→A can't deadlock.
func Transfer(from, to *Account, amount int64) error {
if from.id == to.id {
return errors.New("transfer to same account")
}
first, second := from, to
if second.id < first.id {
first, second = second, first
}
first.mu.Lock()
defer first.mu.Unlock()
second.mu.Lock()
defer second.mu.Unlock()

if from.balance < amount {
return ErrInsufficientFunds
}
from.balance -= amount
to.balance += amount
return nil
}

RWMutex​

Many concurrent readers or one writer. A waiting writer blocks new readers (to avoid writer starvation), which has a sharp consequence: recursive read locking can deadlock — goroutine X holds RLock, a writer queues, X calls RLock again and waits behind the writer, who waits for X.

RWMutex has more bookkeeping than Mutex; under write-heavy or tiny critical sections it is slower. Benchmark before switching. For read-mostly config, atomic.Pointer[T] with copy-on-write beats both.

WaitGroup​

var wg sync.WaitGroup
for _, m := range merchants {
wg.Go(func() { // Go 1.25+: Add(1), go, defer Done() in one call
settle(ctx, m)
})
}
wg.Wait()

Before 1.25: call wg.Add(1) before the go statement and defer wg.Done() first thing inside. Calling Add inside the goroutine races with Wait (vet's waitgroup check flags it since Go 1.25). A WaitGroup gives no error propagation and no cancellation — that's errgroup.

Once, OnceFunc, OnceValue​

// Loaded on first use, shared by all goroutines, computed exactly once.
var signingKey = sync.OnceValues(func() (*ecdsa.PrivateKey, error) {
return loadKeyFromVault() // hypothetical loader
})

func sign(msg []byte) ([]byte, error) {
key, err := signingKey()
if err != nil {
return nil, fmt.Errorf("load signing key: %w", err)
}
return ecdsa.SignASN1(rand.Reader, key, digest(msg))
}
  • sync.Once.Do(f): if f panics, the Once still counts as done — later calls do nothing, leaving you uninitialised.
  • OnceFunc/OnceValue/OnceValues (Go 1.21) re-panic with the same value on every call if f panicked, which is easier to debug.
  • The result is cached forever, including errors. If Vault was briefly unavailable at startup, signingKey() fails for the life of the process. For retryable initialisation, use a mutex and only cache success — or fail fast at startup so Kubernetes restarts you.

sync.Map​

An untyped concurrent map optimised for two patterns: keys written once and read many times (caches that only grow), and goroutines working on disjoint key sets. Since Go 1.24 it is backed by a concurrent hash-trie, which reduces contention for modifications on large maps. API highlights: Load, Store, LoadOrStore, LoadAndDelete, Swap/CompareAndSwap/CompareAndDelete (Go 1.20), Clear (Go 1.23), Range.

For most "map plus lock" needs, a map with a Mutex is clearer and type-safe; under heavy contention, shard it (N maps with N locks, chosen by key hash).

sync.Pool​

A per-P cache of reusable temporary objects, used to cut allocation and GC pressure on hot paths (encoding buffers, scratch slices).

var bufPool = sync.Pool{New: func() any { return new(bytes.Buffer) }}

func encodeEvent(e Event) ([]byte, error) {
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer func() {
if buf.Cap() <= 64<<10 { // don't let one huge event pin memory in the pool
bufPool.Put(buf)
}
}()
if err := json.NewEncoder(buf).Encode(e); err != nil {
return nil, err
}
return bytes.Clone(buf.Bytes()), nil // copy out: buf returns to the pool
}

Rules: always reset state on Get; never return an object that's still referenced; store pointers (putting a non-pointer value allocates); never pool things with identity or lifecycle like DB connections. Pooled objects are dropped across garbage collections (a "victim" cache, since Go 1.13, keeps them for one extra cycle) — a pool is a cache, not storage.

sync.Cond​

A condition variable: goroutines Wait (atomically unlocking a mutex) until another goroutine calls Signal or Broadcast. Always wait in a loop re-checking the condition. It can't be combined with select or context cancellation, so channels usually fit better; reach for Cond when many goroutines wait for a shared state change and you've measured channel-based alternatives as too costly.

Atomics​

type PSPStats struct {
approved atomic.Int64
declined atomic.Int64
healthy atomic.Bool
}

func (s *PSPStats) Record(ok bool) {
if ok {
s.approved.Add(1)
} else {
s.declined.Add(1)
}
}

// Exactly one goroutine wins the right to start shutdown.
var shuttingDown atomic.Bool

func beginShutdown() bool { return shuttingDown.CompareAndSwap(false, true) }
  • The typed API (Go 1.19) prevents mixing atomic and plain access to the same field — the bug the old atomic.AddInt64(&x, 1) style invited — and guarantees 64-bit alignment on 32-bit platforms.
  • Go's atomics are sequentially consistent; they create happens-before edges like locks do (see Memory, GC & Escape Analysis).
  • Go 1.23 added And/Or methods for bit flags.
  • A CAS loop (for { old := x.Load(); if x.CompareAndSwap(old, f(old)) { break } }) is fine for a single word. If an invariant spans two values ("debits equal credits"), use a mutex or put both in one struct behind atomic.Pointer.

context​

A Context is an immutable tree node. Deriving a child adds cancellation, a deadline, or a value; cancelling a parent cancels all descendants; children never affect parents.

func (h *Handler) Checkout(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel() // releases the timer and children even on success

quote, err := h.svc.Checkout(ctx, cartFrom(r))
// ...
}

The API, with versions:

FunctionPurpose
WithCancel, WithTimeout, WithDeadlineclassic cancellation and deadlines
WithCancelCause, Cause (Go 1.20)cancel with a reason: cancel(ErrFraudSuspected); ctx.Err() stays Canceled, context.Cause(ctx) returns the reason
WithTimeoutCause, WithDeadlineCause (Go 1.21)deadline with a reason, e.g. ErrPSPBudgetExceeded
WithoutCancel (Go 1.21)keep values, drop cancellation — for work that must finish after the response
AfterFunc (Go 1.21)run a callback when ctx is done (e.g. cancel a non-context-aware call); returns stop
WithValueattach request-scoped metadata

Rules:

  • ctx is the first parameter, named ctx, of every function that does I/O or may block. Don't store it in a struct (exception: a struct that is a single operation, like an http.Request).
  • Always call cancel (vet's lostcancel reports leaks); defer cancel() right after creating it.
  • Check ctx.Err() before expensive work and select on ctx.Done() in loops.
  • Timeouts shrink down the call chain. A child WithTimeout longer than the parent's remaining budget is silently capped by the parent.
  • gRPC propagates deadlines across services automatically (the grpc-timeout header). Plain HTTP does not — pass a budget header yourself or the downstream keeps working after you gave up.
  • WithoutCancel work (audit logs, outbox inserts after the response) still needs its own timeout so it can't hang forever.

What belongs in context values — data that is request-scoped and crosses API boundaries transparently:

GoodBad
request ID, correlation IDoptional function parameters
trace span (OpenTelemetry does this)database handles, repositories, clients
authenticated principal / tenant IDamounts, account IDs, business inputs
deadline budget metadatafeature flags you could pass explicitly

Use an unexported key type so no other package can collide, and typed accessors:

type ctxKey int

const principalKey ctxKey = iota

type Principal struct {
UserID string
TenantID string
Scopes []string
}

func WithPrincipal(ctx context.Context, p Principal) context.Context {
return context.WithValue(ctx, principalKey, p)
}

func PrincipalFrom(ctx context.Context) (Principal, bool) {
p, ok := ctx.Value(principalKey).(Principal)
return p, ok
}

Value lookup walks up the parent chain — O(depth). Fine for a handful of values; don't build a key-value store in it.

errgroup​

golang.org/x/sync/errgroup is the standard way to run related goroutines that can fail:

func (s *Checkout) Prepare(ctx context.Context, cart Cart) (Quote, error) {
g, ctx := errgroup.WithContext(ctx) // ctx is canceled on first error

var (
stock Reservation
price PriceQuote
risk RiskScore
)
g.Go(func() (err error) { stock, err = s.inventory.Reserve(ctx, cart); return })
g.Go(func() (err error) { price, err = s.pricing.Quote(ctx, cart); return })
g.Go(func() (err error) { risk, err = s.fraud.Score(ctx, cart); return })

if err := g.Wait(); err != nil {
// A reservation may have succeeded before another call failed: compensate.
s.inventory.ReleaseAsync(cart.ID)
return Quote{}, fmt.Errorf("prepare cart %s: %w", cart.ID, err)
}
return NewQuote(stock, price, risk), nil
}
  • Each goroutine writes its own variable; Wait happens-after all of them, so reading afterwards is race-free.
  • Wait returns the first non-nil error; others are discarded (log them inside the goroutine if you need them).
  • g.SetLimit(n) bounds concurrent goroutines — Go blocks when the limit is reached; TryGo returns false instead.
  • The derived ctx is canceled when Wait returns, so don't use it for work after Wait.

Semaphores​

golang.org/x/sync/semaphore.Weighted bounds concurrent access with context-aware acquisition:

type CoreBanking struct {
sem *semaphore.Weighted // host allows 20 concurrent sessions
client *Client
}

func NewCoreBanking(c *Client) *CoreBanking {
return &CoreBanking{sem: semaphore.NewWeighted(20), client: c}
}

func (b *CoreBanking) Post(ctx context.Context, e Entry) error {
if err := b.sem.Acquire(ctx, 1); err != nil {
return fmt.Errorf("core banking: wait for session: %w", err)
}
defer b.sem.Release(1)
return b.client.Post(ctx, e)
}

Weights let a bulk statement export take 5 slots while a balance inquiry takes 1. A buffered channel make(chan struct{}, 20) is the lightweight alternative when you don't need weights. Both bound concurrency per process — for a fleet-wide limit you need a distributed limiter (see Rate Limiting).

Trade-offs​

OptionStrengthsWeaknessesChoose when
MutexSimple, protects multi-field invariantsContention under heavy writes; deadlock risk with several locksDefault for shared mutable state
RWMutexParallel readersExtra overhead; recursive RLock deadlocks; slower when writes are commonRead-heavy with non-trivial read sections (measured)
Sharded mutex mapScales with coresMore code; cross-shard ops are hardHot per-key state (rate counters per merchant)
AtomicsLock-free, very fastSingle-word only; subtleCounters, flags, config pointer swaps
atomic.Pointer copy-on-writeLock-free reads of a consistent snapshotEach write copies the whole structRead-mostly config, routing tables
sync.MapGood for write-once/read-many and disjoint keysUntyped; worse than map+mutex for mixed workloadsLong-lived caches that mostly grow
ChannelsOwnership transfer, composes with select/cancelOverhead, leak and deadlock riskPassing work/results between goroutines
errgroupErrors + cancellation + waitFirst error onlyParallel calls inside one request
semaphore.WeightedWeighted, context-awareProcess-local onlyProtecting a dependency's concurrency limit

In practice​

  • Name what a mutex guards: place it directly above the fields it protects, with a // guarded by mu comment.
  • Don't do I/O under a lock. Copy what you need, unlock, call the network. A lock held across a 2 s PSP timeout serialises every request behind it.
  • Shard hot locks — e.g. 64 shards keyed by fnv(merchantID) % 64 for per-merchant velocity counters in fraud checks.
  • Budget timeouts top-down: edge 3 s → checkout 2.5 s → PSP 2 s → retry only if time remains (deadline, ok := ctx.Deadline()). See Resilience Patterns.
  • Use context.Cause in logs to explain why something was canceled (client disconnected vs fraud budget exceeded).
  • Run tests with -race in CI always; enable it in a canary or load-test build to catch races only real traffic triggers.

Common pitfalls​

  • Copying a struct containing a mutex (value receivers, passing by value, range over []Account). Symptom: no mutual exclusion; races. go vet copylocks.
  • Lock held during I/O — p99 latency equals the slowest dependency times the queue depth.
  • Inconsistent lock order — deadlocks only under concurrent opposite operations; often found in production first.
  • Recursive RLock with a waiting writer — deadlock under load only.
  • wg.Add inside the goroutine — Wait returns early; results missing.
  • sync.Once with a fallible init — error or panic cached forever; service is "up" but every call fails.
  • Pool misuse — not resetting buffers (data from one customer's request leaking into another's response is a security incident), or pooling huge buffers.
  • context.Background() inside request handlers — work continues after the client is gone; no deadline propagation.
  • Forgotten cancel — timers and child contexts leak until the parent ends.
  • Business data in context — invisible dependencies; tests fail mysteriously when a value is missing.
  • Mixing atomic and non-atomic access to the same variable — still a data race.

Interview angle​

Typical questions: "Mutex vs RWMutex vs atomic — when?", "How do you prevent deadlocks when transferring between two accounts?", "What goes in context values?", "How do you propagate a deadline from the API gateway to the database?", "How would you call five services in parallel and fail fast?", "How do you limit concurrent calls to a legacy system?"

A strong answer: mutex by default, RWMutex only when measured, atomics for single-word state; lock ordering (and the same rule in SQL with ORDER BY id FOR UPDATE); context for cancellation/deadlines/metadata with unexported keys; deadline budgets that shrink down the chain, gRPC's automatic propagation; errgroup.WithContext with compensation for partial success; semaphore.Weighted per process plus a distributed limiter for the fleet.

Follow-ups: "What's mutex starvation mode?", "Why does sync.Pool get emptied?", "What does WithoutCancel solve?", "What happens to errgroup's other goroutines after the first error?" (their ctx is canceled; they must observe it).

Red flags: "I'd use sync.Map everywhere for safety", storing loggers/DB pools/amounts in context, timeouts that grow downstream, no story for partial failure in parallel calls.

Self-check​

1. Two goroutines run Transfer(A, B) and Transfer(B, A) with "lock from, then lock to". Why can this deadlock and what's the fix?

Each goroutine holds one lock and waits for the other's — a cycle. Fix by acquiring locks in a global order (e.g. sorted account IDs) regardless of direction, so both try A first and one simply waits. The database equivalent is locking rows in ID order with SELECT ... FOR UPDATE.

2. When is RWMutex slower than Mutex, and what can deadlock with it?

When writes are frequent or read sections are tiny: RWMutex has more bookkeeping, and writers block new readers. A goroutine taking RLock twice deadlocks if a writer queues between the two calls, because the second RLock waits behind the writer, who waits for the first RLock to be released.

3. What's wrong with loading a signing key with sync.OnceValues if Vault can be briefly unavailable?

The first result, error included, is cached for the life of the process — one transient failure makes signing fail forever while health checks may still pass. Either fail fast at startup (crash and restart) or use a mutex-protected lazy init that caches only success and retries with backoff.

4. Which of these belong in context values: request ID, merchant ID being paid, a *sql.DB, authenticated tenant ID, a logger?

Request ID and authenticated tenant ID: request-scoped metadata that crosses API boundaries. The merchant ID is a business input — pass it as a parameter. *sql.DB is a dependency — inject it into the struct. Loggers are debated; the common idiom is to inject a logger and put only correlation fields (request/trace ID) in context.

5. In errgroup.WithContext, the pricing call fails while inventory reservation already succeeded. What happens to each goroutine, and what must your code do?

Wait returns the pricing error; the derived context is canceled, so the fraud call (if it honours ctx) stops early. The inventory reservation already happened and is not undone automatically — the caller must compensate (release the reservation) or rely on a reservation TTL.

6. Scenario: a payroll batch of 50,000 transfers must post to a core-banking host limited to 20 concurrent sessions, while ATM traffic shares the host. Design the concurrency control.

Use errgroup with SetLimit (or a semaphore.Weighted) well below 20 — e.g. 12 — for the batch, leaving headroom for online traffic, ideally through a separate weighted semaphore or priority. Each posting carries an idempotency key, honours ctx, and retries with backoff on transient errors. Across multiple batch pods, the limit must be shared — a distributed limiter or a single scheduler.

7. Why does Go recommend typed atomics (atomic.Int64) over atomic.AddInt64(&x, 1)?

The typed field can only be accessed through atomic methods, so you can't accidentally read or write it non-atomically elsewhere (a data race). It also guarantees 64-bit alignment on 32-bit platforms, which the function style required you to arrange manually.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Build an in-memory "mini ledger" service:

  1. Ledger with accounts guarded by per-account mutexes; implement Transfer with lock ordering. Write a test that runs 10,000 random concurrent transfers among 50 accounts and asserts the total balance is unchanged — under -race.
  2. Add PSPStats with atomics and a /stats endpoint; benchmark atomic counters against a mutex-guarded struct with b.RunParallel.
  3. Implement Prepare with errgroup.WithContext calling three fakes; make one fail and assert the others observe cancellation within 10 ms.
  4. Wrap a fake "core banking" client with a semaphore.Weighted(5) and prove with a counter that no more than 5 calls are ever in flight.
  5. Thread a request ID through context with an unexported key and log it from the deepest call.

Done when: all tests pass with -race -count=20, the total-balance invariant holds, and go vet is clean.

Further reading​

  • sync, sync/atomic and context package documentation (especially the Mutex fairness notes and RWMutex warnings).
  • Go blog: "Go Concurrency Patterns: Context" (Sameer Ajmani) and "Contexts and structs" (Jean Barkhuysen, Matt T. Proud).
  • The Go Memory Model (go.dev/ref/mem) — synchronisation guarantees of mutexes, atomics and Once.
  • Katherine Cox-Buday, Concurrency in Go — the sync package and context chapters.
  • Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — context misuse, sync copying, WaitGroup mistakes.
  • golang.org/x/sync docs: errgroup, semaphore, singleflight.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).