False Sharing in Go on Apple Silicon: Cache-Line Padding, Measured
8 goroutines with their own counters ran 3.7x slower than padded ones on an M2 Pro. 64-byte padding is not enough there; 128 is. Measured with pprof.
Every Go service that counts things per worker ends up with code like this: a slice of small structs, one per goroutine, so that no two goroutines write the same counter.
1
2
3
4
5
type stats struct {
n, sum atomic.Uint64 // 16 bytes
}
shards := make([]stats, workers) // worker w only ever touches shards[w]
There is no lock and no shared variable, and every goroutine has its own slot. On paper, this scales linearly. On the M2 Pro we measured it on, eight goroutines with their own counters ran 3.7 times slower than the same code with each slot padded to 128 bytes. In a tight counting loop, they were 10 times slower.
The cause is false sharing. A CPU core does not own a variable. It owns the whole cache line that holds it. When eight 16-byte slots share one cache line, every write by one core takes that line away from the other seven. The program is correct and race-free, but the hardware moves one line from core to core millions of times a second.
This post measures how big that cost is, what padding fixes it, why the usual 64-byte padding is not enough on Apple silicon, and a case where padding alone does not help. The program, the scripts and every number here are in this blog’s repository under scripts/go-false-sharing/.
The machine and the cache line
All runs used one Apple M2 Pro (8 performance cores, 4 efficiency cores, macOS 27.0.1) and go1.27.4 darwin/arm64. The number that matters is the cache line size, and the OS reports it:
1
2
$ sysctl hw.cachelinesize
hw.cachelinesize: 128
On most x86 servers the line is 64 bytes. On Apple M-series chips it is 128 bytes. Go knows this: golang.org/x/sys/cpu.CacheLinePad and the runtime’s own internal pad are 128 bytes on arm64 and 64 bytes on amd64. A struct padded “to a cache line” with a hard-coded 64 therefore still puts two slots on each line on a Mac, and on any other arm64 machine with 128-byte lines.
The workload
fsharing is a small Go program that uses the standard library only. In each run, W goroutines wait on a spinning start barrier, so they all start at once. Each one then does N operations, and every operation updates two counters: a count and a running sum, like one shard of a metrics collector. Only the memory layout of those counters changes between runs:
| layout | what each worker writes | slots per 128-byte line |
|---|---|---|
shared | one {n, sum} pair for everyone (true sharing, the naive version) | everyone on one line |
packed | []struct{ n, sum atomic.Uint64 }, 16 bytes a worker | 8 |
pad64 | the same, padded to 64 bytes (the x86 habit) | 2 |
pad128 | the same, padded to 128 bytes | 1 |
local | plain locals in the loop, added to a pad128 slot once at the end | 1, written once |
Two more layouts, packed-plain and pad128-plain, use plain uint64 fields and += instead of atomics. Because each worker writes only its own slot, they are race-free (go build -race agrees). They separate the cost of the atomic instruction from the cost of sharing the line.
The padded struct is the obvious one:
1
2
3
4
5
6
const lineSize = 128 // hw.cachelinesize on Apple M1/M2/M3
type pad128 struct {
n, sum atomic.Uint64
_ [lineSize - 16]byte
}
There are two kinds of operation:
- tight: the loop does nothing but the two counter updates. This is the worst case, and it shows the effect most clearly.
- hash: before the updates, each operation runs FNV-1a over a 64-byte record from a per-worker buffer of 256 KiB, which fits in the core’s L2 cache. That is about 560 instructions of real work for each pair of counter updates, closer to a real request handler.
Every run prints a checksum of all counters, and the summary script fails if any layout disagrees, so no layout can “win” by losing updates. The script also checks the address of the counter block: every padded block in every run started on a 128-byte boundary (base_mod128=0), so each padded slot really sat on its own line.
How we measured
measure.sh runs each cell (layout × workers × kind) as its own process under /usr/bin/time -l. That gives two numbers per cell:
- ns per operation: the wall time of the timed window, divided by the total number of operations.
- cycles and instructions per operation: the CPU cycles and retired instructions of the whole process, summed over all its threads, from the macOS counters that
time -lprints.
There were 11 repetitions, and the cell order was shuffled in each one. The host was busy with other work during the run (1-minute load average 18.7 to 27.2 on 12 cores), so wall time is noisy: single runs of the same cell varied by 2-4x between their fastest and slowest. Cycles per operation do not count time a thread spent descheduled, so they are the steadier number. Where both are quoted, they agree on the direction and on the rough size of every effect below. All figures are medians, and the full table with min and max is in scripts/data/go-false-sharing-m2pro.json.
Result 1: per-worker counters do not scale until they are padded
With one goroutine, all four layouts run at the same speed (58-64 million updates per second): with no other core, there is nothing to share. Adding goroutines splits the layouts apart:
| tight loop, atomics | 1 goroutine | 2 | 4 | 8 | cycles/op at 8 (vs 1) |
|---|---|---|---|---|---|
| one shared pair | 58.5 M/s | 42.1 | 27.6 | 18.5 | 393 (13x) |
| packed, 16 B a worker | 60.6 M/s | 40.2 | 23.9 | 28.8 | 264 (8.9x) |
| padded to 64 B | 63.9 M/s | 95.4 | 133.0 | 215.5 | 46 (1.6x) |
| padded to 128 B | 58.6 M/s | 112.3 | 198.0 | 291.5 | 31 (1.0x) |
Three things stand out:
- Packed per-worker slots behave almost like one shared counter. At 8 goroutines, the “lock-free, sharded” version delivers 28.8 million updates a second, against 18.5 for one shared counter and 291.5 for the padded version. That is 10.1x slower than padded, while every goroutine writes only its own memory.
- Padding to 128 bytes makes the cost per operation flat. At 8 goroutines it is 31 cycles per update, the same as with one goroutine (30). The work now scales with the cores.
- Padding to 64 bytes is only part of the fix on this chip. Two slots still share each 128-byte line, so each line still moves between two cores. That cost 1.5x the cycles and 1.35x the time of the 128-byte layout at 8 goroutines.
The local layout, which counts in local variables and writes the slot once at the end, reached 6,024 million updates per second at 8 goroutines. It does no atomic or shared write in the loop at all. When the counters do not need to be read while the loop runs, this is the fix to reach for first.
Result 2: the extra time is cycles, not instructions
The tight loop is the extreme case. The hash workload is closer to real code: about 560 instructions of hashing for every two counter updates. False sharing still made it 3.7x slower:
| hash workload, 8 goroutines | ns/op | cycles/op | instructions/op |
|---|---|---|---|
| one shared pair | 148.4 (5.4x) | 887 (4.7x) | 580 |
| packed, 16 B a worker | 102.6 (3.7x) | 673 (3.6x) | 581 |
| padded to 64 B | 30.4 (1.1x) | 242 (1.3x) | 575 |
| padded to 128 B | 27.7 | 187 | 575 |
| local, flush once | 27.0 | 180 | 558 |
Every layout ran almost the same number of instructions per operation. The packed layout needed 3.6 times as many cycles for them. The core spends those cycles waiting for a cache line that another core holds. No count of instructions, no -gcflags=-m and no allocation profile will show you this. You only see it in time and cycles.
Once the slots are padded to 128 bytes, the two atomic adds cost almost nothing: 187 cycles per operation against 180 for the version with no atomics in the loop.
Result 3: what pprof shows
A CPU profile of the slow layout points straight at the counter updates, which is a useful tell. We profiled the hash workload with 8 goroutines, packed and padded, with the standard runtime/pprof CPU profiler, and opened both in go tool pprof -http:
In the packed profile, 77.6% of CPU samples fall on sync/atomic.(*Uint64).Add, the two atomic adds of each operation. The hottest line of the 560-instruction hash gets 17.5%. In the padded profile, the hash is on top with 83.3%, and the two adds get 20 ms of 1.38 s.
So if a profile shows a large share of time on one atomic add, one plain store, or one mu.Lock of an uncontended mutex, look at what else sits on the same 128 bytes. Recent CPUs make an uncontended atomic cheap. When an atomic dominates the profile, the usual cause is a cache line that is shared between cores.
On arm64, Go compiles atomic.Uint64.Add to one LDADDALD instruction when the CPU has the LSE atomics (it checks runtime.arm64HasATOMICS once). The instruction is not slow. Getting the line it writes into this core’s cache is.
Result 4: it is not an atomics problem
The obvious objection is that atomics are the slow part and plain fields would be fine. Plain fields are faster, but they suffer from false sharing just as much:
- In the tight loop, plain
+=on packed slots took 3.3x as long as on padded slots (1.02 ns against 0.31 ns per operation). - In the hash loop, it took 2.0x as long (45.0 ns against 22.9 ns).
Packed plain counters (45.0 ns) are still slower than padded atomic counters (27.7 ns). If you have to choose, padding matters more than removing the atomics.
The Go compiler does not keep the field in a register across the loop: each c.n++ on a pointer to a heap slot is a load and a store to memory. Every store needs the line in the “modified” state in this core’s cache, and with eight slots on a line, the line keeps moving. Atomics or not, the line is shared.
Result 5: a ring buffer where padding alone does nothing
The standard textbook case for padding is a single-producer, single-consumer ring. The producer writes tail, the consumer writes head, and putting the two on separate cache lines is meant to stop them fighting over one line. We tested three versions with 20 million items through a 1,024-slot ring:
| SPSC ring | ns/item | cycles/item |
|---|---|---|
head and tail side by side | 164 | 546 |
| each on its own 128-byte line | 171 (1.04x) | 538 |
| own lines + cached index | 93.1 (0.57x) | 319 |
Padding head and tail apart changed nothing: 164 against 171 ns, inside the run-to-run noise, with the same cycles. The reason is that this is mostly true sharing. On every item, the producer reads head, which the consumer just wrote, and the consumer reads tail, which the producer just wrote. Each line moves between the two cores once per item whether head and tail share it or not.
What helped was to stop reading the other side’s index on every item. In the third version, each side keeps a private copy of the other’s index and re-reads the shared one only when the ring looks full (producer) or empty (consumer):
1
2
3
4
5
6
7
8
// producer
t := r.tail.Load()
if t-headSeen == ringSize { // looks full: only now look at the consumer's line
for headSeen = r.head.Load(); t-headSeen == ringSize; headSeen = r.head.Load() {
}
}
r.buf[t%ringSize] = v
r.tail.Store(t + 1)
That cut the time per item by 43% and the cycles by 42%. Padding is needed for this to work, because the private copies only help if the shared indexes are not on the same line as anything else. Padding alone did not help.
A checklist
- Find out the line size of the machine you deploy to. Run
sysctl hw.cachelinesizeon macOS, orgetconf LEVEL1_DCACHE_LINESIZEon Linux. It is 128 bytes on Apple M-series, 64 bytes on most x86. Some arm64 server chips use 64, others 128. Pad with the platform’s constant, not a literal.
_ cpu.CacheLinePadfromgolang.org/x/sys/cpu(an external module) is 128 bytes on arm64 and 64 on amd64. To pin the size exactly, use a fixed array and a compile-time check that fails if the struct is ever not one line long:1 2 3 4 5 6 7
type shard struct { n, sum atomic.Uint64 _ [128 - 16]byte } // Does not compile if shard is not exactly 128 bytes. var _ = [1]struct{}{}[unsafe.Sizeof(shard{})-128]
Putting
cpu.CacheLinePadafter 16 bytes of fields gives a 144-byte struct, not a 128-byte one. That still keeps every slot’s fields on its own line, but slices get 12% bigger. Pick one approach on purpose.- Make sure the slice itself starts on a line boundary. Go’s allocator gave every 128-byte-element slice in these runs a 128-byte-aligned start, but the language does not promise it. For a single global, put a pad on both sides.
- Prefer local accumulation over padding. If the counters do not have to be readable while the loop runs, count in locals and publish once. That was the fastest layout in every case.
- Check the profile, then the counters. A large share of samples on an atomic add or a plain store to a struct field is the sign. Cycles per operation that grow with the number of goroutines while the instruction count stays flat confirm it.
- Remember true sharing. Padding fixes only false sharing. If two goroutines read what the other writes on every operation, as in the ring buffer, change the protocol (batch, cache, or shard the work), not the layout.
Reproduce it
1
2
3
4
REPS=11 bash scripts/go-false-sharing/measure.sh /tmp/fs-work # ~5 min; default REPS=5 takes ~2
python3 scripts/go-false-sharing/summarise.py /tmp/fs-work # -> scripts/data/go-false-sharing-m2pro.json
BROWSER_PATH=<chrome-headless-shell> bash scripts/go-false-sharing/shots.sh /tmp/fs-work
python3 scripts/go-false-sharing/gen_images.py /tmp/fs-work # charts and the pprof screenshots
The program needs only the Go standard library. measure.sh uses macOS’s /usr/bin/time -l for the instruction and cycle counters. On Linux, perf stat -e cycles,instructions gives the same two numbers.
Takeaways
- Per-goroutine counters that share a cache line do not scale. On an M2 Pro, eight goroutines with 16-byte slots ran 10.1x slower than padded slots in a tight loop, and 3.7x slower with 560 instructions of real work around each update.
- The cost is cycles, not instructions. Instruction counts were within 5% of each other across all layouts. Cycles per operation differed by up to 4.7x. pprof puts it on the store or atomic that touches the shared line: 77.6% of samples on one
atomic.Add. - 64-byte padding is an x86 habit. On 128-byte-line hardware it still cost 1.3-1.5x the cycles of 128-byte padding. Use the platform’s line size or
cpu.CacheLinePad. - Plain fields are not a fix. Plain
+=on packed slots was 2.0-3.3x slower than on padded slots. - Padding cannot fix true sharing. In an SPSC ring, padding
headandtailapart did nothing. Caching the other side’s index cut the time per item by 43%.
We used the same measure → change one thing → re-measure loop for this post as for the rest of this series. Measuring a change against a baseline before accepting it is how the self-improvement (RSI) loop in Hive, Lamplit Labs’ open-source agent harness for an AI-native SDLC, decides which changes to keep.
Related reading
- Go PGO in Practice: What go build -pgo Changed in a Log Router, Measured: the same instruction-and-cycle counters on a compiler change, where the cost was instructions, not cycles.
- Go pprof Profiling Guide: CPU, Goroutine and Mutex Profiles on One Service: how to collect and read the CPU profiles shown above.
- sync.Pool vs fresh allocation, round two: p99 under a live HTTP handler: another per-goroutine structure where the effect only shows under load.
- Rust RwLock on a Read-Heavy Path: parking_lot vs std::sync, Measured: lock-word cache-line traffic from the Rust side.
- Rust Lock Contention Under Load: When RwLock Loses to a Sharded Cache: sharding as the fix for true sharing.
- Hive: Lamplit Labs’ open-source, self-improving (RSI) agent harness: the product mentioned above.





