Chapter 03 / 10 · Foundations

The machine underneath

The same code, 2,500 times more pages: why the answer depends on caches and layout more than on the sort.

This chapter gives you a cost model for reading memory that is good enough to compare two designs before you build either: which is faster, and by roughly how much. The model has two parts. Where does each piece of data sit, and does the program walk through it in order or jump around?

hitcount’s /top endpoint builds a list of every page and sorts it. For the one blog it was written for, about two thousand pages, that takes well under a millisecond. Now change one variable. A friend who runs a blogging platform asks to use hitcount for all of their blogs: roughly 5 million pages, with a platform-wide “trending” list built the same way. The code and the algorithm are unchanged. The number of pages is 2,500 times larger. Is /top 2,500 times slower, or worse? The answer depends less on the sort than on where the pages live.

A core, its caches and the long walk to main memory

A core works on values in its registers. Everything else is fetched from memory, and memory is arranged as a hierarchy. Closest to each core is the L1 data cache, typically 32 to 48 KB, which answers in about a nanosecond. Behind it is a per-core L2 of around one or two megabytes, then an L3 of tens of megabytes shared by all the cores on the chip. Behind all of that is main memory (DRAM): tens or hundreds of gigabytes, about 100 nanoseconds away.

The caches exist because DRAM latency has improved very little in decades while cores have become much faster. A core running at 3 GHz completes a cycle every third of a nanosecond, and can retire several instructions per cycle. A 100 ns trip to main memory is 300 cycles in which a core that needs the value has nothing useful to do. The caches hold copies of recently used memory, on the bet that a program will soon use the same data again, or data next to it.

bar length on a log scaleL1 cache~1 ns1×Main memory~100 ns100×SSD read~100 µs100,000×Same-region network hop~0.5 ms500,000×Spinning disk seek~10 ms10,000,000×Cross-continent round trip~150 ms150,000,000×relative to an L1 hit
Fig 1 · The latency ladder on a log scale. Each rung is roughly ten to a thousand times the one above

The same ladder continues below memory, into storage and the network. The rounded figures below change a little with each hardware generation; the ratios between them have been stable for a long time, and the ratios are what decisions depend on. The right-hand column says where hitcount touches each rung.

AccessRough costWhere hitcount meets it
L1 cache hit~1 nsthe Views field of a page it touched a moment ago
L2 / L3 hit~4–40 nsa popular page’s struct, touched within the last few thousand requests
Main memory~100 nsa rarely read page’s struct, chased through a pointer
Sequential read from RAM~10 GB/s per corea scan over a flat, contiguous array
SSD random read~100 µsloading the snapshot file at start-up, if it is not in the OS cache
Round trip in one data centre~0.5 msfetchTitle calling the content system
Round trip across a continent~150 msa reader far from the server sending a hit

Two things in this table matter for everything that follows. First, the jump from cache to main memory is about a hundredfold, so a program that misses the cache on every access runs at a hundredth of the speed of one that does not, with exactly the same instructions. Second, the network rows are thousands of times slower than any memory row. Shaving cache misses from a request that also makes a network call is usually wasted effort, a point we return to at the end.

Memory moves in 64-byte lines

Memory does not travel one byte at a time. The unit of transfer between main memory and the caches is the cache line, 64 bytes on most current processors. Read one byte and the hardware fetches the 63 around it. If the program then reads those neighbours, they are already in the cache. On top of that, the core watches the pattern of addresses being read. When it sees a steady walk forwards through memory, a hardware prefetcher starts fetching lines before they are asked for. A sequential scan therefore pays the main-memory latency roughly once and then streams at memory bandwidth.

hitcount’s data does not look like that. pages is a map[string]*Page. The map’s own table is reasonably compact, but each entry holds a pointer to a Page struct that was allocated on the heap when the page was first seen. Pages are first seen in an arbitrary order, interleaved with every other allocation the program makes, so the structs are scattered. To read one page’s Views, the core loads the pointer from the map, then loads from wherever that pointer leads. When the data set is larger than the caches, that second load is usually a miss.

