Skip to content

About

Delayed Messaging for RabbitMQ

Resources

Code of conduct

Contributing

Stars

6 stars

Watchers

4 watching

Forks

 
 

Repository files navigation

RabbitMQ Delayed Message Plugin

This is a fork of https://github.com/rabbitmq/rabbitmq-delayed-message-exchange which is no longer maintained by Team RabbitMQ. The goal of this fork is to support newer RabbitMQ versions that are using the Khepri metadata store.

This plugin adds delayed-messaging (or scheduled-messaging) to RabbitMQ.

Its current design has significant limitations (documented below) consider the alternatives on the original repo.

If you accept the limitations, please read on.

The Basics

With this plugin enabled, a user can declare an exchange with the type x-delayed-message and then publish messages with the custom header x-delay expressing in milliseconds a delay time for the message. The message will be delivered to the respective queues after x-delay milliseconds.

Intended Use Cases

This plugin was designed for delaying message publishing for a number of seconds, minutes, or hours. A day or two at most.

It is not a longer term scheduling solution. If you need to delay publishing by days, weeks, months, or years, consider using a data store suitable for long-term storage, and an external scheduling tool of some kind.

Supported RabbitMQ Versions

This version of the plugin requires RabbitMQ 4.3.3 or later.

Each build of this plugin pins to a specific RabbitMQ patch version (see RABBITMQ_VERSION in the Makefile).

This version of the plugin requires the khepri_db feature flag to be enabled (the default in RabbitMQ 4.2+). Delayed messages are stored in a Leveled LSM-tree database local to each node.

Supported Erlang/OTP Versions

The latest version of this plugin requires Erlang 27.0 or later versions. RabbitMQ 4.3.3 dropped support for Erlang 26, so Erlang 26 nodes cannot run this version of the plugin.

Feature Flags

This plugin ships a stable feature flag, delayed_message_topic_projection_v2. It selects the internal Khepri projection the plugin uses to route messages whose x-delayed-type is topic, once their delay elapses:

  • when disabled, the plugin uses a single-table projection (v1)
  • when enabled, the plugin uses a two-table projection (v2) that mirrors the core broker's v5 topic trie projection

The v5 topic trie projection was introduced in RabbitMQ 4.3.1 as part of a routing bugfix. The flag depends on topic_binding_projection_v5, so it can only be enabled once every node runs RabbitMQ 4.3.1 or later with the topic_binding_projection_v5 flag enabled.

Enabling the flag does not change the plugin's routing results, only its internal representation.

On a new cluster the flag is enabled by default once the plugin is enabled, so no action is needed. When upgrading from a plugin version that predates the flag, enable it once every node has been upgraded:

rabbitmqctl enable_feature_flag delayed_message_topic_projection_v2

The migration is safe to run on a live cluster: the plugin keeps routing through the v1 projection while the v2 projection is registered, and only removes the v1 projection after the flag is enabled cluster-wide.

Installation

Download a Binary Build

Binary builds are distributed via GitHub releases.

As with all 3rd party plugins, the .ez files the release provides must be copied into the node's plugins directory with sufficient permissions for the effective user of the RabbitMQ process to load it from disk.

To find out what the plugins directory is, use rabbitmq-plugins directories

rabbitmq-plugins directories -s

Enabling the Plugin

To enable the plugin run the following command:

rabbitmq-plugins enable rabbitmq_delayed_message_exchange

Upgrading from the Original Plugin

This version keeps delayed messages in Leveled and has no Mnesia code left, so it cannot see the messages the original plugin, or any version of this fork running on a cluster without khepri_db, stored in Mnesia. The upgrade path goes through v4.2.6 of this fork, the last release that still ships the Mnesia backend: it uses the table names and record layout of the original plugin, so it picks up your existing delayed messages and keeps working with them, and it carries the Mnesia-to-Leveled migration that runs when the khepri_db feature flag is enabled.

Two rules hold for the whole procedure:

  • do not disable the plugin at any point, not even to swap the .ez files: disabling it destroys the storage and ALL DELAYED MESSAGES THAT HAVEN'T BEEN DELIVERED WILL BE LOST
  • do not enable khepri_db before v4.2.6 of this fork is running on every node: the plugin picks its backend from whether that flag is enabled, so if it is already enabled the first time this fork starts, the plugin goes straight to Leveled and the messages sitting in the Mnesia tables are never migrated

