Skip to content

RabbitMQ: run the event loop on its own thread instead of spinning (up to −96% CPU) - #130767

Closed
comino wants to merge 7 commits into
ClickHouse:masterfrom
comino:rabbitmq-event-loop-thread
Closed

comino wants to merge 7 commits into
ClickHouse:masterfrom
comino:rabbitmq-event-loop-thread

Conversation

@comino

@comino comino commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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):

  • Performance Improvement

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

RabbitMQ tables 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 RabbitMQ table streams to a view, its event loop spins on epoll for 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 in RabbitMQHandler::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.sh below 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 BackgroundSchedulePool task that calls uv_run(UV_RUN_NOWAIT) and yield() until the round ends. While the connection is open uv_run never returns 0, so the task never sleeps.

Fix. RabbitMQHandler 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 (acks, channel changes, reconnect, heartbeat) to it and waits; otherwise run() 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 a SELECT reads. 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):

rabbitmq-event-loop-cpu
scenario #124655 this PR change
360 msg/s, block 1000, flush 5 s 0.98 cores 0.04 cores −96 %
10k msg/s 1.08 cores 0.19 cores −82 %
drain a 1M backlog, server CPU per message 30.4 µs 11.0 µs −64 %
p99 latency at 360 / 10k msg/s 2.75 s / 1.00 s 2.75 s / 1.00 s same

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)
scenario metric #124655 this PR
idle server CPU, cores 0.06–0.10 0.05–0.05
360 msg/s server CPU, cores 0.56–0.99 0.03–0.09
360 msg/s broker µs / message 105–482 130–550
10k msg/s server CPU, cores 1.07–1.09 0.16–0.19
10k msg/s broker µs / message 38.8–47.4 40.4–49.9
drain server µs / message 27.6–35.0 10.5–12.4
drain throughput, msg/s 34.0k–40.2k 40.6k–49.6k
drain broker µs / message 26.6–33.1 22.2–27.1

Behaviour changes:

  • The loop keeps running while a channel is replaced; a delivery of the old channel still in flight is dropped and redelivered by the broker (_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.
  • A SELECT that starts while the table shuts down throws ABORTED instead of restarting the loop.
  • Each streaming table now uses one thread from the global pool while it streams, instead of a slot of 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 in KeeperHandlingConsumer. 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 in test_shutdown.py, skipped on master for a known shutdown race. The new test_rabbitmq_trickle_does_not_spin_event_loop fails on master: the server used 989 CPU ticks while consuming 50 messages over 10 s, against 233 idle (bound: 300 above idle).
  • RabbitMQ gtests (13 tests: handler start/stop, posting and inline execution, idle loop CPU, channel replacement, reconnect after the thread died): 10 runs in a row under TSan, no report.
  • Each fix was reverted on its own and its test failed: the replacement not waking a parked delivery, a delivery of the old channel being queued after the wait, the stop request surviving stopLoop().
  • Style check and clang-tidy: no findings in the changed files.
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 server pinned with taskset to 8 P-cores. Each run starts a fresh server with a RabbitMQ table (rabbitmq_num_consumers = 1) and a materialized view into MergeTree, then samples /proc/<pid>/stat every 2 s; CPU is utime + stime of the server process over the steady window. Both binaries are amd_binary builds (the CI Build (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.

scenario load settings
idle no messages, 90 s defaults
360 msg/s 185 B rows, 120 s rabbitmq_max_block_size = 1000, rabbitmq_flush_interval_ms = 5000
10k msg/s 300 B rows, 120 s defaults
drain 1M messages of 300 B queued first, then the view is created defaults
repro.sh
#!/bin/sh
# One-minute repro: a RabbitMQ table with a view and 1 msg/s keeps a core busy. Needs only Docker.
# Usage: sh repro.sh [clickhouse image]   (default clickhouse/clickhouse-server:latest)
set -eu
IMG=${1:-clickhouse/clickhouse-server:latest}
docker network create rq-repro >/dev/null
trap 'docker rm -f rq-rmq rq-ch rq-pub >/dev/null 2>&1; docker network rm rq-repro >/dev/null 2>&1' EXIT
docker run -d --name rq-rmq --network rq-repro -e RABBITMQ_DEFAULT_USER=ch -e RABBITMQ_DEFAULT_PASS=ch rabbitmq:4 >/dev/null
docker run -d --name rq-ch --network rq-repro -e CLICKHOUSE_SKIP_USER_SETUP=1 ${CH_DOCKER_ARGS:-} "$IMG" >/dev/null
q() { docker exec rq-ch clickhouse-client -q "$1"; }
for i in $(seq 120); do docker exec rq-rmq rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1 && q "SELECT 1" >/dev/null 2>&1 && break; sleep 1; done
q "SELECT 1" >/dev/null || { docker logs rq-ch 2>&1 | tail -20; exit 1; }
q "CREATE TABLE q (x UInt64) ENGINE = RabbitMQ SETTINGS rabbitmq_host_port = 'rq-rmq:5672', rabbitmq_username = 'ch', rabbitmq_password = 'ch', rabbitmq_exchange_name = 'e', rabbitmq_format = 'JSONEachRow'"
q "CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY x"
q "CREATE MATERIALIZED VIEW mv TO t AS SELECT x FROM q"
q "SELECT version()"
cpu() { docker exec rq-ch sh -c 'awk "{print \$14+\$15}" /proc/$(pidof clickhouse-server || pidof clickhouse)/stat'; }
sleep 10; c0=$(cpu); sleep 30; c1=$(cpu)
echo "idle, 30 s:       $(( (c1 - c0) / 30 ))% of one core"
docker run -d --name rq-pub --network rq-repro python:3.12-alpine sh -c 'pip install -q pika && sleep infinity' >/dev/null
until docker exec rq-pub python -c 'import pika' 2>/dev/null; do sleep 1; done
c0=$(cpu)
# Publish from a separate container, so that only the server's consuming side is measured.
docker exec -i rq-pub python - <<'PY'
import pika, time
c = pika.BlockingConnection(pika.ConnectionParameters("rq-rmq", credentials=pika.PlainCredentials("ch", "ch")))
ch = c.channel()
for i in range(30):
    ch.basic_publish("e", "", b'{"x": %d}' % i)
    time.sleep(1)
PY
c1=$(cpu)
echo "1 msg/s, 30 s:    $(( (c1 - c0) / 30 ))% of one core"
echo "rows in t: $(q 'SELECT count() FROM t')"

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 comino changed the title RabbitMQ: run the event loop on its own thread instead of spinning RabbitMQ: run the event loop on its own thread instead of spinning (−94% CPU) Nov 11, 2026
@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 11, 2026
@comino
comino force-pushed the rabbitmq-event-loop-thread branch from 18a486f to 3355c97 Compare November 12, 2026 09:24
@comino comino changed the title RabbitMQ: run the event loop on its own thread instead of spinning (−94% CPU) RabbitMQ: run the event loop on its own thread instead of spinning Nov 12, 2026
@comino
comino force-pushed the rabbitmq-event-loop-thread branch 2 times, most recently from a01d1dc to 58ca3fb Compare November 12, 2026 23:20
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
comino force-pushed the rabbitmq-event-loop-thread branch from 58ca3fb to 120ca05 Compare November 13, 2026 00:01
@comino comino changed the title RabbitMQ: run the event loop on its own thread instead of spinning RabbitMQ: run the event loop on its own thread instead of spinning (up to −96% CPU) Nov 13, 2026
@comino

comino commented Nov 13, 2026

Copy link
Copy Markdown
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.

@comino comino closed this Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Using RabbitMQ Engine, CPU load is very high

1 participant