Concurrency & Synchronization
- Identify race conditions and critical sections in money-moving and inventory code
- Choose between mutex, RWMutex, semaphore, condition variable, atomics and channels for a given access pattern
- Explain memory ordering and the Go memory model well enough to avoid "it works on my laptop" races
- State the four Coffman conditions and prevent deadlock with lock ordering in a transfer service
- Implement producer-consumer and readers-writers patterns correctly in Go
TL;DR
- A race condition is when correctness depends on interleaving. In a bank, the classic one is read-check-write on a balance: two debits both see 100 and the account goes negative.
- Mutexes give mutual exclusion; on Linux they are built on futexes (user-space fast path, kernel only on contention). Go's
sync.Mutexparks goroutines, not threads, and switches to a fair "starvation mode" after a waiter waits more than 1 ms. - Semaphores bound concurrency (bulkheads); condition variables wait for a predicate and must always be used in a
forloop; spinlocks only make sense for very short critical sections where the holder cannot be preempted. - Atomics are cheap for single words but don't compose; CPUs and compilers reorder memory operations, so only synchronisation primitives (mutexes, channels, atomics) create happens-before edges. In Go, atomics are sequentially consistent.
- Deadlock requires all four Coffman conditions: mutual exclusion, hold-and-wait, no preemption, circular wait. Break one — usually circular wait via a global lock order (e.g. lock accounts by ID).
- In-process locks only protect one process. Across pods you need database row locks, conditional updates or distributed locks.
Why it matters
A flash sale offers 1,000 phones. Thousands of checkout goroutines across 40 pods try to decrement stock. A non-atomic if stock > 0 { stock-- } oversells; a global mutex serialises everything and caps throughput; a database SELECT ... FOR UPDATE on one hot row turns into a lock convoy. In a bank, two concurrent transfers A→B and B→A that lock "source then destination" deadlock under load, and the payment queue backs up until timeouts fire.
These are concurrency problems first and distributed-systems problems second. Interviewers use them to see whether you can reason about interleavings, pick the right primitive and explain the cost. The same thinking scales up to Locking & Concurrency Control and Distributed Locks & Leases.
Core concepts
Race conditions and critical sections
- A data race (Go's definition): two goroutines access the same memory concurrently, at least one writes, and they are not ordered by synchronisation. Data races are bugs even when "the result looks right"; in Go, racing on multi-word values (interfaces, slices, strings) can even produce torn values and memory corruption.
- A race condition is broader: logic depends on timing, even with no data race (e.g. check-then-act across two separately locked operations).
- A critical section must provide mutual exclusion, progress (someone eventually enters) and bounded waiting (no one waits forever).
Hardware building blocks
- Atomic read-modify-write instructions: compare-and-swap (CAS,
LOCK CMPXCHGon x86), fetch-and-add, exchange. Everything else is built on these. - Cache coherence (MESI-family protocols) keeps caches consistent at cache-line granularity (64 bytes on most x86/ARM). A contended atomic or lock makes the line bounce between cores — each transfer costs tens of nanoseconds or more (rough).
- False sharing: two independent counters in the same cache line, updated by different cores, contend as if they were one. Pad hot per-core structs (
golang.org/x/sys/cpu.CacheLinePad).
Mutex
A mutex (lock) gives exclusive access. Modern implementations are adaptive:
- Fast path: one CAS in user space when uncontended (roughly 10–20 ns, rough).
- Brief spinning if the holder is running on another CPU.
- Slow path: sleep in the kernel (
futex(FUTEX_WAIT)) and be woken by the unlocker (FUTEX_WAKE) — microseconds.
Go's sync.Mutex is similar but parks goroutines on runtime semaphores, so a blocked goroutine frees its thread to run other goroutines. It has two modes:
- Normal mode: woken waiters compete with newly arriving goroutines (which are already on-CPU and usually win) — good throughput, possible unfairness.
- Starvation mode: if a waiter has waited more than 1 ms, ownership is handed directly to the head of the queue until the queue drains — fairness over throughput.
Rules: keep critical sections short; never do I/O (DB calls, HTTP) while holding a lock unless the lock exists precisely to serialise that I/O; always defer mu.Unlock() unless profiling shows the defer matters; never copy a struct containing a mutex (go vet checks this).
Spinlocks
A spinlock busy-waits instead of sleeping. Good when the critical section is a few dozen instructions and the holder cannot be descheduled — which is true inside the kernel (spinlocks disable preemption, sometimes interrupts). In user space a spinning thread can't stop the OS from preempting the holder, so spinners may burn an entire time slice — and under container CPU limits they burn quota too. Use adaptive mutexes in application code.
Semaphores
A counting semaphore holds N permits: acquire blocks when zero, release returns one. A binary semaphore (N = 1) is like a mutex but without ownership (any thread can release).
Backend uses: limit concurrent calls to a fragile dependency (a core-banking host that allows 50 sessions), cap concurrent expensive operations (PDF statement generation), bound worker parallelism. In Go use a buffered channel (make(chan struct{}, 50)) or golang.org/x/sync/semaphore (weighted, context-aware).
Condition variables
A condition variable lets a goroutine sleep until a predicate on shared state may have become true. It is always paired with a mutex:
Waitatomically unlocks the mutex and sleeps; on wake-up it re-locks before returning.- Always re-check the predicate in a loop — another goroutine may have consumed the item first, and spurious wake-ups are allowed by most implementations.
Signalwakes one waiter;Broadcastwakes all (use when the state change may satisfy several waiters, or different waiters wait for different predicates).
In Go, channels cover most cases (sync.Cond cannot be combined with select or a context). sync.Cond still fits "many waiters, repeated broadcast on state change".
Atomics and memory ordering
Without synchronisation, neither the compiler nor the CPU promises that other cores see your writes in program order:
Initially x = 0, y = 0
Core 1: x = 1; r1 = y
Core 2: y = 1; r2 = x
Can both r1 and r2 be 0?
x86 (TSO): yes. Each store waits in its core's store buffer while the
following load reads the old value from cache. ARM and POWER allow even
more reorderings (load-load, store-store) unless barriers are used.
The Go memory model (revised in 2022) defines happens-before: if event A happens-before B, B observes A's effects. Edges are created by:
- channel send → corresponding receive completes; closing a channel → a receive that returns because it is closed;
Unlock→ a laterLockof the same mutex;sync.Oncefunction return → everyDocall returning;- atomic operations: Go's
sync/atomicoperations are sequentially consistent (like C++seq_cst), and an atomic write that is observed by an atomic read happens-before it.
Consequences:
- A plain boolean "done" flag written by one goroutine and polled by another is a data race; the reader may never see it (the compiler can hoist the load out of the loop). Use
atomic.Bool, a channel or a mutex. - Double-checked locking without atomics is broken; use
sync.Once(orsync.OnceValue). - Atomics are per-word. "Check balance then subtract" across two atomics is still a race — use a CAS loop or a mutex.
Deadlock
Coffman et al. (1971) — deadlock is possible only if all four hold:
| Condition | Meaning | How to break it |
|---|---|---|
| Mutual exclusion | Resource can be held by one at a time | Use lock-free/immutable data, or sharable resources (read locks) |
| Hold and wait | Hold one resource while waiting for another | Acquire all locks at once (or none); release before waiting |
| No preemption | Resources can't be taken away | Try-lock with timeout and back off; DB deadlock detector aborts a victim |
| Circular wait | A cycle in the wait-for graph | Global lock ordering (lock lower account ID first) |
Beyond prevention:
- Avoidance (Banker's algorithm) checks each request against declared maximum needs — rarely used in practice because needs are unknown.
- Detection and recovery: databases build a wait-for graph and abort a victim. PostgreSQL checks after
deadlock_timeout(1 s default) and raises SQLSTATE40P01; your code should retry the transaction. - Go's runtime only detects global deadlock ("all goroutines are asleep - deadlock!"). A partial deadlock — two goroutines stuck while HTTP handlers still run — is invisible and looks like a goroutine leak.
Livelock, starvation, priority inversion
- Livelock: threads keep reacting to each other and make no progress — two transactions that detect conflict, back off for the same fixed time, and collide again. Fix: randomised (jittered) backoff.
- Starvation: a thread never gets the resource — writers starving under a reader-preferring lock, low-priority jobs under strict priority scheduling. Fix: fairness (FIFO handoff, Go's starvation mode), aging.
- Priority inversion: a high-priority task waits for a lock held by a low-priority task that is preempted by a medium-priority task. The Mars Pathfinder resets (1997) were caused by this; the fix was enabling priority inheritance on the mutex.
Producer-consumer (bounded buffer)
Producers block when the buffer is full; consumers block when it is empty. The bound gives backpressure — the same idea as a bounded Kafka consumer pipeline or a worker pool. In Go, a buffered channel is a bounded buffer; the explicit version below shows what the channel does for you.
Readers-writers
Many readers may hold the lock together; writers need exclusivity. Policies:
- Reader preference: maximum read throughput, writers can starve.
- Writer preference: a waiting writer blocks new readers. Go's
sync.RWMutexbehaves this way — onceLockis waiting, newRLockcalls block — so a recursiveRLockcan deadlock. - Copy-on-write snapshot: readers take no lock at all; a writer builds a new version and publishes it with an atomic pointer swap. Ideal for read-mostly data such as FX rate tables, feature flags, routing tables.
RWMutex is not free: every RLock does an atomic add on shared state, so with many cores and tiny read sections it can be slower than a plain Mutex or a snapshot.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
sync.Mutex | Simple, composable invariants across fields, cheap uncontended | Serialises; contention hurts tail latency | Default for protecting a struct's invariants |
sync.RWMutex | Parallel readers | Reader-count contention; writer preference; recursive RLock deadlock | Read-heavy with non-trivial read sections |
| Atomics / CAS loop | No blocking, very fast for single words | Doesn't compose across fields; subtle; contention still bounces cache lines | Counters, flags, single-value state machines |
| Atomic pointer snapshot (copy-on-write) | Lock-free reads, consistent snapshots | Writes copy the structure; more garbage | Read-mostly config, rate tables, caches rebuilt periodically |
| Channels | Ownership transfer, backpressure, select with timeouts/ctx | Overhead higher than a mutex; easy to leak goroutines | Pipelines, worker pools, signalling, handoff |
| Sharded/striped locks | Reduces contention by partitioning | More memory; cross-shard operations need ordering | Hot maps, per-SKU or per-account state |
| DB row lock / conditional UPDATE | Works across pods; durable | Network round-trips; hot rows serialise | Anything that must be correct across instances (balances, stock) |
In practice
Lock ordering for transfers (in-process version; the same rule applies to SELECT ... FOR UPDATE order in SQL):
package ledger
import (
"errors"
"sync"
)
var (
ErrSameAccount = errors.New("same account")
ErrInsufficientFunds = errors.New("insufficient funds")
)
type Account struct {
ID int64
mu sync.Mutex
balance int64 // minor units
}
// Transfer locks accounts in ascending ID order, so concurrent
// A->B and B->A transfers cannot form a cycle.
func Transfer(from, to *Account, amount int64) error {
if from.ID == to.ID {
return ErrSameAccount
}
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
}
A bounded buffer with condition variables (what a buffered channel gives you for free):
package queue
import "sync"
type Bounded[T any] struct {
mu sync.Mutex
notEmpty *sync.Cond
notFull *sync.Cond
items []T
limit int
}
func NewBounded[T any](limit int) *Bounded[T] {
q := &Bounded[T]{limit: limit}
q.notEmpty = sync.NewCond(&q.mu)
q.notFull = sync.NewCond(&q.mu)
return q
}
func (q *Bounded[T]) Put(v T) {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == q.limit { // always re-check after waking
q.notFull.Wait()
}
q.items = append(q.items, v)
q.notEmpty.Signal()
}
func (q *Bounded[T]) Take() T {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == 0 {
q.notEmpty.Wait()
}
v := q.items[0]
q.items = q.items[1:] // a ring buffer avoids re-slicing in production
q.notFull.Signal()
return v
}
Lock-free stock reservation within one process, and a copy-on-write rate table:
package flash
import (
"sync/atomic"
"time"
)
// TryReserve decrements stock by n if enough remains, without a mutex.
func TryReserve(stock *atomic.Int64, n int64) bool {
for {
cur := stock.Load()
if cur < n {
return false
}
if stock.CompareAndSwap(cur, cur-n) {
return true
}
// Lost the race: another goroutine changed stock. Retry.
}
}
type RateTable struct {
Rates map[string]int64 // "USD/VND" -> rate in micro-units
UpdatedAt time.Time
}
var rates atomic.Pointer[RateTable]
// PublishRates swaps in a fully built table; readers never see a partial map.
func PublishRates(t *RateTable) { rates.Store(t) }
func Rate(pair string) (int64, bool) {
t := rates.Load()
if t == nil {
return 0, false
}
r, ok := t.Rates[pair]
return r, ok
}
TryReserve is correct only within a single process. With 40 pods, the shared counter must live in Redis (DECR or a Lua script that checks first) or the database (UPDATE inventory SET stock = stock - 1 WHERE sku = $1 AND stock >= 1 and check rows affected). See Inventory & Flash Sales.
Tooling:
go test -race ./...and race-enabled canary builds. The race detector only finds races that actually execute; expect roughly 2–20× slowdown and 5–10× memory.- Mutex and block profiles:
runtime.SetMutexProfileFraction(5),runtime.SetBlockProfileRate(...), then/debug/pprof/mutexand/debug/pprof/block. go vetcatches copied locks;golang.org/x/sync/errgroupandsemaphorecover most structured-concurrency needs.
Common pitfalls
- Check-then-act across separate critical sections.
if cache.Get(k) == nil { cache.Set(k, load()) }with each call locked separately: thundering herd of loads. Usesingleflightor hold the lock across both. - Holding a lock while calling the network. A slow downstream turns into a global stall. Symptom: mutex profile dominated by one lock; latency tracks the downstream.
- Inconsistent lock order between code paths (refund locks order then account; payment locks account then order). Symptom: occasional hangs under load, goroutine dump shows two goroutines each in
Lock. - Recursive
RLockwhile a writer waits → deadlock. Symptom: rare freezes during config reloads. - Unsynchronised flags and lazy init. Polling a plain
bool, or hand-rolled double-checked locking. Symptom: works in tests, fails on ARM or under-race. sync.Cond.Waitwithout a loop, orSignalwhenBroadcastis needed. Symptom: lost wake-ups, consumers stuck while items are queued.- Unbounded goroutines as "producer-consumer". Spawning a goroutine per message with no limit removes backpressure. Symptom: memory explosion during a traffic spike.
- In-process locks for cross-instance invariants. Works on one pod, oversells with ten.
- False sharing in per-worker counters. Symptom: adding cores makes a counter-heavy benchmark slower.
Interview angle
- Expect "how would you prevent double-spending / overselling?" Strong answers move from in-process (mutex, CAS) to cross-process (DB conditional update, row locks, Redis atomic ops, idempotency keys), explaining where each breaks.
- "What is a deadlock and how do you avoid it?" — list the four Coffman conditions and give a concrete prevention (lock ordering by account ID), plus detection/retry for databases (
40P01). - "Mutex vs channel in Go?" — mutex for protecting state invariants, channels for transferring ownership and coordinating; cite "share memory by communicating" without being dogmatic.
- Follow-ups: what is a memory barrier; why a plain bool flag is a race; RWMutex writer preference; how Go's mutex avoids starvation; spinlock vs mutex.
- Red flags: "Go is safe because of goroutines"; "atomics make everything thread-safe"; using
time.Sleepto fix races; not knowing the race detector.
Self-check
1. Two goroutines each run counter++ 1,000 times on a shared int. Why can the result be less than 2,000, and give two correct fixes?
counter++ is read, add, write — not atomic. Two goroutines can read the same value and both write value+1, losing an increment (and it is a data race, so behaviour is undefined in the Go memory model). Fixes: atomic.Int64.Add(1), or protect it with a sync.Mutex; alternatively give each goroutine its own counter and sum at the end.
2. State the four Coffman conditions and say which one lock ordering breaks.
Mutual exclusion, hold and wait, no preemption, circular wait. A global lock order (e.g. always lock the lower account ID first) breaks circular wait: no cycle can form in the wait-for graph because every goroutine acquires locks in the same increasing order.
3. Why must sync.Cond.Wait be called in a loop?
Between the signal and the waiter re-acquiring the mutex, another goroutine may change the state (e.g. take the item), and implementations may wake waiters spuriously or via Broadcast when only some predicates are true. The loop re-checks the predicate under the lock before proceeding.
4. On x86, can two cores each store to one variable and then load the other and both see zeros? What does Go guarantee?
Yes: x86-TSO allows a store followed by a load to a different address to be reordered via the store buffer, so both loads can see 0. Go guarantees nothing for unsynchronised accesses (it's a data race). If the variables are accessed with sync/atomic, Go's atomics are sequentially consistent, so the both-zero outcome is impossible.
5. When is a spinlock better than a mutex, and why is it usually wrong in a Go service?
When the critical section is very short and the holder cannot be preempted (kernel code with preemption disabled), spinning avoids the cost of sleeping and waking. In a Go service, the holder goroutine can be descheduled by the Go scheduler or the OS (or throttled by CFS quota), so spinners waste CPU and quota. sync.Mutex already spins briefly before parking.
6. Scenario: a pricing service reloads a 50,000-entry promotion table every minute and serves 30,000 reads/s. Which primitive and why?
Copy-on-write snapshot with atomic.Pointer: build the new table off to the side, then Store it. Reads do one atomic load and no locking, scaling across cores; each request sees a consistent version. RWMutex would work but adds reader-count contention and blocks readers during the swap; a plain Mutex would serialise reads.
7. Why does a CAS loop for stock reservation not solve overselling in a 40-pod deployment, and what does?
Each pod has its own memory, so a per-process atomic counter only coordinates goroutines within that pod. A shared authority is required: a conditional database update (UPDATE ... WHERE stock >= n, check rows affected), a Redis atomic decrement/Lua script, or a partitioned reservation service — combined with idempotency keys so retries do not double-reserve.
Exercise
Build and break a tiny in-memory ledger.
- Implement
AccountandTransferwithout lock ordering (lockfromthento). Write a test that spawns 1,000 goroutines doing random transfers among 10 accounts in both directions. Observe the hang; capture a goroutine dump withSIGQUITor/debug/pprof/goroutine?debug=2and identify the cycle. - Fix it with ID ordering. Add an invariant check: total balance is constant after all transfers. Run with
go test -race -count=20. - Replace per-account mutexes with one global mutex and benchmark both (
go test -bench . -cpu 1,4,8). Then enable the mutex profile and compare contention. - Implement
TryReservewith a CAS loop and with a mutex; benchmark under 8 and 64 goroutines. Explain the results in terms of cache-line contention. - Bonus: write the SQL version of the transfer for PostgreSQL that locks both rows in ID order (
SELECT ... WHERE id IN ($1, $2) ORDER BY id FOR UPDATE) and handles40P01with a retry.
Done looks like: a passing race-enabled test suite, a benchmark table, and a paragraph explaining which design you would ship and why.
Further reading
- Operating Systems: Three Easy Pieces — Concurrency part: locks, condition variables, semaphores, common concurrency bugs: https://pages.cs.wisc.edu/~remzi/OSTEP/
- Allen B. Downey, The Little Book of Semaphores (free book) — classic synchronisation problems
- The Go Memory Model: https://go.dev/ref/mem
- Russ Cox, "Memory Models" series (Hardware, Programming Language, and Updating the Go Memory Model, 2021)
- Paul E. McKenney, Is Parallel Programming Hard, And, If So, What Can You Do About It?
- Coffman, Elphick, Shoshani, "System Deadlocks" (ACM Computing Surveys, 1971)
Related
- sync, atomic & context — the Go APIs in detail
- Concurrency Patterns — pipelines, worker pools, fan-out/fan-in
- Locking & Concurrency Control — row locks, MVCC and database deadlocks
- Distributed Locks & Leases — mutual exclusion across machines
- Inventory & Flash Sales — contention on hot stock counters
- Double-Entry Ledger Design — correctness of balance updates
- Processes & Threads — what is being synchronised and how it is scheduled
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).