The Upgrade Path

  1. Upgrade the broker to RabbitMQ 4.2.6 or a later 4.2.x release, with khepri_db still disabled. Fork v4.2.6 requires 4.2.6 because migrating the plugin's dynamically named Mnesia tables needs rabbitmq/rabbitmq-server#16139

  2. Install fork v4.2.6 in place of the original plugin on every node: download rabbitmq_delayed_message_exchange-4.2.6-erlang-26.zip from the release, extract both .ez files it contains (one for the plugin, one for leveled) into the node's plugins directory, and remove the original plugin's .ez from there. Leave the plugin enabled

  3. Restart the nodes, one at a time if you prefer: each node keeps its delayed messages in tables of its own. From the outside nothing should change, the plugin keeps working with the same Mnesia tables, only the code behind them is the fork's

  4. Enable the metadata store feature flag once for the cluster:

    rabbitmqctl enable_feature_flag khepri_db

    This triggers the plugin's migration: pending delayed messages are copied out of Mnesia into the node-local Leveled store, and the plugin switches to it once the flag is fully enabled

  5. Confirm the migration went through before going any further: the node log records the copy (Mnesia->Leveled data copy entries, at debug level), a Leveled store appears under user_provided_plugins_data_dir/rabbit_delayed_message/leveled in the node's data directory, and messages scheduled before the upgrade are still delivered on time

  6. Upgrade the broker to RabbitMQ 4.3.3 or later (Erlang 27 or newer, and khepri_db is required there) and replace the .ez files with the ones from the matching release of this plugin. The on-disk Leveled store is read as it is, no further data migration takes place

  7. Enable the plugin's own feature flag once every node runs the new version (see Feature Flags above):

    rabbitmqctl enable_feature_flag delayed_message_topic_projection_v2

From that point on this plugin is upgraded like any other one: drop in the new .ez files and restart the node.

Rehearse the whole path on a test cluster before running it in production: the delayed messages of a node exist in one copy, on that node, and there is no way to recover them if a step goes wrong.

When khepri_db Is Already Enabled

A cluster that enabled khepri_db while still running the original plugin has no automatic path for the messages already in Mnesia: whichever version of this fork is installed afterwards starts on an empty Leveled store and the Mnesia tables are left untouched. Drain the backlog first instead. Stop publishing to the delayed exchanges, wait until every scheduled message has been delivered, and only then swap the plugin for this fork. There is nothing to migrate at that point, so the intermediate v4.2.6 step can be skipped as well.

After the Migration

Messages stored by v4.3.3 and earlier, including the ones the migration copied out of Mnesia, carry no payload size in their store metadata: the byte counter did not exist yet. They are counted as zero bytes by rabbitmq_detailed_delayed_message_bytes (see Prometheus Metrics below) until they are delivered, so the reported size of an exchange with a pre-upgrade backlog is lower than the actual one. The message counts are unaffected.

Usage

To use the delayed-messaging feature, declare an exchange with the type x-delayed-message:

// ... elided code ...
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-delayed-type", "direct");
channel.exchangeDeclare("my-exchange", "x-delayed-message", true, false, args);
// ... more code ...

Note that we pass an extra header called x-delayed-type, more on it under the Routing section.

Once we have the exchange declared we can publish messages providing a header telling the plugin for how long to delay our messages:

// ... elided code ...
byte[] messageBodyBytes = "delayed payload".getBytes("UTF-8");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("x-delay", 5000);
AMQP.BasicProperties.Builder props = new AMQP.BasicProperties.Builder().headers(headers);
channel.basicPublish("my-exchange", "", props.build(), messageBodyBytes);

byte[] messageBodyBytes2 = "more delayed payload".getBytes("UTF-8");
Map<String, Object> headers2 = new HashMap<String, Object>();
headers2.put("x-delay", 1000);
AMQP.BasicProperties.Builder props2 = new AMQP.BasicProperties.Builder().headers(headers2);
channel.basicPublish("my-exchange", "", props2.build(), messageBodyBytes2);
// ... more code ...

In the above example we publish two messages, specifying the delay time with the x-delay header. For this example, the plugin will deliver to our queues first the message with the body "more delayed payload" and then the one with the body "delayed payload".