map[string]*Page · each entry points elsewhere in the heapkey · ptrPagekey · ptrPagekey · ptrPagekey · ptrPagekey · ptrPagekey · ptrPagekey · ptrPagekey · ptrPageeach arrow is a likely cache miss · ~100 ns[]Stat · 16-byte records packed side by side64-byte line64-byte line64-byte line64-byte lineone miss brings in four pages · the prefetcher runs ahead
Fig 2 · The same counters, laid out two ways. Pointers send each read somewhere new; a flat slice puts four pages in each cache line

/top then makes it worse. It copies the pointers into a slice and calls sort.Slice, whose comparison function reads list[i].Views and list[j].Views, two more pointer dereferences per comparison, landing in random places. A sort of n items makes about n log₂ n comparisons.

Predict first

With 5 million pages, estimate how long /top takes in the current design. Then estimate it for a design that keeps a separate flat slice of 16-byte records (an int64 view count and a page index) and scans it once, keeping the ten largest in a small heap.

Show the worked answer

Current design. Just visiting every page once to read its count is 5 million likely misses. At about 100 ns each, that is around 0.5 seconds. The sort is worse: 5 million × log₂(5 million) ≈ 5 million × 22 ≈ 110 million comparisons, each touching two scattered structs. Even if the core overlaps several misses at a time, this is several seconds of work for one request, and possibly more than ten.

Flat design. The slice is 5 million × 16 bytes = 80 MB, read front to back. At something like 10 GB/s, streaming it takes about 8 ms. Most records are compared once against the smallest of the current top ten and rejected, which costs a few nanoseconds and overlaps with the memory traffic. Call it 10 to 20 ms in total.

The ratio is somewhere between a hundred and several hundred to one, from layout and algorithm together. Now redo the estimate at 2,000 pages: the whole set is a few hundred kilobytes and stays in L2 or L3 after the first call, so both versions finish in tens of microseconds to a fraction of a millisecond. The difference is real but invisible next to the network time of the request.

One more effect sits behind the word “overlap” in that answer. A modern core can have around ten or more cache misses in flight at once, provided it knows the addresses in advance. Iterating a map and following each entry’s pointer gives it independent addresses to work on, so some misses overlap. Walking a linked list does not: the address of the next node is inside the current node, so each miss must finish before the next can start. Of all layouts, a long linked list traversal is the one that pays the full 100 ns per element.

Seeing the misses instead of guessing them

Estimates like these are worth checking, and the processor will tell you directly. Every modern core keeps hardware counters of cycles, instructions retired, cache misses and mispredicted branches, and on Linux perf stat reads them for any command. Running a benchmark of each /top design over 5 million pages gives output shaped like this (numbers rounded, and yours will differ):

map of pointers + sort.Slice
    21,000,000,000  cycles
     7,300,000,000  instructions        #  0.35  insn per cycle
       200,000,000  cache-misses

flat slice + 10-item heap
        52,000,000  cycles
       118,000,000  instructions        #  2.27  insn per cycle
         1,300,000  cache-misses

The line to read first is instructions per cycle. A core that can retire several instructions per cycle retiring only a third of one is mostly waiting, and the cache-miss count says what for. The flat version not only executes far fewer instructions; it executes them about six times more efficiently, because the data arrives before it is needed. Its 1.3 million misses are close to what streaming 80 MB in 64-byte lines must cost, about 1.25 million lines, which is a good sign that the model in this chapter describes what the hardware is doing.

Low instructions per cycle is the signature of a memory-bound program, and it changes what is worth trying. Reducing the arithmetic in a loop that runs at 0.35 instructions per cycle does almost nothing, because the core was not busy with arithmetic. Reducing the number of distinct cache lines the loop touches is what helps.

Lay the data out the way it is read

The flat slice is fast for one reason: the query reads only view counts, and the layout puts only view counts side by side. That principle reaches further than this one endpoint.

