Skip to content

Fix RabbitMQ engine stopping consumption when the backlog exceeds the internal queue - #124655

Open
comino wants to merge 5 commits into
ClickHouse:masterfrom
comino:fix-rabbitmq-consumer-deadlock-54775
Open

comino wants to merge 5 commits into
ClickHouse:masterfrom
comino:fix-rabbitmq-consumer-deadlock-54775

Conversation

@comino

@comino comino commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #54775
Related: #74430
Related: #50692

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes RabbitMQ tables that silently stop consuming, with DROP TABLE hanging until a restart, when inserts fall far behind the broker (about 1 million messages with default settings, 100000 with a small rabbitmq_max_block_size). ClickHouse now limits how many unacknowledged messages RabbitMQ sends at once.

Description

The consumer sets no basic.qos, so RabbitMQ pushes every ready message into a bounded queue of max(100000, block size) entries (block size: rabbitmq_max_block_size, or max_insert_block_size / rabbitmq_num_consumers = 1048449 by default). Once inserts are that far behind, the libuv delivery callback blocks in push() while streamToViews, the only thread that drains the queue, waits for the loop task to return: consumption stops without any error in the log and DROP TABLE hangs in shutdown(). In production this hits as soon as inserts fall behind under load: consumption stops without any error, DROP TABLE hangs, and only a server restart recovers. Because of this we had to build our own ingestion system instead of using the RabbitMQ engine.

Fix:

  1. Non-global basic.qos per subscription, clamp(queue_size / num_queues, 1, 65535) (65535 unless there are several queues). A channel then has at most num_queues * prefetch_count <= queue_size deliveries outstanding, so received never fills and the delivery callback never waits for space.
  2. Ack messages that produce no rows, so they cannot hold prefetch slots forever.
  3. End a block once the channel's prefetch window is used up and nothing is pending, instead of waiting for the flush interval. The window counts messages an earlier reader of the pooled consumer left unacked (a direct SELECT); if they hold all of it, the block acks them, as the next block does on master.

