The Go Memory Model
Concurrent programming introduces a problem that isn’t always obvious when reading code: how does one goroutine know that another goroutine’s changes are visible?
Consider a backend service where multiple goroutines update shared application state. One goroutine writes a value, while another reads it.
The code might look straightforward. It might even appear to work consistently during testing.
But without proper synchronization, the program can contain a data race.
Understanding the Go memory model is essential for writing concurrent code that is not just fast, but correct.
In this article, we’ll explore how Go defines memory visibility, what happens-before means, and how synchronization primitives establish safe communication between goroutines.
1. The problem with shared memory
Let’s start with a simple example:
package main
import (
"fmt"
"time"
)
func main() {
var ready bool
go func() {
ready = true
}()
for !ready {
time.Sleep(time.Millisecond)
}
fmt.Println("Ready!")
}
At first glance, this looks reasonable.
One goroutine updates ready, while the main goroutine waits until it becomes true.
But this program contains a data race.
Both goroutines access the same variable concurrently, and at least one access is a write. There is no synchronization establishing a safe relationship between them.
The fact that ready is a boolean doesn’t make the operation safe.
Even if the program appears to work on your machine, Go does not guarantee that the main goroutine will observe the update.
The compiler and runtime are allowed to make optimizations that can invalidate assumptions about unsynchronized memory access.
The important lesson is that concurrent access to shared memory requires synchronization when one or more accesses are writes.
2. Understanding the Go memory model
The Go memory model defines the conditions under which one goroutine’s memory operations are guaranteed to be observable by another.
Two concepts are particularly important:
- Sequenced before: The ordering of operations within a single goroutine.
- Synchronized before: The ordering established by synchronization operations between goroutines.
Together, these relationships contribute to the definition of happens-before.
An operation A happens before operation B if:
- A is sequenced before B, or
- A is synchronized before B, or
- A happens before some operation that happens before B.
This gives us a way to reason about memory visibility.
Consider the following:
var message string
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
message = "Payment processed"
}()
wg.Wait()
fmt.Println(message)
Why is this safe?
The assignment to message happens before the call to Done within the worker goroutine.
A call to Done synchronizes before the return of a Wait call that it unblocks.
Therefore, the assignment happens before the main goroutine reads message.
The important distinction is that the synchronization comes from the WaitGroup, not from the fact that the goroutine has probably finished executing.
3. What exactly is happens-before?
Let’s make the concept more concrete.
Imagine two goroutines:
- Goroutine A writes a value.
- Goroutine B reads that value.
We need a synchronization mechanism that establishes an ordering between the write and the read.
Without that relationship, the program cannot safely assume that B observes A’s write.
For example, consider a channel:
package main
import "fmt"
func main() {
message := make(chan string)
go func() {
message <- "Payment processed"
}()
result := <-message
fmt.Println(result)
}
The channel send synchronizes before the corresponding receive completes.
This establishes a happens-before relationship between the sender’s operations before the send and the receiver’s operations after the receive.
The receiver can safely observe the message.
This is more than passing data between goroutines. It is also a synchronization mechanism.
4. Mutexes: protecting shared state
Channels are useful for communication, but not every concurrent problem needs a channel.
Sometimes multiple goroutines need to access the same shared data structure.
Consider a shared request counter:
type Counter struct {
value int
}
func (c *Counter) Increment() {
c.value++
}
If multiple goroutines call Increment() simultaneously, the operation can race.
Why?
Because incrementing an integer is a read-modify-write operation:
- Read the current value.
- Add one.
- Write the updated value.
Two goroutines can interleave these operations and overwrite each other’s updates.
A mutex protects the critical section:
type Counter struct {
mu sync.Mutex
value int
}
func (c *Counter) Increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.value++
}
func (c *Counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.value
}
The mutex ensures that only one goroutine can access the protected state at a time.
More importantly, an unlock synchronizes before a subsequent successful lock on the same mutex.
This establishes the memory ordering required for safe access.
The general principle is simple:
If multiple goroutines access mutable shared state, protect that state with a clearly defined synchronization strategy.
5. Channels versus mutexes
Go’s concurrency philosophy is often summarized as:
Don’t communicate by sharing memory; share memory by communicating.
This is a useful design principle, but it doesn’t mean channels should replace every mutex.
The choice depends on the problem.
Use channels when:
- Goroutines exchange ownership of data.
- Work needs to be distributed among workers.
- Events need to be communicated.
- A pipeline coordinates multiple processing stages.
Use mutexes when:
- Multiple goroutines access shared state.
- A data structure needs coordinated updates.
- A critical section is easier to express through locking.
- Introducing channels would make the design unnecessarily complicated.
For example, a worker pool naturally uses channels to distribute jobs, while a shared in-memory cache may be more naturally protected by a mutex.
The goal is not to use more concurrency primitives. It is to make synchronization explicit and understandable.
6. Atomic operations: synchronization without a mutex
For certain simple shared-state operations, Go provides atomic primitives through sync/atomic.
Consider our earlier counter.
Instead of protecting an integer with a mutex, we can use an atomic counter:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var counter atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter.Add(1)
}()
}
wg.Wait()
fmt.Println(counter.Load())
}
The atomic increment ensures that concurrent updates are performed safely.
Go’s atomic operations provide sequentially consistent ordering: their behaviour can be understood as if all atomic operations occurred in a single global order consistent with program order.
However, atomics are not automatically a better alternative to mutexes.
They are useful for simple state transitions, counters, flags, and carefully designed lock-free algorithms.
When multiple fields must change together, a mutex is often easier to reason about.
Use atomics when the synchronization requirements are simple and the design remains understandable.
7. Safe publication: making initialized data visible
One subtle concurrency problem is publishing data to another goroutine.
Consider a service that initializes configuration and then starts background workers.
The intended sequence is:
- Initialize configuration.
- Start workers.
- Allow workers to read the configuration.
Go guarantees that the go statement that starts a goroutine is synchronized before the goroutine begins execution.
Therefore, initialization performed before starting the goroutine is visible to it, provided the data isn’t subsequently modified without synchronization.
For example:
type Config struct {
Endpoint string
Timeout time.Duration
}
func main() {
config := Config{
Endpoint: "https://api.example.com",
Timeout: 5 * time.Second,
}
go func(cfg Config) {
fmt.Println(cfg.Endpoint)
}(config)
time.Sleep(time.Second)
}
Passing the configuration by value gives the goroutine its own copy of the struct.
This is a straightforward way to avoid shared mutable state.
However, copying a struct does not necessarily copy everything it references. Slices, maps, pointers, and other reference-containing fields may still refer to shared underlying data.
If the configuration is shared by reference and modified later, appropriate synchronization is still required.
Safe publication is not just about making data available. It is about ensuring that readers observe fully initialized state and that subsequent mutations are coordinated.
8. Detecting data races in practice
Understanding the memory model is important, but detecting violations is equally important.
Go provides a built-in race detector.
Run your tests with:
go test -race ./...
Or run an application with:
go run -race .
The race detector instruments memory accesses and reports conflicting unsynchronized accesses that occur during execution.
For example, if two goroutines concurrently access a shared variable and at least one access is a write, the race detector can identify the issue when that execution path is exercised.
A few important limitations:
- It only detects races that actually occur during the instrumented execution.
- It introduces additional runtime and memory overhead.
- A clean race-detector run does not prove that a program is free of all concurrency bugs.
Still, it should be part of the development and testing workflow for concurrent Go applications.
9. What this means for production systems
Memory visibility is not an academic concern. Incorrect synchronization can produce difficult production failures.
Consider a payment-processing service with multiple goroutines updating transaction state.
Without proper synchronization, concurrent updates may overwrite one another or readers may observe inconsistent state.
In distributed systems, there is another important distinction: a Go mutex only coordinates goroutines within the relevant process. It does not provide consistency across multiple application instances.
If multiple service instances update the same transaction, database transactions, optimistic concurrency control, idempotency, or distributed coordination may be necessary.
The synchronization mechanism must match the scope of the problem.
A few principles are worth carrying into production:
Minimize shared mutable state.
Passing immutable data between goroutines is often easier to reason about than coordinating repeated mutations.
Define ownership clearly.
Know which goroutine owns a piece of state and which goroutines are allowed to access it.
Choose synchronization deliberately.
Use channels, mutexes, atomics, or higher-level coordination primitives based on the actual consistency requirements.
Test under concurrency.
Use the race detector and realistic concurrent workloads to expose problems that sequential tests may miss.
Don’t confuse process-level synchronization with distributed consistency.
A mutex cannot coordinate independent service instances or guarantee database-level transaction correctness.
Conclusion
The Go memory model gives us a formal way to reason about how concurrent operations interact.
Happens-before relationships establish the ordering and visibility guarantees required for safe communication between goroutines.
Mutexes protect shared mutable state. Channels coordinate communication. Atomics provide efficient synchronization for specific operations.
The most important lesson is that concurrent code must be correct by design, not merely appear to work during testing.
As backend systems grow, understanding memory visibility and synchronization becomes just as important as understanding goroutines and scheduling.
What’s next?
In Part 5, we’ll apply these concurrency principles to a practical infrastructure problem:
Designing Concurrent Rate Limiters in Go
We’ll explore token buckets, concurrency-safe state, distributed rate limiting, and how to protect backend services from excessive request traffic.
Further reading:
Comments