Skip to content

Rabbitmq eventbus buffer implementation - #14677

Open
durdin85 wants to merge 6 commits into
apache:mainfrom
durdin85:rabbitmq-eventbus-buffer
Open

durdin85 wants to merge 6 commits into
apache:mainfrom
durdin85:rabbitmq-eventbus-buffer

Conversation

@durdin85

@durdin85 durdin85 commented Nov 11, 2026 •

Copy link
Copy Markdown

Description

This PR makes the RabbitMQ event bus keep events that are published while the
AMQP broker is unreachable and send them, in the order they were published, once
the connection is back. Until now such events were discarded.

Behaviour:

  • Events that cannot be sent are kept in an in-memory FIFO buffer (routing key,
    body, time of buffering).
  • Buffering starts only after the broker was reachable at least once. Before
    that, publish() fails as it does today.
  • The buffer is bounded: at most bufferSize events (default 1000, the oldest is
    dropped when full) and each event is dropped bufferExpiry milliseconds
    (default 300000) after it was buffered. bufferSize 0 disables buffering and
    restores the previous behaviour.
  • While the buffer is not empty, or the connection is down, new events are
    appended to the buffer, so they never overtake older ones. publish() returns
    normally for a buffered event and no longer connects on the calling thread
    while the broker is down (the connection timeout of amqp-client 5.17.0 is
    60 s, so every API call that published an event could hang that long).
  • ReconnectionTask is scheduled with a fixed delay of retryInterval (default
    10 s) for the lifetime of the event bus, instead of being started by
    DisconnectHandler. Each run reconnects if there is no connection,
    re-registers subscribers whose channel is not open, drops expired events and
    sends the buffered ones. This also re-establishes connections closed by the
    bus itself (AlreadyClosedException in publish(), blocked connection),
    which previously started no reconnect. stop() shuts the executor down.
  • Once basicPublish() has returned, an event counts as sent: a failure to
    close the channel afterwards is logged, but the event is not sent again, as
    the broker may already have it.
  • The bus requests a heartbeat timeout of heartbeat seconds (default 10,
    previously the client default of 60). A connection that silently stopped
    working (e.g. packets dropped by a firewall) is only noticed after about two
    heartbeat timeouts; until then events are still sent on the API thread and
    wait for replies, so API calls hung for about 2 minutes with the old value.
  • Errors of the AMQP client are logged with their cause (e.g. connection error: Connection reset) instead of null.

All three settings are optional properties of the existing bean, next to the
other AMQP settings:

<bean id="eventNotificationBus" class="org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus">
    ...
    <property name="bufferSize" value="1000"/>
    <property name="bufferExpiry" value="300000"/>
    <property name="heartbeat" value="10"/>
</bean>

Known limits, by design:

  • No publisher confirms are used. An event that is being sent when the
    connection breaks can be lost unnoticed; events are never sent twice.
  • The buffer is in memory only and is lost when the management server restarts.

No new dependencies; the change is confined to RabbitMQEventBus.

Fixes: #14676

AI disclosure: the code, the unit tests and this description were generated with an AI assistant (Claude Code). The design and its constraints were set by the submitter, who also tested the change on a live system. If the project does not accept AI-generated contributions, please say so and treat this as a proposal for discussion.

Types of changes

  • Breaking change (fix or feature that would cause existing functionality to change)
  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • Enhancement (improves an existing feature and functionality)
  • Cleanup (Code refactoring and cleanup, that may add test cases)
  • Build/CI
  • Test (unit or integration test code)

Feature/Enhancement Scale or Bug Severity

Feature/Enhancement Scale

  • Major
  • Minor

How Has This Been Tested?

New unit test RabbitMQEventBusTest (mocked AMQP connection and channel):

  • publish() still fails when the broker was never reachable;
  • events published while disconnected are sent in order after the reconnect, and
    an event published while the buffer is not empty does not overtake them;
  • an event whose send fails with an IOException is buffered and re-sent;
  • an event is not sent again when closing the channel fails after the publish;
  • the oldest event is dropped when the buffer is full;
  • expired events are dropped, also while disconnected;
  • only subscribers without an open channel are re-registered, and buffered
    events are sent even if a subscriber cannot be re-registered;
  • the reconnection task keeps being scheduled after an unexpected failure;
  • error messages include the causes of the exception.