If the x-delay header is not present, then the plugin will proceed to route the message without delay.

Routing

This plugin allows for flexible routing via the x-delayed-type arguments that can be passed during exchange.declare. In the example above we used "direct" as exchange type. That means the plugin will have the same routing behavior shown by the direct exchange.

If you want a different routing behavior, then you could provide a different exchange type, like "topic" for example. You can also specify exchange types provided by plugins. Note that this argument is required and must refer to an existing exchange type.

Blocking Routing During Upgrades

While nodes restart during a rolling upgrade, quorum queues elect new leaders and classic queue processes stop. A delayed message whose delay expires at that moment can find no route and is then dropped silently. To avoid that, routing of expired delayed messages can be blocked before the upgrade and unblocked after it.

The block is per node: each node keeps its own delayed messages and its own block. Since a queue may live on another node than the delayed message, block every node before the upgrade, and unblock every node after it:

rabbitmqctl -n rabbit@node1 eval 'rabbit_delayed_message:block_routing().'
# ... the same for every node, then the rolling upgrade ...
rabbitmqctl -n rabbit@node1 eval 'rabbit_delayed_message:unblock_routing().'

# the state of a node
rabbitmqctl -n rabbit@node1 eval 'rabbit_delayed_message:is_routing_blocked().'

A node that is down can be blocked by creating its marker file (see below) before starting it.

While routing is blocked on a node:

  • every x-delayed-message exchange keeps accepting and storing delayed messages on that node, but routes none of them when their delay expires: they stay stored, and still count in messages_delayed and in the Prometheus metrics
  • messages published without a delay are routed as usual: the publishing channel routes them, so publishers learn about a missing route through publisher confirms or the mandatory flag
  • the block is written to disk before block_routing() returns, so the node comes back blocked after a restart

Once unblocked, the node goes back to routing as usual, starting with the messages that expired meanwhile, in delay order. unblock_routing() does not wait for those messages to be routed: the routing happens in the background.

The block is an empty marker file next to the node's data directory: routing is blocked while <data dir>-delayed-message-exchange/routing_blocked exists (for example /var/lib/rabbitmq/mnesia/rabbit@hostname-delayed-message-exchange/routing_blocked). Creating the file by hand while a node is down makes it start blocked. It is kept outside the data directory because on RabbitMQ 3.13, enabling the khepri_db feature flag deletes most of the data directory's content. The file is not removed when the plugin is disabled or the node is reset.

Nodes running a plugin version without this feature ignore the block.

Performance Impact

Due to the "x-delayed-type" argument, one could use this exchange in place of other exchanges, since the "x-delayed-message" exchange will just act as proxy. Note that there might be some performance implications if you do this.

For each message that crosses an "x-delayed-message" exchange, the plugin will try to determine if the message has to be expired by making sure the delay is within range, i.e.: Delay > 0, Delay =< ?ERL_MAX_T (In Erlang a timer can be set up to (2^32)-1 milliseconds in the future).

If the previous condition holds, then the message is persisted. The message body goes into a Leveled LSM-tree database on disk, and an entry keyed by the scheduled delivery time stamp is inserted into an in-memory ordered_set ETS index that drives next-timer selection. Some other logic will then kick in to determine if this particular message delay needs to replace the current scheduled timer and so on.

This means that while one could use this exchange in place of a direct or fanout exchange (or any other exchange for that matter), it will be slower than using the actual exchange. If you don't need to delay messages, then use the actual exchange.

Storage Characteristics

The Leveled-based storage has two notable characteristics:

  • Smaller memory footprint: delayed messages are not kept in memory in their entirety. Only an index is held in memory while the message bodies live in the Leveled LSM-tree on disk, resulting in a considerably smaller memory footprint.
  • Stable behavior under scheduling collisions: write and startup times remain stable even when a large number of messages are scheduled to the exact same expiry timestamp.

Configuration

The plugin reads its configuration from rabbitmq.conf:

delayed_message_exchange.journal_compaction_interval_seconds = 600
  • journal_compaction_interval_seconds: how often, in seconds, the plugin asks Leveled to compact its journal. Defaults to 600 (10 minutes); 0 disables the periodic runs

