FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

CPU Cache Alignment & NUMA Nodes

L1/L2/L3 cache lines, false sharing, cache coherency protocols, and NUMA memory affinity.

Freshness: current•16 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Eliminate false sharing in multi-threaded data structures
  • ✓Enforce NUMA memory affinity for high-performance workloads
Full Technical Reference Document

Mental model

CPUs never load single isolated bytes straight out of main memory: hardware transfers aligned 64-byte Cache Lines across private L1/L2 and shared L3 caches governed by strict MESI / MOESI coherency protocols, while multi-socket AI/DB servers split physical RAM controllers across distinct NUMA (Non-Uniform Memory Access) nodes. Packing two cores' hot counters onto one shared 64-byte line triggers ping-pong False Sharing stalls, just as reading across inter-socket UPI/InfinityFabric bridges multiplies memory latency cleanly!

Core loads 64B cache line -> L1(1ns)/L2(4ns)
Two cores write same 64B line -> MESI invalidation!
Pad hot atomic fields cleanly via alignas(64)
Check NUMA node local DRAM vs remote socket
Pin CPU cores, RAM & NIC/GPU to matching NUMA node
Conceptual teaching model synthesized from:Linux Kernel Kernel.org Official Architecture & Systems DocumentationSite Reliability Engineering

Learning outcomes

  • Diagnose and abolish False Sharing across concurrent counters, ring-buffer head/tail pointers, and lock arrays using alignas(64) (C/C++) or CachePadded (Rust).
  • Quantify hardware latency cliffs cleanly across L1 (~1 ns), L2 (~4 ns), L3 (~15 ns), local NUMA DRAM (~65 ns), and cross-socket remote NUMA hops (~120–200+ ns).
  • Configure NUMA locality cleanly across multi-socket databases (Postgres/ClickHouse) and PCIe multi-GPU hosts (matching PCIe root NUMA node -> CPU -> DRAM via numactl / TopologyManager).

Theory

Why can adding threads slow down parallel metrics loops by 10x–20x cleanly even with zero locks (using lock-free std::atomic counters)? Look cleanly inside counters[thread_id]: when long counters[8] packs eight 8-byte integers adjacently cleanly inside a single 64-byte hardware cache line, Core 0 incrementing counters[0] forces the MESI hardware coherency controller to invalidate that entire 64-byte cache line cleanly inside Core 1's L1 cache, forcing Core 1 to stall fetching the line across L3/DRAM just to write counters[1]!

Memory & Coherency OptimizationHardware Mechanism FixedTypical Speedup GainMemory Cost / Caution
64-Byte Cache-Line Padding (alignas(64))Isolates hot writable fields (ring.head vs ring.tail, worker stats) onto disjoint L1 cache lines5x–20x multi-core atomic scaling jump cleanly!Slight per-struct RAM padding (64 B per slot cleanly)
Struct-of-Arrays (SoA) vs Array-of-Structs (AoS)Keeps contiguous hot loop vector/score floats packed tightly cleanly inside sequential L1 linesEliminates hardware prefetch waste skipping cold fieldsSlightly separates related entity fields across parallel arrays cleanly
NUMA Affinity (numactl --cpunodebind --membind)Guarantees process threads allocate RAM pages strictly on their physical CPU socket's DRAM bankAvoids remote UPI/cross-socket latency drops & bandwidth contention cleanly (30–50% boost on DBs!)Over-filling Node 0 RAM causes local NUMA zone reclaim OOM cleanly even while Node 1 sits idle!
Interleave Mode (numactl --interleave=all)Spreads giant read-only shared page tables/caches cleanly round-robin across all sockets cleanlyPrevents single-socket memory channel congestion on giant global Postgres shared_buffers cleanlyTrades slight average RTT cleanly for balanced multi-socket bandwidth cleanly

Crucially inside multi-GPU inference servers, match GPU PCIe Root Complex -> NUMA Node Affinity (nvidia-smi topo -m!): running vLLM CPU tokenizer/pre-fetch threads on NUMA Socket 0 while DMA-ing pinned memory cleanly to a GPU wired physically to Socket 1 forces every Host-to-Device transfer across inter-socket links!

c
#include <stdatomic.h>
#include <stdalign.h>
#include <stdint.h>
​
/* Anti-pattern: head & tail sit side-by-side inside SAME 64-byte cache line -> False Sharing!
* Clean fix: alignas(64) places producer write pointer & consumer read pointer on separate cache lines */
struct SpscRingPointers {
alignas(64) atomic_size_t write_head; /* Written strictly by Producer Core */
alignas(64) atomic_size_t read_tail; /* Written strictly by Consumer Core */
};
​
/* Pin large thread-local counters cleanly onto isolated cache lines */
struct alignas(64) PaddedCoreCounter {
atomic_uint_fast64_t value;
};

Trade-offs

Applying alignas(64) isolation cleanly on hot multi-core shared counters/ring indexes and configuring explicit NUMA node pinning (both in bare-metal numactl and Kubernetes TopologyManager single-numa-node policies) eliminates hidden hardware coherency stalls cleanly and maximizes memory-channel bandwidth for vector HNSW scans and GPU DMA staging. Padding cold rarely written configuration objects wastes L2/L3 cache capacity needlessly cleanly (fitting fewer objects per cache line!), so reserve 64-byte alignment strictly cleanly for variables experiencing frequent cross-core concurrent writes—and watch zone_reclaim_mode carefully cleanly when hard-binding huge caches to one socket cleanly!

Failure modes and misconceptions

  • Assuming Lock-Free std::atomic Automatically Means Scalable: Packing atomics side-by-side in an unpadded array suffers crippling hardware MESI false-sharing cache bounces across cores identical to coarse lock contention cleanly!
  • Blindly Binding Giant Database Caches Strictly (--membind=0) Without Capacity Headroom: Pinning 80 GB Postgres memory tightly onto Socket 0 (64 GB local RAM) triggers kernel OOMKills cleanly on Socket 0 cleanly even cleanly while Socket 1 sits 90% empty!
  • Ignoring Hardware Prefetch / Pointer-Chasing Cache Misses: Linked-list node jumping across scattered heap addresses stalls CPU execution waiting ~65ns per pointer cleanly (prefers cache-friendly dense flat vectors / arenas).
  • Ignoring GPU-CPU NUMA Alignment (nvidia-smi topo -m): Running PyTorch DataLoader / vLLM tokenizer workers cleanly on remote sockets cuts PCIe DMA throughput substantially cleanly.

Decision scenario

A dual-socket C++ vector search / ring-buffer telemetry aggregator degrades horribly cleanly past 4 worker threads, with perf c2c highlighting intense HITM (Hit Modified) L1 cache bounces across producer/consumer ring indices and thread counters, while GPU H2D transfers hit cross-socket bottlenecks! Pad ring write_head / read_tail and worker counters cleanly with alignas(64), convert sparse linked nodes into contiguous SoA flat slabs, and bind each worker + GPU pod cleanly cleanly via NUMA Socket affinity matching PCIe root topology (numactl / TopologyManager) cleanly!

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next