Skip to content

Optimize MemoryTracker layout (improves performance of it ~25%) - #103464

Merged
azat merged 3 commits into
ClickHouse:masterfrom
azat:memory-tracker-opt
Apr 24, 2026
Merged

azat merged 3 commits into
ClickHouse:masterfrom
azat:memory-tracker-opt

Conversation

@azat

@azat azat commented Apr 23, 2026

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Optimize MemoryTracker layout (improves performance of it ~25%)

Results
# tests/performance/group_by_multiple_strings.xml
$ clickhouse-benchmark -i 100 -q "select key1_8, key2_8, sum(value) from test_group_by_strings group by key1_8, key2_8 format Null settings max_threads = 32, query_profiler_cpu_time_period_ns=0, query_profiler_real_time_period_ns=0, memory_profiler_step=0, memory_profiler_sample_probability=0, max_untracked_memory='0'"

# before
Queries executed: 97 (97%).

localhost:9000, queries: 24, QPS: 23.728, RPS: 71183368.874, MiB/s: 2036.573, result RPS: 0.000, result MiB/s: 0.000.

0%              0.038 sec.
10%             0.039 sec.
20%             0.041 sec.
30%             0.041 sec.
40%             0.041 sec.
50%             0.042 sec.
60%             0.042 sec.
70%             0.042 sec.
80%             0.042 sec.
90%             0.043 sec.
95%             0.043 sec.
99%             0.043 sec.
99.9%           0.043 sec.
99.99%          0.043 sec.

# after
Queries executed: 100 (100%).

localhost:9000, queries: 100, QPS: 27.094, RPS: 81282582.316, MiB/s: 2325.513, result RPS: 0.000, result MiB/s: 0.000.

0%              0.032 sec.
10%             0.033 sec.
20%             0.034 sec.
30%             0.034 sec.
40%             0.034 sec.
50%             0.035 sec.
60%             0.035 sec.
70%             0.036 sec.
80%             0.036 sec.
90%             0.036 sec.
95%             0.037 sec.
99%             0.039 sec.
99.9%           0.041 sec.
99.99%          0.041 sec.

azat and others added 3 commits April 23, 2026 21:19
Group fields into three anonymous nested structs aligned to
`DB::CH_CACHE_LINE_SIZE` by access pattern:

  - Hot writes (`amount`, `peak`, `rss`) — updated on every alloc/free
    flush.
  - Read-mostly (`soft_limit`, `hard_limit`, `profiler_limit`, `parent`,
    `metric`, `description_ptr`) — read on every alloc to enforce caps and
    walk the tracker chain, but written only at construction or on rare
    config changes.
  - Cold configuration / sampling parameters.

Previously all fields packed contiguously, so a single cache line held
both `amount` (written on every flush) and the limits (read on every
alloc). Concurrent flushes from many threads invalidated the limit cache
line on every other core, forcing repeated reloads even though those
fields were never written. Splitting onto separate cache lines eliminates
this false sharing on shared trackers (`total_memory_tracker`, hot query
trackers).

`static_assert` on `MemoryTracker` alignment guards against future
reordering that would silently undo the separation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Merge the previously-separate hot-write group (`amount`, `peak`, `rss`)
and read-mostly group (`soft_limit`, `hard_limit`, `profiler_limit`,
`parent`, `metric`) into one anonymous struct that occupies exactly
64 bytes — one cache line. `description_ptr` is demoted to the cold
group since it is read only on logging paths, not per allocation.

Rationale: every field on the alloc/free path now lands on a single
cache line, so each allocation needs at most one line in flight. On
writer cores the limits/parent/metric come along "for free" with the
fetch needed to write `amount`. Across multiple writer cores the line
bounces no more than the prior amount-only line did. The trade-off is
that reader-only cores re-fetch the line whenever an allocator writes,
but allocations dominate over pure reads in practice.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6bce0cc]

Summary: ❌

job_name test_name status info comment
Unit tests (asan_ubsan, function_prop_fuzzer) FAIL
Unit tests (msan, function_prop_fuzzer) FAIL
Stress test (arm_msan) FAIL
Logical error: Port is already connected, (header: [A]) (STID: 0996-3f42) FAIL cidb

AI Review

Summary

This PR reorganizes MemoryTracker field layout in src/Common/MemoryTracker.h to improve cache locality on the allocation path. I did not find correctness, safety, or compatibility issues in the patch, and the change is acceptable as-is.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.20% 76.20% +0.00%

Changed lines: N/A (no coverable changed lines) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Apr 24, 2026
@azat
azat enabled auto-merge April 24, 2026 11:34
@azat
azat added this pull request to the merge queue Apr 24, 2026
Merged via the queue into ClickHouse:master with commit e93129b Apr 24, 2026
160 of 164 checks passed
@azat
azat deleted the memory-tracker-opt branch April 24, 2026 11:59
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 24, 2026
struct
{
/// Hot writes: updated on every alloc/free flush.
alignas(DB::CH_CACHE_LINE_SIZE) std::atomic<Int64> amount {0};

@monoid monoid Apr 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A cache coherence size can be larger than a cache line size. Other project uses 128 bytes on x86_64, for example.

@azat azat Apr 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is interesting, but I doubt that it will make any difference, since here we have cold and hot part, hot fits into 64 bytes and cold accessed rarely

Also if we will change it, we need to do some benchmarks, AFAICS it can be helpful for Intel, but not sure about AMD. Though we do not use it for small frequent structures, and if it will help for some CPUs it can be OK to do this unconditionally for amd64.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've also tested this changes on Intel XEON, and I don't see the difference - https://pastila.nl/?0012525f/220080b545e4afff7e27c25307341e69#gr1F9PIgEX0ADOBhsmMxFg==GCM

Neither for 64 nor 128 alignment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I've tried to find a reliable source for my original statement, and it seems to be more complicated: the cache coherence granule is still 64 bytes, not 128, but Intel's spatial prefetcher may load 128 bytes into cache, inducing a false sharing of 128 bytes.

https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107

It might be just access-pattern dependent.

@monoid monoid May 2, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is MSR setting called "Adjacent Cache Line Prefetcher Disable" or "L2 Adjacent Cache Line Prefetcher Disable" that controls this behavior (see Intel SDM).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants