Skip to content

Reuse RabbitMQ producer connections and channels across INSERT queries - #127611

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
davimi:rabbitmq-reuse-producer-connection
Nov 18, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
davimi:rabbitmq-reuse-producer-connection

Conversation

@davimi

@davimi davimi commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Every INSERT into a RabbitMQ table created a new RabbitMQProducer, which opened its own connection and channel synchronously on the inserting thread and closed both at the end. Every insert paid a full AMQP handshake cost, even when it wrote no rows. No rows may be a common case for a materialized view with a filter: it fires on every insert into its source table and pays the full cost each time.
The issue also describes the 200 ms polling sleep in RabbitMQConnection::connectImpl. That is not addressed here and it can be fixed separately.

Related: #122943

Changes

  • New table setting rabbitmq_max_idle_producer_connections, default 0 (the previous behavior). When set, the table keeps up to that many idle connections, each with an open confirm-mode channel, for subsequent inserts. It does not limit concurrency: each running insert borrows its own connection, and connections returned beyond the limit are closed.
  • The connection, the channel and all per-channel state (delivery tags, unconfirmed messages, republish queue, channel callbacks) move from RabbitMQProducer into a new RabbitMQPublisher. The channel callbacks previously captured the producer, so they would have outlived it on a reused channel. Most of RabbitMQPublisher.cpp is code moved from RabbitMQProducer.cpp. The producer now only borrows a publisher and passes it messages.
  • New RabbitMQPublisherPool, one per table:
    • A publisher goes back to the pool only after all its messages are confirmed and its channel is still usable. In every other case it is closed.
    • On borrow, one event loop tick processes anything the broker sent meanwhile, such as Connection.Close, then the connection and channel state is checked.
    • AMQP-CPP's libuv handler accepts the negotiated heartbeat but never sends heartbeats, so the broker closes a silent connection after the heartbeat timeout. Idle publishers are therefore discarded once they have been idle for half the negotiated interval. RabbitMQHandler::onNegotiate now records that interval.
  • RabbitMQPublisher::connect waits for the channel to become ready, bounded by BLOCKING_LOOP_TIMEOUT_MS. Before, the producing task waited for it. Without this, an insert without rows finished before onReady fired, so its publisher was never reusable.
  • StorageRabbitMQ::shutdown closes the idle connections, also when streaming to views is disabled.

Results

Local run: native macOS build, rabbitmq:4-management-alpine in Docker, the reproduction from the issue. Ten inserts into the source table (nine without rows, the last with 100 rows), view_duration_ms of each materialized view:

  • rabbitmq_max_idle_producer_connections = 0: 1280, 1232, 1232, 1228, 1235, 1250, 1227, 1235, 1230, 1244 ms
  • rabbitmq_max_idle_producer_connections = 1: 1229, 0, 0, 0, 1, 7, 1, 1, 0, 19 ms
    This shows that only the first insert is incurring the connection setup costs. Subsequent inserts take less time.

Tests

  • New integration test test_rabbitmq_insert_reuses_producer_connection, using a dedicated vhost:
    • sequential inserts keep the same connection and channel;
    • an insert after rabbitmqctl close_all_connections still succeeds and all messages arrive;
    • DROP TABLE leaves no connections behind.
  • test_rabbitmq_many_inserts now sets the setting to 4, so its 10 concurrent inserters exercise concurrent borrow and release, and the closing of connections returned beyond the limit.

Caveats

  • With the setting at 0, the only behavior difference is the wait for the channel in connect. If the channel never opens, the insert now fails after the timeout instead of waiting in the producing task.
  • If the broker disables heartbeats, idle connections are never expired by age. A connection silently dropped by a middlebox is then only detected when publishing fails.
  • For consistent_hash exchanges, the routing key is the delivery tag. On a reused channel it keeps counting across inserts instead of restarting at 0.

Changelog category

  • Performance Improvement

Changelog entry:

Add the RabbitMQ table setting rabbitmq_max_idle_producer_connections, which keeps idle connections with their channels open and reuses them across INSERT queries. This removes the connection setup from every insert, which is especially costly for materialized views that fire often, including when they write no rows. The default 0 keeps the previous behavior.


🤖 Generated with Claude Code. Opus 5.5 xhigh effort.


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

Version info

  • Merged into: 26.11.1.2693-master (included in 26.11 and later)
  • Backported to: 26.9.39.4, 26.8.47.2

@clickhouse-gh clickhouse-gh Bot added the comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). label Oct 23, 2026
@nickitat nickitat added the can be tested Allows running workflows for external contributors label Oct 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [60380c3]

Summary: ✅


AI Review

Summary

This PR adds optional reuse of RabbitMQ publisher connections and channels across INSERT queries through rabbitmq_max_idle_producer_connections, with idle cleanup and shutdown handling. Reviewed head 60380c3d23ca313a09ca91a6ff1d4fcd6be0159f, the full diff, surrounding code, AMQP-CPP callback behavior, and all prior discussion. No actionable findings remain; the previous cleanup and liveness concerns are addressed. The description supplies before/after measurements supporting the performance claim.

Missing context / blind spots
  • ⚠️ RabbitMQ integration jobs are pending in the current CI workflow. No local ClickHouse binary is available, so runtime validation relies on CI executing test_rabbitmq_insert_reuses_producer_connection and test_rabbitmq_many_inserts. The report helper's green summary includes jobs without results and does not establish that these tests passed.
Final Verdict

Status: ✅ Approve

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

