Zum Hauptinhalt springen

The Counter That Fought Itself: False Sharing and the Cache Line

· 11 Minuten Lesezeit
Clustron Team
Engineering für verteilte Systeme

Here is a performance bug that feels like a contradiction. A server has a counter — bytes processed, requests served, a rate meter — and each worker thread increments it on the hot path. The increment is a single atomic instruction, there is no lock, and the counter is logically trivial. Yet when the server is given more cores, throughput does not rise; it falls, and a profiler blames the cheapest line in the program. The code is correct and the contention is invisible, because the thing the cores are fighting over is not in the source at all.

The missing piece is how CPUs actually move memory. A core does not read or write individual bytes from main memory; it pulls in a cache line — a fixed block, almost always 64 bytes — and all reads and writes happen against that cached line. Cache coherence then guarantees that if one core writes to a line, every other core's cached copy of that line is invalidated, so nobody reads stale data. This is exactly right and exactly necessary. The trap is the granularity: coherence operates on the whole 64-byte line, not on the individual variable, so two completely unrelated variables that happen to land in the same line are treated as one unit of contention.

That is false sharing. Two threads write two different counters, share nothing logically, hold no common lock — but their counters sit in the same cache line, so each write yanks the line away from the other core's cache. The line ping-pongs across the interconnect, every "cheap" atomic increment turns into a cross-core cache miss costing tens to hundreds of cycles, and adding cores makes it worse because there are now more writers fighting over the same line. The scaling curve bends the wrong way.

The line is the unit of contention​

To see why it bites so hard, follow one line through the coherence protocol. Core 0 wants to increment counter A; it loads A's cache line into its L1 in an exclusive/modified state and writes. Core 1 wants to increment counter B, which lives three bytes away in the same line; to write, it must take the line exclusive, which means invalidating core 0's copy and fetching the line across the interconnect. Now core 0 increments A again, and must pull the line back, invalidating core 1. Neither counter is shared, but the line is, and the line is what the hardware tracks. The two cores have accidentally serialized themselves through the memory system, achieving the throughput of one core minus the cost of all that bouncing.

The cruelty is that it is invisible in the code. True contention — a real lock, a shared accumulator every thread updates — is at least visible as a shared variable you can reason about. False sharing has no shared variable; it is an artifact of layout, of which fields the allocator or the struct packer happened to put next to each other. A single array of per-thread counters, long[] counts indexed by thread id, is the classic offender: eight consecutive longs are 64 bytes, so the first eight threads' counters all share one line and contend maximally, even though the whole point of the array was to give each thread its own slot.

False sharing — A and B share one 64-byte line, so the cores fight over itcore 0core 1ABone cache line = 64 bytesline bounces core→core on every incrementPadded — each counter owns a full line, so the cores never collidecore 0core 1AA's own line (padded)BB's own line (padded)separate lines → no invalidation traffic → throughput scales with cores

Spotting it: scaling that goes backwards​

The signature of false sharing is distinctive and worth memorizing, because it is the opposite of what intuition predicts. A workload that is CPU-bound and lock-free is supposed to scale up with cores. False sharing makes it scale down: one thread is fast, two are slower than one, and each added thread drops throughput further, while the CPUs sit at high utilization doing nothing useful — the cycles are spent stalled on cross-core cache misses, which still count as busy. If a lock-free counter or a per-thread array shows negative scaling and the profiler attributes huge time to a trivial atomic or a plain field write, suspect the line, not the code. Hardware performance counters confirm it directly: a spike in cache-line invalidations or "HITM" (hit-modified-in-another-core) events on an address that your logic says is private is false sharing caught red-handed.

It is the hidden tax behind a whole class of "why doesn't this scale?" mysteries, and it sits right next to the ones Zaris has written about before: the worker-pool ceiling where threads are capped, the latency floor set by fixed per-op costs, and the goal of reads that scale with cores. A shared statistics counter touched on every request is exactly the kind of thing that quietly turns a linear read path sublinear.

The fix: give each writer its own line​

The cure is to stop sharing the line, which means either padding a hot variable out to a full line so nothing else can share it, or — better for counters — giving each core or each thread its own independent cell on its own line and summing them only when someone actually reads the total. The write path then touches purely local state with no cross-core traffic, and the rare read pays the aggregation cost. .NET makes the padding idiom explicit.

// WRONG: eight threads' counters pack into one 64-byte line → maximal false sharing.
long[] counts = new long[threadCount];
void Hit(int t) => Interlocked.Increment(ref counts[t]); // every increment bounces the line

// RIGHT: pad each counter onto its own cache line so writers never collide.
[StructLayout(LayoutKind.Explicit, Size = 64)] // one full line per counter
struct PaddedLong { [FieldOffset(0)] public long Value; }

PaddedLong[] striped = new PaddedLong[threadCount];
void Hit(int t) => Interlocked.Increment(ref striped[t].Value); // local line, no bouncing

long Total() { // readers pay the sum, writers don't
long sum = 0;
for (int i = 0; i < striped.Length; i++) sum += Volatile.Read(ref striped[i].Value);
return sum;
}

This striping is precisely the move behind Zaris's per-core rate counters: a metric incremented on every single operation cannot live in a shared cell, so each core accumulates into its own padded slot and the aggregate is computed lazily on read. It is the same instinct as spreading a hot key across replicas — take the thing everyone hammers and give each hammer its own target — applied one level down, at the cache line instead of the key. The trade is a little memory (a full line per counter instead of eight bytes) for the removal of all coherence traffic, which on a hot path is overwhelmingly worth it.

Wrap-up​

False sharing is contention without a shared variable: the CPU tracks ownership at the 64-byte cache-line granularity, so two unrelated fields in the same line make two cores invalidate each other on every write, and the line ping-pongs across the interconnect while the "cheap" atomic increment quietly becomes a cross-core miss. Its fingerprint is a lock-free, CPU-bound workload that scales downward with added cores at high utilization, with the profiler blaming a trivial write. The fix is layout, not logic: pad a hot variable onto its own line, or give each core a private padded cell and aggregate only on read — the striped-counter pattern in Zaris's own hot path. Remember that the cache line, not the variable, is the unit the hardware contends over, and a surprising amount of "it won't scale" turns out to be two cores fighting over a line they never meant to share.