Delivering a message appends a tombstone to the Leveled journal instead of freeing the space the message occupied, and that space only comes back when the journal is compacted. Leveled leaves the scheduling of journal compaction to the application embedding it, so the plugin has to ask for it, and this setting controls how often. Note that a run can only reclaim journal entries that the on-disk ledger already covers, so a store that has seen little traffic since the node started may hold on to its journal even though the messages in it have all been delivered.

rabbit_delayed_message:compact_journal() runs a compaction immediately, independently of the schedule. It returns ok once the run has been handed to Leveled, busy when the previous run has not finished yet (the periodic runs skip for the same reason), not_running when the store is not up, and {error, Reason} if the request could not be made.

The same setting can be given in the rabbitmq_delayed_message_exchange application environment in advanced.config:

[
  {rabbitmq_delayed_message_exchange, [
    {journal_compaction_interval_seconds, 600}
  ]}
].

Both files are only read at boot. To change the interval on a running node, set the application environment variable and ask the plugin to re-read its configuration:

application:set_env(rabbitmq_delayed_message_exchange,
                    journal_compaction_interval_seconds, 60),
rabbit_delayed_message:refresh_config().

Tuning the Leveled Store

The settings below are passed straight to the Leveled bookie the plugin keeps its messages in, under the name Leveled gives them, so Leveled's startup options documentation applies to them as well. Leaving one unset leaves Leveled's own default in place, except for log_level. They are only read when the store starts, so a change needs a node restart (or a plugin disable and re-enable), unlike the compaction interval:

delayed_message_exchange.leveled.max_run_length = 8
delayed_message_exchange.leveled.singlefile_compactionpercentage = 30.0
delayed_message_exchange.leveled.maxrunlength_compactionpercentage = 70.0
delayed_message_exchange.leveled.journalcompaction_scoreonein = 1
delayed_message_exchange.leveled.max_journalobjectcount = 200000
delayed_message_exchange.leveled.max_journalsize = 1GB
delayed_message_exchange.leveled.waste_retention_period_seconds = 3600
delayed_message_exchange.leveled.log_level = warning
  • log_level: level of the logs the store writes, one of debug, info, warning, error and critical. Defaults to warning, unlike Leveled's own default of info, which logs a report on every journal roll, compaction run and ledger merge. Set it to info to get those reports back
  • max_run_length: largest number of consecutive journal files one compaction run may rewrite. This is what caps how long a run can take. Defaults to 8
  • singlefile_compactionpercentage: percentage of a journal file that may be kept for that file to still be worth compacting on its own. Defaults to 30.0, meaning a file has to be at least 70% reclaimable
  • maxrunlength_compactionpercentage: the same percentage for a run of max_run_length files, interpolated for shorter runs. Defaults to 70.0, and has to be at or above singlefile_compactionpercentage
  • journalcompaction_scoreonein: probability (1 in this many) that a journal file is rescored on a run instead of reusing its cached score. Defaults to 1, which rescores every file on every run; higher values trade accuracy for less scan I/O
  • max_journalobjectcount: number of entries after which a journal file is rolled. Only a rolled file can be compacted, so this is also the unit of reclaim. Defaults to 200000
  • max_journalsize: size at which a journal file is rolled, whichever comes first with max_journalobjectcount. Defaults to 1GB, and Leveled caps it at 4GB
  • waste_retention_period_seconds: how long journal files that compaction has replaced are kept in a waste directory instead of being deleted. Unset by default, which deletes them; setting it keeps the disk space for that long, so it is only useful for debugging

In advanced.config these are rabbitmq_delayed_message_exchange application environment keys of the same name, except for waste_retention_period_seconds, whose environment key is Leveled's own waste_retention_period, and log_level, whose environment key is leveled_log_level:

[
  {rabbitmq_delayed_message_exchange, [
    {max_run_length, 4},
    {singlefile_compactionpercentage, 40.0}
  ]}
].

Everything else the plugin passes to the bookie is fixed, including the recovr reload strategy and the metadata extractor, both of which this store depends on.

Values set in rabbitmq.conf are validated against the plugin's schema, which also rejects a maxrunlength_compactionpercentage/singlefile_compactionpercentage pair in the wrong order, so such a configuration is reported before it is applied. Values set in advanced.config skip that validation and reach the bookie as they are, and Leveled refuses to start on one it does not accept: there the two compaction percentages have to be floats (40.0, not 40) and in the right order.

