Repository navigation
Conversation
Without basic.qos the broker pushed every ready message. The delivery callback blocked in a full ConcurrentBoundedQueue while the streaming thread waited for that loop to stop, so consumption and DROP TABLE hung. - Limit unacked deliveries with basic.qos; the received queue no longer blocks. - Ack messages that produce no rows, so they cannot hold prefetch slots. - End a block once the prefetch window is used up and drained. Closes ClickHouse#54775
…left unacked A message a direct SELECT read without acking it held a prefetch slot of the pooled consumer: with rabbitmq_flush_interval_ms = 0 a view's block waited forever for a full window.
The broker requeues them. With the queue now unbounded, every reconnect would otherwise add a prefetch window.
# Conflicts: # src/Storages/RabbitMQ/RabbitMQConsumer.cpp
The prefetch window bounds the deliveries of a channel to num_queues * prefetch_count <= queue_size, so the queue never fills and ClickHouse#125105's wait for space never blocks the loop.
comino
force-pushed
the
rabbitmq-event-loop-thread
branch
from
November 12, 2026 09:24
18a486f to
3355c97
Compare
comino
force-pushed
the
rabbitmq-event-loop-thread
branch
2 times, most recently
from
November 12, 2026 23:20
a01d1dc to
58ca3fb
Compare
waitForMessages checks the received queue and starts waiting while holding the consumer mutex, but deliveries notified the condition variable without it. A notify that fell between the check and the wait was lost, so the reader slept until the next delivery or the end of the flush interval. This delays a full block, a direct SELECT, DROP TABLE and shutdown. Notify under the mutex, also in stop(). Without either lock its unit test fails in nearly every run.
The AMQP event loop was driven by a BackgroundSchedulePool task that spun uv_run(UV_RUN_NOWAIT) + yield for the whole streaming round, burning a core per table while a round waited out its flush interval. It also had to be stopped and restarted around every block, because acks from the streaming thread raced with it. RabbitMQHandler now owns a thread that blocks in uv_run(UV_RUN_DEFAULT) and is woken through a uv_async_t. While it runs, run() posts AMQP-CPP calls (ack, nack, channel open and close, connect, disconnect, heartbeat) to it and waits for the result; otherwise run() executes them inline. Inline execution, loop start and the exiting thread's final drain hold exec_mutex, so the two never overlap. The thread runs across the blocks of a streaming round and stops at its end unless a SELECT still reads, as the loop task did. The loop now keeps running while a channel is replaced, so a delivery of the old channel can still arrive. updateChannel() bumps the channel generation and clears the queue under channel_mutex, and wakes a delivery that waits for space in a full queue; deliveries of the old generation are dropped and redelivered by the broker. Acks now run on the loop thread, so it must not wait for space in the queue: the prefetch window (ClickHouse#124655) keeps the queue from filling. Nothing may unwind through libuv, so the loop thread does not throw on the memory limit. If an exception still escapes, the thread exits, marks the connection broken and run() executes inline until startLoop() replaces the thread. Such a connection may still look usable, so reconnect() closes it at once instead of gracefully: a graceful close ends the channels without an error, and the consumers would keep them. Removed: the looping task, startup_mutex, the iterateLoop() try_lock, deactivateTask/task_mutex, the loop stop in read(), the self-driving driveLoopUntilMessage() in RabbitMQSource (a one-shot REFRESH round now waits on the consumer's condition variable) and the unused unbindExchange().
comino
force-pushed
the
rabbitmq-event-loop-thread
branch
from
November 13, 2026 00:01
58ca3fb to
120ca05
Compare
Contributor
Author
|
Closing in favour of #131355, which removes the same spin with a much smaller change and saves the same CPU in the same benchmark. This dedicated-thread version stays here as a reference: it also frees the message-broker pool worker during a streaming round and drains a large backlog with small blocks somewhat faster. The branch remains available if that approach is wanted later. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes: #53401
Related: #50692
Depends on #124655 and #130854. This branch contains both; review only the last commit, "RabbitMQ: run the event loop on its own thread instead of spinning" (120ca05). I will rebase it once they are merged.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
RabbitMQtables that stream to materialized views no longer keep a CPU core busy while they wait for messages: the event loop now sleeps until the broker sends data.Description
Why this hurts in production. While a
RabbitMQtable streams to a view, its event loop spins onepollfor the whole flush interval, whatever the message rate: at 360 msg/s it uses as much CPU as at 10k msg/s, about one CPU core for the table on every server. On a production cluster (26.8, one table at ~360 msg/s) 80–85 % of the server's CPU samples are inRabbitMQHandler::startLoop → uv_run → uv__io_poll; parsing, the views and merges together are below 2 %. #53401 and #50692 report the same.Try it in one minute on the official image (needs only Docker):
repro.shbelow prints the server's CPU while idle and at 1 msg/s. On 26.10.3.7 it reports 12 % of one core while idle and 100 % at 1 msg/s.Cause. The loop is a
BackgroundSchedulePooltask that callsuv_run(UV_RUN_NOWAIT)andyield()until the round ends. While the connection is openuv_runnever returns 0, so the task never sleeps.Fix.
RabbitMQHandlerowns a thread that blocks inuv_run(UV_RUN_DEFAULT)and is woken through auv_async_t. While it runs,run()posts AMQP-CPP calls (acks, channel changes, reconnect, heartbeat) to it and waits; otherwiserun()executes them inline. One mutex covers inline execution, loop start and the thread's final drain, so inline calls never run while the loop thread does. The thread runs exactly when the loop task ran before: across the blocks of a streaming round, and while aSELECTreads. Acks now run on the loop thread, so it must never wait for space in the internal queue; the prefetch window of #124655 guarantees that, which is why this PR builds on it.Result (#124655 vs this PR, same build type, alternating runs on one machine):
Median of 3 runs per side, all runs kept. The host was shared with other jobs, so the spreads are wide (min–max below); the rows above do not overlap. Idle CPU, drain throughput and the broker's CPU per message moved within the noise of this host (below). No row was duplicated, and the drain runs delivered all 1M rows.
All runs (min–max)
Behaviour changes:
_redelivered = 1). Test:ReplacementDropsDeliveryInFlightOnOldChannel.reconnect()closes the old connection at once instead of gracefully: after the loop thread died from an exception, a graceful close would end the channels without an error and the consumers would keep them. Test:ReconnectAfterLoopThreadDiedFailsChannels.SELECTthat starts while the table shuts down throwsABORTEDinstead of restarting the loop.background_message_broker_schedule_pool.Settings, formats, queue declarations and ack-after-insert are unchanged. No setting switches back to the old loop: the two cannot coexist, and the change is one self-contained commit to revert.
Exceptions. Nothing may unwind through
uv_run(libuv keeps pointers into the frames of a running poll), so the loop thread does not throw on the memory limit, as inKeeperHandlingConsumer. If an exception still escapes, the thread exits as the task did on master, the connection is marked broken, and the next round reconnects.Tests
test_storage_rabbitmq: 91 passed. The 4 skipped are the shutdown tests intest_shutdown.py, skipped on master for a known shutdown race. The newtest_rabbitmq_trickle_does_not_spin_event_loopfails on master: the server used 989 CPU ticks while consuming 50 messages over 10 s, against 233 idle (bound: 300 above idle).stopLoop().Benchmark setup
One machine (Intel i7-14700KF, 28 threads, Linux 6.8), shared with other jobs: RabbitMQ 4.1 pinned to 2 cores, a paced Go publisher with publisher confirms on 2 others,
clickhouse serverpinned withtasksetto 8 P-cores. Each run starts a fresh server with aRabbitMQtable (rabbitmq_num_consumers = 1) and a materialized view intoMergeTree, then samples/proc/<pid>/statevery 2 s; CPU is utime + stime of the server process over the steady window. Both binaries areamd_binarybuilds (the CIBuild (amd_binary)job) of #124655 (3a227d8) and of this branch at 3355c97, run alternately (ABBA), 3 rounds. The final commit differs from 3355c97 only by the memory-exception lock in the loop thread and one condition in the wait for queue space.rabbitmq_max_block_size = 1000,rabbitmq_flush_interval_ms = 5000repro.sh