The plugin builds and RabbitMQEventBusTest passes on main and on 4.22.1.1
(mvn -pl plugins/event-bus/rabbitmq -am test -Dtest=RabbitMQEventBusTest).

Live test on a 4.22.1.1 management server (classes replaced in the bundled jar)
with a RabbitMQ 4.4.0 cluster behind a TCP load balancer, outages simulated with
iptables on the management server, events produced by user login/logout and
compared with the events stored by the consumer:

  • short outages (REJECT --reject-with tcp-reset), including two outages in a
    row: all events buffered during the outage arrived after the reconnect, in
    order and without duplicates;
  • an outage longer than 5 minutes: events older than bufferExpiry were dropped
    and logged, the newer ones arrived after the reconnect;
  • outages with packets dropped in both directions: buffered events arrived after
    the reconnect. The first API call publishing an event waits until the client
    notices the dead connection: about 2 minutes with the previous heartbeat of
    60 s, 23 s with the new default of 10 s (logged as Failed to create a channel due to connection error: Heartbeat missing with heartbeat = 10 seconds).

How did you try to break this feature and the system with this change?

The unit tests cover a full buffer, expired events, a failing send, a failing
channel close, failing subscriber registration, an unexpected failure of the
reconnection task and a connection that returns while events are still
buffered. The live tests cover hard (reset) and silent (dropped packets)
outages, repeated outages and outages longer than the buffer expiry.

durdin85 and others added 2 commits November 11, 2026 11:00
Events published while the AMQP connection is down were discarded.
Keep them in a bounded in-memory FIFO buffer and send them in order
once the connection is back.

- events are buffered only after the broker was reachable once
- buffer is capped (bufferSize, default 1000, oldest dropped first)
  and entries expire (bufferExpiry, default 300000 ms)
- publish() no longer connects on the calling thread while the
  broker is down
- ReconnectionTask runs for the lifetime of the bus, so connections
  closed by the bus itself are re-established as well

This change, including the unit test, was generated with an AI
assistant (Claude Code).

Fixes: apache#14676

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- keep the buffer flush inside the try block, so an unexpected
  exception cannot end the only reconnect thread
- check for an existing connection and connect under the same lock
  as getConnection(), so a connection created by publish() is not
  replaced and leaked

Generated with an AI assistant (Claude Code).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@boring-cyborg