Leveled's design notes and startup options describe how its journal, ledger and compaction work; the Max Journal Size, Journal Compaction and Waste Retention Period sections of the latter cover the settings above.

Prometheus Metrics

When the rabbitmq_prometheus plugin is enabled, this plugin exposes, for each x-delayed-message exchange, the number of messages currently delayed and the size of their bodies:

rabbitmq_detailed_delayed_messages{exchange="my-exchange",vhost="/"} 42.0
rabbitmq_detailed_delayed_message_bytes{exchange="my-exchange",vhost="/"} 6144.0

rabbitmq_detailed_delayed_message_bytes counts message bodies only, the same way the broker's own message_bytes metrics do, so it excludes per-message metadata and storage overhead.

The metric is only served by the detailed endpoint and, like every other detailed metric, it must be requested explicitly with the family query parameter:

GET /metrics/detailed?family=delayed_exchange_metrics

The vhost query parameter is honoured as well, so a scrape can be limited to a subset of virtual hosts:

GET /metrics/detailed?family=delayed_exchange_metrics&vhost=my-vhost

Both metrics are reported per exchange only. Per-virtual-host and cluster-wide numbers have to be aggregated from them at query time.

Delayed messages are stored by the node that accepted the publish, so the reported values are node-local: a cluster-wide total aggregates the values reported by every node.

An exchange gets its series on a node once it delays its first message there, and loses them when it is deleted. Messages an exchange had already delayed stay on disk until they expire, but they are then routed to nowhere, so no metric is reported for them.

The plugin does not depend on rabbitmq_prometheus: when that plugin is not enabled, no metrics are exported. The collector is registered when this plugin starts, so if rabbitmq_prometheus is enabled afterwards, register it without restarting this plugin with:

rabbitmqctl eval 'rabbit_delayed_message_prometheus:ensure_registered().'

Limitations

Delayed messages are stored in a Leveled LSM-tree database with a single copy on the current node. They will survive a node restart. While timer(s) that triggered scheduled delivery are not persisted, they will be re-initialised during plugin activation on node start. Obviously, only having one copy of a scheduled message in a cluster means that losing that node or disabling the plugin on it will lose the messages residing on that node.

The plugin only performs one attempt at publishing each message but since publishing is local, in practice the only issue that may prevent delivery is the lack of queues (or bindings) to route to.

Closely related to the above, the mandatory flag is not supported by this exchange: we cannot be sure that at the future publishing point in time

  • there is at least one queue we can route to
  • the original connection is still around to send a basic.return to

The Leveled-based storage keeps message bodies on disk (see Storage Characteristics above), but its in-memory ETS index still holds one entry per scheduled message until delivery, so memory overhead grows linearly with the number of pending messages. Workloads with very large backlogs (hundreds of thousands or millions of pending messages) should size node memory accordingly.

Disabling the Plugin

You can disable this plugin by calling rabbitmq-plugins disable rabbitmq_delayed_message_exchange but note that ALL DELAYED MESSAGES THAT HAVEN'T BEEN DELIVERED WILL BE LOST.

Building the Plugin

PROJECT_VERSION=4.3.3 PRODUCT_VERSION=4.3.3 VERSION=4.3.3 \
    gmake dist PROJECT_VERSION=4.3.3 PRODUCT_VERSION=4.3.3 \
    VERSION=4.3.3 DIST_AS_EZS=true

The EZ file is created in the plugins directory.

Creating a Release

  1. Update RABBITMQ_VERSION in Makefile to the target RabbitMQ release (e.g. v4.3.3)
  2. Update broker_version_requirements in the PROJECT_APP_EXTRA_KEYS block of Makefile to the oldest patch release the artifacts can load on, which need not be RABBITMQ_VERSION but must not predate the first release requiring the Erlang version used to build them
  3. Update the RabbitMQ and Erlang versions in .github/workflows/test.yml and .github/workflows/package.yml
  4. Push a tag (i.e. v4.3.3) with the matching version
  5. The Package workflow (.github/workflows/package.yml) builds the .ez artifacts on push
  6. Attach the produced rabbitmq_delayed_message_exchange*.ez and leveled*.ez files to a GitHub release

LICENSE

See the LICENSE file.

About

Delayed Messaging for RabbitMQ

Resources

Code of conduct

Contributing

Stars

6 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages