Skip to content

Rabbitmq eventbus buffer implementation - #14677

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

durdin85 wants to merge 5 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.

Comment on lines +89 to +90
// max number of events kept in memory while the AMQP server is unreachable, 0 disables buffering
private static Integer bufferSize = 1000;

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
private static Integer bufferSize = 1000;
private static Integer maxEventBufferSize = 1000;

Comment on lines +92 to +93
// time in milliseconds after which a buffered event is dropped if it could not be sent
private static Integer bufferExpiry = 300000;

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
private static Integer bufferExpiry = 300000;
private static Integer eventBufferExpiryTime = 300000;

Comment on lines +95 to +96
// events (routing key, description, time of buffering) waiting to be sent, oldest first
private static final ArrayDeque<Ternary<String, String, Long>> s_buffer = new ArrayDeque<>();

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
// events (routing key, description, time of buffering) waiting to be sent, oldest first
private static final ArrayDeque<Ternary<String, String, Long>> s_buffer = new ArrayDeque<>();
/**
* events, stored as {routing key, description, time of buffering}, waiting to be sent, oldest first
*/
private static final ArrayDeque<Ternary<String, String, Long>> eventBuffer = new ArrayDeque<>();

needs renaming below as well!

Comment on lines +193 to +195
public static void setBufferSize(Integer bufferSize) {
RabbitMQEventBus.bufferSize = bufferSize;
}

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
public static void setBufferSize(Integer bufferSize) {
RabbitMQEventBus.bufferSize = bufferSize;
}
/**
* maximum size to which the event buffer may grow
*/
public static void setBufferSize(Integer bufferSize) {
maxEventBufferSize = bufferSize;
}

Comment on lines +197 to +199
public static void setBufferExpiry(Integer bufferExpiry) {
RabbitMQEventBus.bufferExpiry = bufferExpiry;
}

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
public static void setBufferExpiry(Integer bufferExpiry) {
RabbitMQEventBus.bufferExpiry = bufferExpiry;
}
/**
* expriy time to set for events that cannot be send
*
*/
public static void setBufferExpiry(Integer bufferExpiry) {
eventBufferExpiryTime = bufferExpiry;
}

return true;
}

// drops the expired events and, if connected, sends the buffered ones in the order they were added

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.

top of method comment:

Suggested change
// drops the expired events and, if connected, sends the buffered ones in the order they were added
/**
* drops the expired events and, if connected, sends the buffered ones in the order they were added
*/

Comment on lines +385 to +389
// the event stays in the buffer while being sent, so that newer events queue up behind it
synchronized (s_buffer) {
if (s_buffer.peek() == bufferedEvent) {
s_buffer.poll();
}

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.

can you extract this to a separate method? sounds trivial but it makes for better reading

}

abortConnection(); // disconnected to AMQP server, so abort the connection and channels
// the ReconnectionTask started with the event bus takes care of the re-connect

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 ReconnectionTask started with the event bus takes care of the re-connect

Comment on lines +658 to +659
// runs for the lifetime of the event bus: connects back to AMQP server after any loss of connection
// and sends the events buffered in the meantime

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
// runs for the lifetime of the event bus: connects back to AMQP server after any loss of connection
// and sends the events buffered in the meantime
/*
* runs for the lifetime of the event bus: connects back to AMQP server after any loss of connection
* and sends the events buffered in the meantime
*/

protected void runInContext() {

while (!connected) {
while (true) {

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.

not all of this is on you, @durdin85 , but this is a forever loop with nested try blocks and an anonymous class inside. Could you at least put the new part (the sync block in a separate method? If you have the energy, feel free to simplify it further.

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.

Thanks @DaanHoogland for review, I'll take a look on this. The old while task ended after one successful connect if I am not mistaken, and a new one was spawned per disconnect, whereas now one task lives as long as the bus and does all reconnecting and flushing, but maybe it is a good idea to redo it.

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 was thinking about that, and instead of the endless loop, the loop content might be moved to the SingleThreadScheduledExecutor, which then does the repetition, and should be guaranteed to be in order and unique. There's second endless loop in buffer flush, but that can be easily fixed.

@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

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