Dependency. With the AMQP-CPP currently pinned, one basic.nack (a failed insert into a view, SYSTEM STOP/CANCEL during a block) makes AMQP-CPP queue every later ack without sending it (#76163). On master that gives duplicates; with a prefetch window the broker stops after 65535 unacked messages and the table stalls until it reconnects. Measured: one failing message, then 70000 messages:

binary AMQP-CPP consumed
master 4fccd7f (pin) 70000 of 70000
this PR 4fccd7f (pin) stops at 65535 (broker: 65535 unacked, 0 acks)
this PR c0049e0 (AMQP-CPP#9) 70000 of 70000

Resolved: master pins AMQP-CPP 5f4c447 (the merge of AMQP-CPP#9) since #130541, merged 2026-11-12.

Behaviour changes:

  • A block ends after at most prefetch_count messages per consumer (65535, or queue_size / num_queues with several queues, documented), so a large rabbitmq_max_block_size can give more, smaller parts. Draining a 300000-message backlog with default settings takes the same time as on master (8.5–8.9 s vs 8.8–8.9 s, 7 parts each, 3 runs each).
  • A direct SELECT without rabbitmq_commit_on_select still leaves what it read unacked, as on master, and a view's next block acks it. Without a view, prefetch_count (up to 65535) such reads use up the window until the connection is re-established.
  • The window makes a pre-existing lost wake-up in waitForMessages likelier: with rabbitmq_flush_interval_ms = 0 a block can sleep until the next delivery or the sanity timeout. Fixed in a follow-up PR.

Tests: five new integration tests pass with the fix at 3a227d8e483 (3 of 3 runs each after merging master with #125105, 10 of 10 before). Four fail on current master; the fifth, a window held entirely by direct SELECTs, fails on ed652fa8d and passes on master, which has no window. Before the merge, the rest of test_storage_rabbitmq passed on a minimal local build, except two tests that need Arrow or the JSON type and failed on master too.

Repro, one minute on the official 26.9 image: https://gist.github.com/comino/349122b3f425d277569c08187289852f

Stacks and design notes

Stacks while stuck (system.stack_trace, official 26.9.12.8, shortened):

loop thread:      pthread_cond_wait <- RabbitMQConsumer::subscribe()::$_1 <- … <- AMQP::DeferredReceiver::process <- uv_run <- RabbitMQHandler::startLoop
streaming thread: mutex::lock <- BackgroundSchedulePoolTaskInfo::deactivate <- StorageRabbitMQ::streamToViews
DROP TABLE:       mutex::lock <- StorageRabbitMQ::shutdown <- InterpreterDropQuery::executeToTableImpl
  • QoS is non-global because global QoS is deprecated and rejected by quorum and stream queues.
  • No new settings and no queue or exchange declaration changes, so existing tables and queues keep working.
  • Side effect: without basic.qos, RabbitMQ caps quorum-queue consumers at 2000 unacked messages; with an explicit prefetch a 20000-message quorum backlog drained in 8 s instead of 56 s (RabbitMQ 4, rabbitmq_flush_interval_ms = 5000).
  • Tests: test_rabbitmq_backlog_larger_than_received_queue, test_rabbitmq_empty_messages_are_acked (waits for the ack in the log), test_rabbitmq_block_ends_when_prefetch_is_used_up, test_rabbitmq_view_acks_messages_a_select_left_unacked, test_rabbitmq_view_acks_a_window_selects_left_unacked.

cc @alexey-milovidov


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

@CLAassistant

CLAassistant commented Oct 8, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@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 Oct 8, 2026
@comino

comino commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Dependency: this PR needs ClickHouse/AMQP-CPP#9 (plus the submodule bump). AMQP-CPP treats basic.nack as synchronous, so after the engine's first multiple nack (SYSTEM CANCEL/STOP, a failed insert into the views) no ack on that channel reaches the broker. On master that shows up as duplicates after a reconnect (#76163). With the prefetch added here, the unacked messages would fill the window after one nack, and the table would stop consuming again. Details and a test: ClickHouse/AMQP-CPP#9 (comment)

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
@comino
comino force-pushed the fix-rabbitmq-consumer-deadlock-54775 branch from 631358b to ed652fa Compare October 14, 2026 14:15
@kssenii kssenii added the can be tested Allows running workflows for external contributors label Oct 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3a227d8]

Summary: ✅


AI Review

Summary

Adds per-subscription prefetch limits to prevent the RabbitMQ delivery callback from blocking on its bounded queue, acknowledges messages producing no rows, and flushes exhausted delivery windows. Both previous inline findings are addressed in the current code. No new inline findings; the documented dependency still blocks merging the current revision.

Findings

❌ Blockers

  • src/Storages/RabbitMQ/RabbitMQConsumer.cpp:307 — Known merge dependency: acknowledgements must keep reaching the broker after a negative acknowledgement. The checkout still pins AMQP-CPP to 4fccd7f84318fe3a022c63a5b621a831c99e3a32. At that revision, BasicNackFrame inherits MethodFrame::synchronous, and ChannelImpl::send queues subsequent frames waiting for a reply that does not exist. After a failed view insert or cancellation sends a multiple negative acknowledgement, later acknowledgements never reach RabbitMQ. The new prefetch limit then stops ingestion when the outstanding window fills. This is already documented by the author, so no duplicate inline comment was posted. Merge the dependency fix and update the ClickHouse submodule pin before merging this PR.
Missing context / blind spots
  • ⚠️ The fetched Praktika report has the targeted integration and integration bug-fix validation jobs pending, without test results. The description supplies local regression results; no local build or integration suite was run during this review. Completed integration results against the updated dependency would close the remaining validation gap.
Final Verdict

Status: ❌ Block until the AMQP-CPP fix is included in the ClickHouse pin. Validate that a multiple negative acknowledgement followed by more than one prefetch window of valid messages continues consuming with that pin.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 14, 2026
…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 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@kssenii CI is green after merging master (including #125105). Ready for review 🙂

( ClickHouse/AMQP-CPP#9 is pending - the code here doesn't change with that fix; only the submodule pin follows.)

@comino

comino commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Any change to pick this up? @groeneai
Im happy to respond to feedback :). The bug is still hurting us in prod.

@groeneai

Copy link
Copy Markdown
Collaborator

I can't merge PRs in this repo or in ClickHouse/AMQP-CPP, so I can't land ClickHouse/AMQP-CPP#9 myself. It needs a maintainer with write access to that fork.

One thing changed today: @ tavplubix merged ClickHouse/AMQP-CPP#11 into the fork's master and opened #130541 to move the pin to it. ClickHouse/AMQP-CPP#9 changes only src/basicnackframe.h, which ClickHouse/AMQP-CPP#11 doesn't touch, so it still merges cleanly, and a pin bump like #130541 could carry the fix.

On this PR: the description says the lost wake-up in waitForMessages is fixed in a follow-up PR, but I can't find that PR. This change makes the stall likelier, so I'd open the follow-up now and link it here, so both can be reviewed together. Otherwise I have nothing to add to the bot's review.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, merged the AMQP-CPP PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged, thanks. I'm opening the ClickHouse PR that moves contrib/AMQP-CPP to 5f4c447 (it already contains a451d69 from #130541) and tightens test_rabbitmq_default_mode_nack_on_parse_error so it fails without the fix. I'll post the link here.

@groeneai

Copy link
Copy Markdown
Collaborator

The PR is #130649. It moves contrib/AMQP-CPP from 4fccd7f to 5f4c447 and makes test_rabbitmq_default_mode_nack_on_parse_error wait for two dead letters, which fails on current master and passes with the new pin.

comino added a commit to comino/ClickHouse that referenced this pull request Nov 12, 2026
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. The loop thread must never wait for
space in the queue, because acks now run on it: the prefetch window (ClickHouse#124655)
keeps the queue from filling.

Nothing may unwind through libuv. If an exception still escapes, the thread
exits, marks the connection broken and run() executes inline until
startLoop() replaces the thread. Such a connection is still 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 added a commit to comino/ClickHouse that referenced this pull request Nov 12, 2026
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 added a commit to comino/ClickHouse that referenced this pull request Nov 12, 2026
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 added a commit to comino/ClickHouse that referenced this pull request Nov 13, 2026
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 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov The AMQP-CPP dependency is resolved: master pins AMQP-CPP 5f4c447 (the merge of ClickHouse/AMQP-CPP#9) since #130541. CI is green and nothing else blocks this PR. It fixes RabbitMQ consumption stopping once the backlog exceeds the internal queue (#54775). Could you take a look? @groeneai

@groeneai

Copy link
Copy Markdown
Collaborator

I re-checked this PR at 3a227d8e against current master:

This branch has not been deployed

No deployments
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RabbitMQ stops consume after sometimes, clickhouse 22, 23

5 participants