NewsCrawler.org

It's the Memory Latency, Stupid: Making GROUP BY Faster by Doing More CPU Work

A database process that reports 100% CPU may in fact be spending that time waiting on memory: a modern CPU executes roughly 4-8 instructions per nanosecond, while a single RAM access takes 50-100ns, so the processor could run around 400-800 instructions in the time of one memory access. CPU caches exist to bridge this gap: the L1 cache serves a memory operation in about 1ns, 50-100x faster than RAM, but holds only ~64KB, and even the farther caches max out at a few hundred MB on top-end processors. That is why a good database manipulates data in small chunks to make full use of the caches.

To demonstrate the cost of ignoring this, the author stripped the Pivot engine's GROUP BY down to a naive implementation that keeps one ever-growing HashTable keyed by the group key. Running SELECT count(*), UserID FROM hits GROUP BY UserID on the ClickBench "hits" dataset (99m rows, ~17m unique UserID) produces millions of groups, so nearly every HashTable access is a cold hit that goes to RAM. The test ran on a bare metal CherryServers server (AMD EPYC 9124 Genoa, 16 cores, 128 GB DDR5), with the process pinned to a single core via taskset; a shared AWS/GCP machine was not an option because it does not expose the needed memory counters, and the naive group by cannot use many cores anyway. The query took 3.9 seconds on the first run and 3.6s on the second, when everything was already in the page cache[1] and no disk was involved.

perf stat showed 50.1% of CPU slots stalling on memory (backend_bound_memory) and only 16.1% retiring[2], that is, actually executing micro-ops. The counter ls_dmnd_fills_from_sys.dram_io_near counted 76190837 loads from DRAM, which multiplied by the 64-byte cache line[3] size comes to 4.5GB pulled from DRAM during the query, without prefetching. The proposed fix is radix partitioning[4] in two phases: phase 1 hashes each key and pushes it into one of 4096 partitions, chosen by the top 12 bits of the hash (2**12 = 4096) and stored as a Vec of SlabVecs, a Vec-like structure over memory that is already paged in, and phase 2 walks the partitions one at a time, building a HashMap and aggregating each partition into it.

Read the original pivotlake.ioDiscussion

Sources

Published: First seen: Читать по-русски

Open as a page