sync, atomic & context
- 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,OnceandPoolmisuses. - Propagate cancellation and deadlines with
contextacross goroutines and services, and know what belongs in context values. - Coordinate parallel work with
errgroupand bound it with semaphores.
TL;DR
sync.Mutexprotects 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).RWMutexonly pays off when reads vastly outnumber writes and critical sections are non-trivial; otherwise a plainMutexis 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 theAdd/Doneboilerplate;sync.Poolreuses short-lived buffers but is emptied by GC.context.Contextcarries cancellation, deadlines and request-scoped metadata — not optional parameters, not dependencies, not business data. Alwaysdefer cancel().errgroup.WithContext= parallel calls + first-error cancellation + wait.SetLimitorsemaphore.Weightedbounds 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 UPDATEin 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'scopylockscheck reports it. - Not reentrant: locking twice in the same goroutine deadlocks.
defer mu.Unlock()right afterLock()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): iffpanics, 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 iffpanicked, 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/Ormethods 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 behindatomic.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:
| Function | Purpose |
|---|---|
WithCancel, WithTimeout, WithDeadline | classic 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 |
WithValue | attach request-scoped metadata |
Rules:
ctxis the first parameter, namedctx, 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 anhttp.Request).- Always call
cancel(vet'slostcancelreports leaks);defer cancel()right after creating it. - Check
ctx.Err()before expensive work and select onctx.Done()in loops. - Timeouts shrink down the call chain. A child
WithTimeoutlonger than the parent's remaining budget is silently capped by the parent. - gRPC propagates deadlines across services automatically (the
grpc-timeoutheader). Plain HTTP does not — pass a budget header yourself or the downstream keeps working after you gave up. WithoutCancelwork (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:
| Good | Bad |
|---|---|
| request ID, correlation ID | optional function parameters |
| trace span (OpenTelemetry does this) | database handles, repositories, clients |
| authenticated principal / tenant ID | amounts, account IDs, business inputs |
| deadline budget metadata | feature 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;
Waithappens-after all of them, so reading afterwards is race-free. Waitreturns the first non-nil error; others are discarded (log them inside the goroutine if you need them).g.SetLimit(n)bounds concurrent goroutines —Goblocks when the limit is reached;TryGoreturns false instead.- The derived
ctxis canceled whenWaitreturns, so don't use it for work afterWait.
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
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
Mutex | Simple, protects multi-field invariants | Contention under heavy writes; deadlock risk with several locks | Default for shared mutable state |
RWMutex | Parallel readers | Extra overhead; recursive RLock deadlocks; slower when writes are common | Read-heavy with non-trivial read sections (measured) |
| Sharded mutex map | Scales with cores | More code; cross-shard ops are hard | Hot per-key state (rate counters per merchant) |
| Atomics | Lock-free, very fast | Single-word only; subtle | Counters, flags, config pointer swaps |
atomic.Pointer copy-on-write | Lock-free reads of a consistent snapshot | Each write copies the whole struct | Read-mostly config, routing tables |
sync.Map | Good for write-once/read-many and disjoint keys | Untyped; worse than map+mutex for mixed workloads | Long-lived caches that mostly grow |
| Channels | Ownership transfer, composes with select/cancel | Overhead, leak and deadlock risk | Passing work/results between goroutines |
errgroup | Errors + cancellation + wait | First error only | Parallel calls inside one request |
semaphore.Weighted | Weighted, context-aware | Process-local only | Protecting a dependency's concurrency limit |
In practice
- Name what a mutex guards: place it directly above the fields it protects, with a
// guarded by mucomment. - 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) % 64for 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.Causein logs to explain why something was canceled (client disconnectedvsfraud budget exceeded). - Run tests with
-racein 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,
rangeover[]Account). Symptom: no mutual exclusion; races.go vetcopylocks. - 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
RLockwith a waiting writer — deadlock under load only. wg.Addinside the goroutine —Waitreturns early; results missing.sync.Oncewith 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.
Exercise
Build an in-memory "mini ledger" service:
Ledgerwith accounts guarded by per-account mutexes; implementTransferwith lock ordering. Write a test that runs 10,000 random concurrent transfers among 50 accounts and asserts the total balance is unchanged — under-race.- Add
PSPStatswith atomics and a/statsendpoint; benchmark atomic counters against a mutex-guarded struct withb.RunParallel. - Implement
Preparewitherrgroup.WithContextcalling three fakes; make one fail and assert the others observe cancellation within 10 ms. - 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. - 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/atomicandcontextpackage documentation (especially theMutexfairness notes andRWMutexwarnings).- 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
syncpackage and context chapters. - Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — context misuse,
synccopying,WaitGroupmistakes. golang.org/x/syncdocs:errgroup,semaphore,singleflight.
Related
- Goroutines & Channels — the message-passing side of Go concurrency.
- Concurrency Patterns — these primitives assembled into pools, pipelines and shutdown.
- Locking & Concurrency Control — the same deadlock rules at the database layer.
- Distributed Locks & Leases — when a process-local mutex isn't enough.
- Rate Limiting — fleet-wide limits beyond a local semaphore.
- Concurrency & Synchronization — OS primitives under
sync.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).