A later version of hitcount keeps an hourly histogram for each page, 24 four-byte counters, so it can draw a chart of the last day. Stored as one array of rows, page after page, each row is 96 bytes. Drawing one page’s chart reads one row: two cache lines, fast. But the platform also wants “views across all pages in the last hour”, which reads one counter from every row. Each of those reads lands in a different cache line, so the query pulls in all 480 MB of histograms to use 20 MB of them. The arithmetic is trivial; the memory traffic is 24 times what it needs to be.

Storing the same data as 24 arrays, one per hour, flips both costs: the cross-page query becomes a sequential scan of one 20 MB array, and the single-page chart becomes 24 scattered reads. Neither layout is correct in general. The right one is the one that matches the query you run most often or most urgently. Analytical databases store data column by column for exactly this reason, and transactional databases store it row by row for the opposite one; the System Design pathway returns to that choice.

Two counters, one cache line

Cache lines also explain a failure that looks impossible from the source code. It shows up when we try to make total cheaper to update from many cores, which the concurrency chapter will make necessary.

The idea is sound: instead of every core incrementing the same counter, give each core its own, and add them up when someone asks for the total. Someone writes var perCore [16]int64. Each core increments only its own element. A benchmark on an 8-core machine shows that this is no faster than a single shared counter, and sometimes slower.

Here is the sequence. Sixteen 8-byte counters occupy 128 bytes, which is two cache lines, eight counters per line. Caches keep copies consistent per line, not per variable. Before a core may write to a line, it must hold that line exclusively, which means every other core’s copy is invalidated. Core 0 writes its counter and takes the line. Core 1 writes its own counter, a different variable in the same line, and must take the line away from core 0. Core 0’s next increment takes it back. The line moves between cores on nearly every increment, each move costing tens of nanoseconds or more, even though no two cores ever touch the same variable. This is false sharing.

The fix is to give each counter its own line:

type paddedCounter struct {
    n int64
    _ [56]byte // fill the rest of the 64-byte line
}
var perCore [16]paddedCounter

The cost is memory: 64 bytes per counter instead of 8. For sixteen counters that is one kilobyte and not worth a second thought. It would be a bad trade for the per-page counters: 5 million pages at 64 bytes is 320 MB instead of 40 MB, to fix contention that only exists on the handful of counters every request touches. So we pad the few hot shared counters and leave the per-page data packed.

Stack, heap and the cost of allocating

Where a value is allocated also decides where it sits. Values that live only during one function call can go on the goroutine’s stack, where allocation is moving a pointer and release is free. Values that outlive the call must go on the heap, where the allocator has to find space and the garbage collector later has to find out that the space is free again. Go decides which is which with escape analysis at compile time: &Page{...} in hit escapes because it is stored in the map; the loop counter in top does not. go build -gcflags=-m prints these decisions.

For hitcount’s ordinary requests, heap allocation is not a problem. Parsing the query string allocates a few hundred bytes per request; at 2,000 requests a second that is well under a megabyte a second. /top at platform scale is different: each call allocates a slice of 5 million pointers, 40 MB, and throws it away. At ten calls a second that is 400 MB a second of allocation, and the garbage collector will have to deal with all of it. The languages chapter prices that. For now, note that an allocation’s cost is paid twice, once when the memory is handed out and again when it is reclaimed.

When not to rearrange data for the cache

At two thousand pages, every byte of hitcount’s state fits comfortably in L2 or L3. The flat layout would save microseconds on a request whose total time is dominated by the network, measured in milliseconds or hundreds of milliseconds. It would also cost something: two structures to keep consistent (the map to find a page by path, the slice to scan), and more work whenever a page is deleted and its slot must be reused or compacted. For the original blog, that complexity buys nothing a reader could notice.

Revisit the layout when three things are true together: the data set has grown past the L3 cache, a request scans much of it, and a profile shows time going to loops that do little arithmetic per element. That is the situation the platform version is in, and it is why the flat slice appears there and not in the original.

Throughout this chapter we treated memory as hitcount’s own: one large array of bytes that the program reads and writes directly. It is not. The next chapter, The operating system’s three lies, looks at what the kernel does between hitcount and the hardware, and at three failures that only make sense once you see it: a slowdown with idle CPU, a silent kill, and a snapshot that vanished in a power cut.