Skip to content

RabbitMQ: block in the poller instead of spinning (up to −96% CPU) - #131355

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
comino:rabbitmq-blocking-loop-wait-master
Nov 17, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
comino:rabbitmq-blocking-loop-wait-master

Conversation

@comino

@comino comino commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #53401. Related: #50692, #130767

Changelog category (leave one):

  • Performance Improvement

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

A RabbitMQ table that streams to materialized views no longer keeps a CPU core busy while it waits for messages.

Description

Problem. Every RabbitMQ table that streams to a view burns about one CPU core per server while it waits for messages, no matter how few arrive. Reported since 2021: #16263, #24339, #48103, #62525, #53401, #50692.

Cause. The looping task calls uv_run(UV_RUN_NOWAIT) for the whole streaming round. With the connection open there is always an active handle, so it never waits and polls epoll in a tight loop.

Fix. Block in uv_run(UV_RUN_ONCE) instead, with a repeating 10 ms timer so that the task still sees a stop request. Socket events wake it at once, so deliveries are not delayed. Nothing else changes; the timer only runs inside startLoop(). Cost: stopping the loop takes up to 10 ms more, and a waiting round wakes 100 times per second.

Result (master vs this PR, median of 3 runs each, all runs kept):

rabbitmq-event-loop-cpu (2)
scenario master this PR change
360 msg/s 0.99 cores 0.04 cores −96 %
10k msg/s 1.06 cores 0.19 cores −82 %
drain a 1M backlog, CPU per message 23.5 µs 11.7 µs −50 %

Throughput and p99 latency are unchanged; no row was lost or duplicated.

Alternative. #130767 moves the loop to a dedicated thread like NATSHandler (+992/−439, depends on #124655). In the same benchmark it saves the same CPU. It drains a large backlog with small blocks about 2 s per million messages faster, because it does not stop the loop per block; this PR is still faster than master there (1M messages, 1000-row blocks: 11.2 s vs 13.8 s). This PR is the smaller change; #130767 is closed and kept for reference.

Tests. test_storage_rabbitmq passes. The new test_rabbitmq_trickle_does_not_spin_event_loop fails without the fix (985 CPU ticks in 10 s while consuming against 222 idle). The new gtest RabbitMQHandler.LoopingTaskBlocksAndStops checks that the loop blocks, stops on request and leaves no active handle; 10 runs under TSan, no report.

Benchmark setup

One machine, shared with other jobs: RabbitMQ 4.1 on 2 cores, a paced publisher with confirms on 2 others, clickhouse server pinned to 8 cores; a fresh server per run with a RabbitMQ table and a materialized view into MergeTree. CPU is utime + stime of the server process. 360 msg/s uses rabbitmq_max_block_size = 1000 and rabbitmq_flush_interval_ms = 5000; the others use defaults. On a quiet host the broker's CPU per message rose with either fix; with one spare core kept busy it did not, which points to idle cores entering deeper power states.


Workflow [PR]
Sync PR [sync-upstream/pr/131355]

Version info

  • Merged into: 26.11.1.2654-master (included in 26.11 and later)

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Ok, let's try...

@comino
comino marked this pull request as ready for review November 13, 2026 15:59
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1bdec60]

Summary: ✅


AI Review

Summary

The PR replaces busy polling in RabbitMQHandler::startLoop with UV_RUN_ONCE and uses uv_async_t to wake the loop immediately when stopping. The previous per-block stop-delay finding is addressed in the current code. No remaining actionable findings.

Missing context / blind spots
  • ⚠️ Local validation was limited to a standalone scheduling/lifecycle check using system libuv 1.43.0: 100 start/stop cycles passed, median stop latency was 0.017 ms, and loop-thread CPU was 1.5 ms versus 307 ms with busy polling. The supplied ingestion benchmarks predate the async-wakeup revision; its end-to-end throughput with rabbitmq_max_block_size = 100 remains unmeasured. The previous finding concerned timer-induced stop latency, which the current code and focused check address.
Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1bdec6095 with master aed311f51 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

9 object files changed (-30.95 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/RabbitMQ/StorageRabbitMQ.cpp.o 1.00 MiB 1008.60 KiB -17.66 KiB (-1.72%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

12 translation units recompiled, 42 s compile time in total, 12 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +2.9 s (+7%) in total before that adjustment.

Job report

@clickhouse-gh clickhouse-gh Bot added comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). external Author is not a member of the ClickHouse organization labels Nov 13, 2026
alexey-milovidov and others added 2 commits November 17, 2026 03:19
`StorageRabbitMQ::streamToViews` stops the looping task after every block and
waits for it, so the 10 ms wake timer added a delay of up to 10 ms per block.
Replace the timer with an async handle: it is referenced only while
`startLoop` runs (so `UV_RUN_ONCE` blocks in the poller), and `stopLoop`
signals it, so the task sees the stop request immediately. Outside
`startLoop` the handle is unreferenced, so the non-blocking and blocking
loops still become idle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=131355&sha=fe83f615007170f20daeebfc03aef2acadb457bf&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%203%2F8%29 (limit_by_misc #3 +32% and limit_by_in_pk_order #1 +16% on arm_release) and provide a fix in a separate PR. If the fix is already in progress, link it here. This PR only changes the RabbitMQ event loop, so it cannot affect LIMIT BY.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the limit_by_misc #3 / limit_by_in_pk_order #1 arm_release slowdown. I measured the same limit_by_misc #3 arm-only red on another unrelated PR last week: LimitByTransform::consumeImpl had byte-identical machine code in both binaries and only its address changed, so this looks like code placement on arm, not this PR. No fix is in progress yet; I'll follow up here with a PR (or my findings) shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #132328.

Both rows spend the extra time in LimitByTransform::consumeImpl for the keys64 method, whose machine code is identical in both binaries (only its address moved by 512 bytes). With 100K keys every lookup misses the cache, so the speed of the loop depends on how many misses the core overlaps, and on ARM that changes with code placement. #132328 prefetches the hash table cells of the rows ahead once the table outgrows L2, as GROUP BY and the hash join probe already do. On x86, limit_by_misc #3 runs at 0.60x and limit_by_in_pk_order #1 at 0.66x of master; ARM is measured only by the PR's own CI.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai. The arm_release LIMIT BY slowdown has nothing to do with this PR's RabbitMQ change and is being handled in #132328. CI on the current head (1bdec609) is green, the PR is approved and has no unresolved threads, so nothing more is needed here.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 17, 2026
Merged via the queue into ClickHouse:master with commit d984987 Nov 17, 2026
193 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 17, 2026
@comino
comino deleted the rabbitmq-blocking-loop-wait-master branch November 18, 2026 21:57
@comino

comino commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for this one! 🎉 We rolled it to production today: 3 replicas, 2 RabbitMQ tables (JSONEachRow, stream error mode, ~63 msg/s) feeding 6 MVs, RabbitMQ 4.3.6 quorum queues. 26.8.36.3 → master 26.12.1.114, CPU from /proc thread stats over 2 min per replica.

before/after

Server 4.79 → 1.32 cores (−72 %); the RabbitMQ pool 3.89 → 0.33 (−92 %). Ingest unchanged.

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

Labels

can be tested Allows running workflows for external contributors comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). external Author is not a member of the ClickHouse organization 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.

Using RabbitMQ Engine, CPU load is very high

4 participants