boring-cyborg Bot commented Nov 11, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache CloudStack community! If you have any issues or are unsure about any anything please check our Contribution Guide (https://github.com/apache/cloudstack/blob/main/CONTRIBUTING.md)
Here are some useful points:

Generated with an AI assistant (Claude Code).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

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

thanks @durdin85 , the code lgtm. I have soem style remarks though.

@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.76471% with 24 lines in your changes missing coverage. Please review.
✅ Project coverage is 20.83%. Comparing base (a7be64a) to head (0b85b3d).
⚠️ Report is 26 commits behind head on main.

Files with missing lines Patch % Lines
...ache/cloudstack/mom/rabbitmq/RabbitMQEventBus.java 71.76% 21 Missing and 3 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main   #14677      +/-   ##
============================================
+ Coverage     20.80%   20.83%   +0.02%     
- Complexity    21945    21978      +33     
============================================
  Files          6496     6496              
  Lines        591838   592011     +173     
  Branches      72617    72635      +18     
============================================
+ Hits         123147   123320     +173     
+ Misses       455315   455307       -8     
- Partials      13376    13384       +8     
Flag Coverage Δ
uitests 3.87% <ø> (-0.01%) ⬇️
unittests 22.14% <71.76%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

durdin85 and others added 2 commits November 27, 2026 09:49
- reconnect and flush from a ScheduledExecutorService instead of a
  while(true) loop; the task catches Throwable, as the executor
  silently stops running a task that ended with an exception
- loop over the buffer with while ((bufferedEvent = peekBuffer()) != null)
- re-register every subscriber whose channel is not open, also when
  publish() or subscribe() re-established the connection
- replace the two duplicated anonymous consumers by SubscriberConsumer
- drop the s_ prefix of the fields, fix Javadoc and typos
- log when the background thread has reconnected
- default retryInterval to 10 s when it is not positive, as
  scheduleWithFixedDelay rejects such a delay

Generated with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0148pno3o4K3zhvhP3AJaJg3
…blished event

- request a heartbeat timeout of 10 s (bean property heartbeat) instead
  of the client default of 60 s: a connection that silently stopped
  working is noticed only after about two heartbeat timeouts, and until
  then events are sent on the API thread and wait for replies
- count an event as sent once basicPublish() has returned; a failure to
  close the channel afterwards is only logged, as the broker may have
  the event already and sending it again could duplicate it
- log the causes of AMQP client exceptions instead of "null"
- document the bean properties on their setters

Tested on a 4.22.1.1 management server against RabbitMQ 4.4.0, with
outages simulated by iptables (connection reset and dropped packets).

Generated with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0148pno3o4K3zhvhP3AJaJg3

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

clgtm, thanks I am suggesting to remove a lot of comments as you are way too generous with those, But left a question at some of them.


private static Integer retryInterval;

// max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering

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.

Suggested change
// max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering
/**
* max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering
*/

// max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering
private static Integer maxEventBufferSize = 1000;

// time in milliseconds after which a buffered event is dropped if it could not be sent

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.

Suggested change
// time in milliseconds after which a buffered event is dropped if it could not be sent
/**
* time in milliseconds after which a buffered event is dropped if it could not be sent
*/

private void registerSubscriber(Connection connection, String queueName) throws Exception {
Ternary<String, Channel, EventSubscriber> subscriberDetails = subscribers.get(queueName);

// create a channel dedicated for this subscription

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.

Suggested change
// create a channel dedicated for this subscription

// create a channel dedicated for this subscription
Channel channel = createChannel(connection);

// create a queue and bind it to the exchange with binding key formed from event topic

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.

Suggested change
// create a queue and bind it to the exchange with binding key formed from event topic

// register a callback handler to receive the events that a subscriber subscribed to
channel.basicConsume(queueName, autoAck, queueName, new SubscriberConsumer(channel));

// update the channel details for the subscription

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.

Suggested change
// update the channel details for the subscription

private static String getErrorMessage(Throwable exception) {
StringBuilder message = new StringBuilder();
for (Throwable cause = exception; cause != null; cause = cause.getCause()) {
// skip messages already included, e.g. by exceptions created with the cause as their message

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.

Suggested change
// skip messages already included, e.g. by exceptions created with the cause as their message

public boolean start() {
ReconnectionTask reconnect = new ReconnectionTask(); // initiate connection to AMQP server
executorService.submit(reconnect);
// initiate connection to AMQP server

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.

Suggested change
// initiate connection to AMQP server

String resourceType = getResourceTypeFromRoutingKey(routingKey);
String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);

// create event object from the message details obtained from AMQP server

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.

Suggested change
// create event object from the message details obtained from AMQP server

Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
event.setDescription(new String(body));

// deliver the event to call back object provided by subscriber

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.

Suggested change
// deliver the event to call back object provided by subscriber

try {
super.run();
} catch (Throwable t) {
// the executor would never run the task again if it ended with an exception

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.

Suggested change
// the executor would never run the task again if it ended with an exception

I agree but on the other hand Throwable is a very wide net. If you feel it is needed...

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I'd keep it. If this would be more specific and it ever hit something unmatched the bus would never reconnect or send the buffered events again until a restart.

Comment changes only, as suggested in the review: drop comments that
repeat the code, turn the buffer limit comments into Javadoc and reword
the comment in flushBuffer() that read as contradicting the code below
it. The compiled bytecode is unchanged.

Generated with an AI assistant (Claude Code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: AMQP event bus - buffer events while the broker is unreachable

2 participants