clickhouse-gh Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 60380c3d2 with master 81c9f0701 (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

6 object files changed (+210.87 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/RabbitMQ/RabbitMQPublisher.cpp.o new 241.15 KiB +241.15 KiB
src/CMakeFiles/dbms.dir/Storages/RabbitMQ/RabbitMQProducer.cpp.o 268.60 KiB 118.32 KiB -150.28 KiB (-55.95%)
src/CMakeFiles/dbms.dir/Storages/RabbitMQ/RabbitMQPublisherPool.cpp.o new 101.57 KiB +101.57 KiB

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

15 translation units recompiled, 47 s compile time in total, 13 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Oct 24, 2026
@antaljanosbenjamin antaljanosbenjamin self-assigned this Nov 2, 2026

@antaljanosbenjamin antaljanosbenjamin 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.

Apart from this small comment, the PR looks pretty good!

@davimi

davimi commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

@antaljanosbenjamin Is there anything else for me to do? I see that there are some CI failures but I can't access them.

@antaljanosbenjamin

Copy link
Copy Markdown
Member

I think the failures are not related, will check them later (I am out of office these days, but will try to merge it).

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master into the branch (no conflicts; the RabbitMQ translation units build). The previous CI failures are unrelated to this PR: 05324_adaptive_aggregator_disable_thaw was fixed on master by #128084, which this merge pulls in, and the Upgrade check (amd_release) failure was an Unknown job error in the job infrastructure. Both open review threads (periodic cleanup of idle publishers and liveness check with isReusable) are addressed in the code: see RabbitMQPublisherPool::cleanupIdlePublishers and publisher_cleanup_task in StorageRabbitMQ.

@clickhouse-gh clickhouse-gh Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review approves this commit, see the AI Review comment.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 17, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 17, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 515a8d9 Nov 18, 2026
192 of 193 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
PedroTadim added a commit to groeneai/ClickHouse that referenced this pull request Nov 18, 2026
…l-on-table-shutdown

Resolve the conflict with ClickHouse#127611, which moved the producer loop into
`RabbitMQPublisher::publishStep` and pools publishers between inserts. The
loop on master still stops silently on `shutdown_called`, so the shutdown
check is kept as the first step of each iteration: it closes `payloads` and
throws `ABORTED`. On that path `can_reuse_publisher` stays false, so
`finishImpl` disconnects the publisher instead of returning a channel with
unconfirmed messages to the pool. `CANNOT_CONNECT_RABBITMQ` is no longer used
in this file after the merge and is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Nov 19, 2026
…n-delivery-tag

Master moved the publisher confirms handling (`removeRecord`, `delivery_record`, `returned`)
from `RabbitMQProducer` into the new `RabbitMQPublisher` class
(#127611). Resolve the conflict by taking master's
`RabbitMQProducer.cpp`, porting the fix for unknown delivery tags to
`RabbitMQPublisher::removeRecord`, moving the test friend declaration to `RabbitMQPublisher`,
and renaming the unit test to `gtest_rabbitmq_publisher.cpp` to drive `RabbitMQPublisher`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 24, 2026
antaljanosbenjamin added a commit that referenced this pull request Nov 24, 2026
Cherry pick #127611 to 26.8: Reuse RabbitMQ producer connections and channels across INSERT queries
antaljanosbenjamin added a commit that referenced this pull request Nov 24, 2026
Cherry pick #127611 to 26.9: Reuse RabbitMQ producer connections and channels across INSERT queries
antaljanosbenjamin added a commit that referenced this pull request Nov 24, 2026
Cherry pick #127611 to 26.10: Reuse RabbitMQ producer connections and channels across INSERT queries
robot-clickhouse added a commit that referenced this pull request Nov 24, 2026
robot-clickhouse added a commit that referenced this pull request Nov 24, 2026
robot-clickhouse added a commit that referenced this pull request Nov 24, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 24, 2026
antaljanosbenjamin added a commit that referenced this pull request Nov 24, 2026
The backport of #127611 moved the publisher confirms state (`delivery_record`,
`returned`, `removeRecord`) from `RabbitMQProducer` to `RabbitMQPublisher`.
The unit test from the backport of #131731 still constructed
`RabbitMQProducer` and used these members, so `unit_tests_dbms` did not
compile in the debug, sanitizer and `arm_darwin` builds.

Test `RabbitMQPublisher` directly, as on master after #131731: the test is
`RabbitMQPublisherTest` in `gtest_rabbitmq_publisher.cpp`, and the `friend`
declaration moves from `RabbitMQProducer` to `RabbitMQPublisher`. The test
cases do not change.

#134083
antaljanosbenjamin added a commit that referenced this pull request Nov 24, 2026
The backport of #127611 moved the publisher confirms state (`delivery_record`,
`returned`, `removeRecord`) from `RabbitMQProducer` to `RabbitMQPublisher`.
The unit test from the backport of #131731 still constructed
`RabbitMQProducer` and used these members, so `unit_tests_dbms` did not
compile in the debug, sanitizer and `arm_darwin` builds.

Test `RabbitMQPublisher` directly, as on master after #131731: the test is
`RabbitMQPublisherTest` in `gtest_rabbitmq_publisher.cpp`, and the `friend`
declaration moves from `RabbitMQProducer` to `RabbitMQPublisher`. The test
cases do not change.

#134084
antaljanosbenjamin added a commit that referenced this pull request Nov 24, 2026
The backport of #127611 moved the publisher confirms state (`delivery_record`,
`returned`, `removeRecord`) from `RabbitMQProducer` to `RabbitMQPublisher`.
The unit test from the backport of #131731 still constructed
`RabbitMQProducer` and used these members, so `unit_tests_dbms` did not
compile in the debug, sanitizer and `arm_darwin` builds.

Test `RabbitMQPublisher` directly, as on master after #131731: the test is
`RabbitMQPublisherTest` in `gtest_rabbitmq_publisher.cpp`, and the `friend`
declaration moves from `RabbitMQProducer` to `RabbitMQPublisher`. The test
cases do not change.

#134085
clickhouse-gh Bot added a commit that referenced this pull request Nov 24, 2026
Backport #127611 to 26.9: Reuse RabbitMQ producer connections and channels across INSERT queries
clickhouse-gh Bot added a commit that referenced this pull request Nov 24, 2026
Backport #127611 to 26.8: Reuse RabbitMQ producer connections and channels across INSERT queries
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants