0.0
The project is in a healthy, maintained state
A RabbitMQ client for the async fiber scheduler: no threads, publishes that wait for the broker, consumers you pull from, reconnection built in.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

async-rabbitmq

A RabbitMQ (AMQP 0-9-1) client for Ruby's fiber scheduler, built on Async and amq-protocol. No threads: the reader, the heartbeat and every handler are fibers, so it fits Falcon and anything else that runs under async.

require "async"
require "async/rabbitmq"

Sync do
  Async::RabbitMQ::Client.open("amqp://guest:guest@localhost") do |client|
    events = client.exchange("events", :topic)
    audit  = client.queue("events.audit").bind(events, routing_key: "audit.#")

    events.publisher do |publisher|
      publisher.publish("user 42 logged in", routing_key: "audit.login")
    end

    audit.consumer do |consumer|
      consumer.each do |message|
        puts message.body
        message.ack
        consumer.stop
      end
    end
  end
end

Contents

  • Installing
  • Two clients in one gem
  • How it is put together
  • Connecting
  • Queues, exchanges and bindings
  • Publishing
  • Consuming
  • Request and reply (RPC)
  • When the connection is lost
  • A cluster
  • Errors
  • Logging
  • OpenTelemetry
  • What is not here
  • Development

Installing

# Gemfile
gem "async-rabbitmq", "~> 0.11"

Requires Ruby 3.4+ and RabbitMQ 3.13+ (tested against 4.x). Everything here runs inside a reactor: Sync do ... end, an Async task, or a Falcon application.

Two clients in one gem

The gem holds two clients. An application uses one or the other, chosen by what it requires:

This client The legacy engine
Require require "async/rabbitmq" require "async_rabbitmq"
Namespace Async::RabbitMQ AsyncRabbitMQ
Shape Built for async Mirrors Bunny's API
Status Where new work goes Kept working, no new features
Documentation This file docs/legacy-engine.md

Neither loads any of the other's code.

Bundler requires a gem by its name, and async-rabbitmq is read as async/rabbitmq. An application that stays on the legacy engine should say which it wants:

gem "async-rabbitmq", "~> 0.11", require: "async_rabbitmq"

How it is put together

There are four things to know, and the rest follows from them.

  • A Client is one connection to one broker, and it keeps it. When the connection is lost the client opens another and declares again whatever it was asked to declare.
  • A Publisher publishes and a consumer consumes. Each has an AMQP channel to itself, which you never see, and each moves itself to the client's next connection when one is lost.
  • publish returns when the broker has taken the message, and raises if it did not. Publisher confirms are on unless you turn them off for a publisher.
  • A consumer is pulled from. each hands your block one message at a time, and the message settles itself: message.ack.

While there is no connection, anything that needs one waits for it. Nothing raises because of an outage unless you ask for that.

Connecting

client = Async::RabbitMQ::Client.open("amqps://app:secret@rabbit.example.com/orders")
# ...
client.close

With a block, open closes the client when the block returns or raises. Closing a client closes every publisher and consumer made through it.

The address is a URL, or an Endpoint when there is more to say:

endpoint = Async::RabbitMQ::Endpoint.parse("amqp://rabbit.example.com/orders",
                                           heartbeat: 30, connection_name: "billing-worker")
client   = Async::RabbitMQ::Client.open(endpoint)
Endpoint option Default Meaning
heartbeat 60 Seconds; 0 asks for none
timeout 10 Seconds to connect and complete the handshake
call_timeout 15 Seconds to wait for the broker to answer a request; nil waits for ever
connection_name none Shown in the broker's management UI
channel_max 2047 Most channels, and so most publishers and consumers, on the connection
frame_max 131072 Largest frame, in bytes
auth_mechanism negotiated "PLAIN" or "EXTERNAL" to force one
tcp_user_timeout from the heartbeat Milliseconds before the kernel gives up on unacknowledged data

A URL may carry heartbeat, channel_max, connection_timeout and auth_mechanism as query parameters. A keyword argument wins over the URL.

Client option Default Meaning
reconnect_interval 1 Seconds before the first attempt to reconnect; doubles with each failure, with jitter
reconnect_max_interval 30 Where the doubling stops
reconnect_attempts nil Failures in a row that end the client; nil never gives up
shuffle true With several endpoints, try them in a new random order each time

Several addresses

Given a list, the client connects to whichever will have it, and tries them all again when that connection is lost. It is still one connection to one node at a time. For a connection to every node, see A cluster.

Async::RabbitMQ::Client.open(%w[amqp://rabbit1 amqp://rabbit2 amqp://rabbit3])

TLS

An amqps:// URL verifies the broker against the system's trust store. For a private CA or a client certificate, build a context:

context  = Async::RabbitMQ::TLS.context(cert: "client.pem", key: "client.key",
                                        ca_certificates: ["ca.pem"])
endpoint = Async::RabbitMQ::Endpoint.parse("amqps://rabbit.example.com", ssl_context: context)

Each of cert, key and ca_certificates takes a file path or PEM text, so material from a secrets manager works as well as a file. The same can be said in the URL with cacertfile, certfile, keyfile and verify=false.

With a client certificate the client offers EXTERNAL authentication, where the broker takes the user from the certificate, and falls back to PLAIN. EXTERNAL needs the rabbitmq_auth_mechanism_ssl plugin on the broker. It is not covered by this gem's integration tests, because the test broker does not have the plugin.

Queues, exchanges and bindings

orders = client.queue("orders")                            # durable
events = client.exchange("events", :topic)                 # durable
orders.bind(events, routing_key: "order.*")

quorum = client.queue("payments", type: :quorum)
ttl    = client.queue("scratch", arguments: { "x-message-ttl" => 60_000 })

Whatever is declared through the client is remembered, and declared again on every new connection before anything else is let onto it. client.forget(queue) drops one from that record; queue.delete and exchange.delete do so too.

On a queue
bind(exchange, routing_key:, arguments:), unbind(...) Returns the queue, so it chains
message_count, consumer_count, exists? Asked of the broker each time
purge, delete(if_unused:, if_empty:)
consumer(**options), managed_consumer(**options) A consumer of this queue
On an exchange
bind(source, routing_key:, arguments:), unbind(...) Exchange-to-exchange
exists?, delete(if_unused:)
publisher(**options) A publisher to this exchange

client.queue?("name") and client.exchange?("name") ask whether one exists without declaring it. client.default_exchange is the default exchange.

A queue declared on the client is always durable. RabbitMQ 4 refuses a queue that is neither durable nor exclusive, and closes the whole connection to say so, so durable: false raises ArgumentError before it is sent. For a queue that should go when you do, let a consumer declare its own: see A queue of the consumer's own.

Publishing

publisher = client.publisher("events")          # an exchange, by name or object
publisher.publish("hello", routing_key: "order.created")

publisher = client.publisher                    # the default exchange:
publisher.publish("hello", routing_key: "orders")   # the routing key is the queue

publish returns true once the broker has confirmed the message. Many fibers can publish through one publisher at once, and each waits only for its own message.

It raises when the message was not taken:

Raises When
NackedError The broker refused it
ReturnedError It was mandatory and no queue took it
UnconfirmedError The connection was lost before the broker answered
ChannelError The broker closed the channel, for example over an exchange that does not exist
ClosedError The publisher was closed first

The message's AMQP properties are keyword arguments: content_type, content_encoding, headers, priority, correlation_id, reply_to, expiration, message_id, timestamp, type, user_id, app_id. So are exchange, mandatory and persistent, to override the publisher's own for one message. A body is a String.

Publisher option Default Meaning
persistent true Messages survive a broker restart, in a durable queue
mandatory false The broker returns a message no queue takes, and publish raises
timestamps true Stamp each message with when it was published; see Message age
max_unconfirmed 1000 Messages sent and not yet answered; a publish beyond that waits
resend false Send unanswered messages again after a lost connection; see below
confirms true Have the broker answer for each message; see Without confirms
no_connection :wait :raise to raise ConnectionError instead of waiting while there is no connection; see With no connection

Not waiting: submit

submit sends the message and returns an Outcome without waiting for the broker. This is how to publish a batch and then collect the answers:

outcomes = orders.map { |order| publisher.submit(order.to_json, routing_key: "orders") }
outcomes.each(&:wait)        # raises for the first that was not taken

outcome.wait(timeout: 5) raises TimeoutError if no answer comes in time, and can be called again. outcome.status is :pending, :acked, :nacked, :returned or :failed (or :sent, without confirms), and outcome.error is what wait would raise.

A message caught by a lost connection

A message that had been sent, and not answered for, when the connection went is a problem with no clean answer: the broker may have it or may not, and nothing will ever say which. By default it fails with UnconfirmedError and you decide. resubmit sends it again, at the risk of a second copy, and the same outcome then answers for the new one:

outcome = publisher.submit(body, routing_key: "orders")
begin
  outcome.wait
rescue Async::RabbitMQ::UnconfirmedError
  outcome.resubmit
  retry
end

A publisher made with resend: true makes that choice for every message. On the new connection it sends again everything unanswered, in the order it was first sent, and fibers waiting in publish go on waiting. Use it when consumers can stand to see a message twice.

A message published while there is no connection has not been sent at all. It waits for the next connection, under either setting, unless the publisher was made with no_connection: :raise.

Without confirms

For messages that can be lost, a publisher can skip confirms:

metrics = client.publisher("metrics", confirms: false)
metrics.publish(sample.to_json, routing_key: "cpu")    # returns once handed over

publish returns true, and submit returns an outcome that is already :sent, as soon as the message has been handed to the connection. Nothing more is ever known of it. A message lost with the connection, or refused by the broker, is lost without a word. A channel the broker closes, over an exchange that does not exist for example, is logged as a warning, because nothing else will say so.

It waits for a connection while there is none, unless made with no_connection: :raise, and while the broker has publishing blocked. mandatory and resend need confirms and raise ArgumentError. max_unconfirmed does not apply.

With no connection

By default a publish made while there is no connection waits for one. To be told at once instead, as Bunny does:

publisher = client.publisher("events", no_connection: :raise)
  • No connection: publish and submit raise ConnectionError.
  • A message still waiting to go out when the connection is lost fails with the ConnectionError instead of going on the next connection.
  • A message sent and not yet answered for fails with UnconfirmedError, as it does by default.
  • A channel the broker closed is opened again on the same connection, and that is waited for.

It works with or without confirms. resend waits for the next connection, so it raises ArgumentError with no_connection: :raise.

Message age

With timestamps on, each message carries the standard timestamp property (seconds) and a timestamp_in_ms header. A consumer reads them back:

message.published_at    # a Time, to the millisecond
message.elapsed         # seconds since it was published, as a Float

Both are nil for a message that carries neither. Setting the two fields costs a few microseconds a message; timestamps: false leaves them out.

Consuming

There are two consumers. Consumer gives you each message and leaves the rest to you. ManagedConsumer runs your handler and looks after concurrency, acknowledging and stopping.

Consumer

consumer = client.consumer("orders", prefetch: 10)
consumer.each do |message|
  process(message.body)
  message.ack
rescue InvalidOrder
  message.reject(requeue: false)
end

each runs the block in the fiber that called it, one message at a time. Nothing is settled for you: a block that returns without ack, nack or reject leaves the message unacknowledged, which is how a message is handed to another fiber to finish later. An exception out of the block ends the loop and is raised from each.

each returns when the consumer goes away, and says why:

Returns When
:stopped consumer.stop was called
:cancelled The broker cancelled the consumer, as when the queue is deleted, or the queue was gone when a lost connection came back
:closed The consumer or its client was closed
:connection_lost The connection was lost and the consumer was made with on_connection_loss: :end

However it ends, messages that had arrived but had not reached the block go back on the queue. stop is safe from any fiber. It does not interrupt a block that is running; each returns when the block finishes.

Consumer option Default Meaning
prefetch 100 Unsettled messages the broker sends at once; nil for no limit
on_connection_loss :wait :wait or :end; in a cluster also :move
on_cancel :end :end or :resubscribe; see below
exclusive true with no queue named The queue is the consumer's own
queue_arguments {} Arguments for the consumer's own queue
arguments {} Arguments for basic.consume

A consumer the broker cancels

The broker cancels a consumer when its queue is deleted. It can also cancel one and leave the queue where it was, as when a quorum queue loses its leader. By default either ends each with :cancelled.

consumer = client.consumer("orders", on_cancel: :resubscribe)

With on_cancel: :resubscribe the consumer asks the broker whether the queue is still there. If it is, the consumer consumes from it again and each carries on. If the broker refuses, it tries again at intervals that grow from one second to thirty, for as long as the queue exists. each returns :cancelled only when the queue is gone.

While the broker goes on refusing, the consumer says so once, as a warning, and logs the attempts after that at debug: a long outage is one warning, not one every thirty seconds.

To hear of it yourself:

consumer.on_cancelled    { |consumer| events.record(:amqp_consumer_cancelled, consumer.queue_name) }
consumer.on_resubscribed { |attempts, consumer| events.record(:amqp_consumer_recovered, consumer.queue_name, attempts) }

on_cancelled is called each time the broker cancels the consumer, whatever on_cancel says, and on_resubscribed each time it is consuming again, with the number of attempts that took and then the consumer. Both run in the fiber that called each or run. With either set, the consumer's own lines about the cancel are logged at debug only.

Nothing is declared along the way, so a queue somebody deleted is not put back. That includes the client: from the cancel until the consumer is consuming again or has found the queue gone, a reconnect leaves that queue and its bindings out of what it declares. A quorum queue that is part way through being deleted can close the connection on a consumer that tries it, and the reconnect would otherwise put the queue back.

Once each has returned :cancelled the queue is the client's to declare again: one made with client.queue comes back on the next reconnect unless you call client.forget(queue).

A message

body, headers, routing_key, exchange
message_id, correlation_id, reply_to, content_type, and the other AMQP properties
redelivered?, persistent?
published_at, elapsed See Message age
ack, nack(requeue: true), reject(requeue: true) Settle it. Only the first of these is sent
settled?, settlement Whether, and how, it was settled
stale? Its connection has gone; the broker has requeued it

ManagedConsumer

consumer = client.managed_consumer("orders", concurrency: 10)
consumer.run do |message|
  process(message.body)
end

run blocks until the consumer goes away, and returns what each would. Handlers run in fibers of their own, up to concurrency at a time. A handler that returns has its message acked. One that raises has it nacked without requeue, so it is dead-lettered if the queue has a dead-letter exchange and discarded if not, and the consumer carries on. A handler's exception never ends run. A handler may settle the message itself, and what it did stands.

ManagedConsumer option Default Meaning
concurrency 1 Handlers running at once
prefetch concurrency Unsettled messages the broker sends at once
ack_on_success true Ack when the handler returns
exception :nack What to do when the handler raises: :ack, :nack or :reject
requeue false For :nack and :reject, whether the message goes back on the queue
drain_timeout 30 Seconds a stop waits for running handlers; nil waits for ever

It takes Consumer's options too.

Stopping is graceful, whether by stop, by close, or by stopping the task that is running run. Nothing new arrives, messages that had not started go back on the queue, and running handlers get drain_timeout to finish. Any still running after that are stopped and their messages requeued. A stop never loses a message.

consumer.on_error { |error, message| ... } is called when a handler raises, before the message is settled. Without it a handler failure is logged as an error. With it the failure is yours to report, and the client logs it at debug only.

A queue of the consumer's own

Given no queue, the consumer declares one that is its alone: exclusive to its connection, and gone when that connection goes.

replies = client.consumer(prefetch: 50)
replies.queue_name                               # the name the broker chose
replies.bind("events", routing_key: "order.*")

After a lost connection the queue is declared and bound again on the next one. Whatever was in it went with the old connection, and a queue the broker named has a new name. on_attach is how to hear of it:

replies.on_attach { |consumer| announce(consumer.queue_name) }

The queue can be named instead, by passing a name with exclusive: true. The same name is then declared again after every reconnect.

  • On a single node this is fine. The old queue is gone by the time the new connection declares it.
  • In a cluster it can fail. An exclusive queue is deleted when its connection closes, and the nodes do not all learn of that at once. A declaration that arrives before the old queue is gone everywhere is refused, and each raises ChannelError with resource_locked? true.

In a cluster, let the broker name the queue. A name it chooses is new each time, so it cannot collide with the old one.

Request and reply (RPC)

client.rpc asks a question over the broker and waits for the answer.

rpc   = client.rpc("orders")                     # an exchange; none means the default
reply = rpc.request("ABC-1", routing_key: "order.price", timeout: 5)
reply.body

request publishes the message with a reply_to and a correlation_id, and returns the Message that comes back with the same id, already acknowledged. Many fibers can ask through one Rpc at once, and each waits only for its own answer.

Whoever answers uses message.reply:

client.consumer("order.price").each do |message|
  message.reply(price_of(message.body), content_type: "application/json")
  message.ack
end

reply publishes to the queue the request named, with its correlation_id. It is sent on the channel the request arrived on and is not confirmed. It returns false for a stale message, which the broker will deliver again. It does not settle the message.

Option of client.rpc Default
timeout 30 Seconds request waits, unless given its own; nil for no limit
reply_via :queue Where answers come back. :queue is the only choice for now
mandatory true A request no queue takes raises ReturnedError at once
persistent false Requests are not written to disk

The other Publisher options are accepted too. request takes the same message properties as publish, other than reply_to and correlation_id.

The answers come back to a queue of the Rpc's own, named by the broker and exclusive to its connection. A request carries its timeout as the message's expiration, so one nobody has picked up by then is dropped by the broker; pass expiration: to say otherwise.

request raises When
NoReplyError No answer came within the timeout
ReplyLostError The connection was lost while the request waited. The reply queue went with it, so the answer can no longer arrive
ReturnedError No queue was bound to take the request
UnconfirmedError The connection was lost before the broker had taken the request
ClosedError The Rpc or its client was closed

After NoReplyError, ReplyLostError or UnconfirmedError the request may or may not have been acted on. Asking again is your decision: the client never sends a request twice.

After a lost connection the Rpc declares a new reply queue on the next one and carries on. A request made while there is no connection waits for one, within its timeout.

When the connection is lost

The client reconnects, with a delay that starts at reconnect_interval, doubles to reconnect_max_interval, and is jittered so a fleet does not come back in one instant. On the new connection it declares its queues, exchanges and bindings again. Then each publisher and consumer attaches itself.

What happens
A declaration or a query in progress Sent again on the new connection
A publish not yet sent Waits, and is sent on the new connection
A publish sent and not answered Raises UnconfirmedError, or is sent again with resend: true
A consumer Consumes again on the new connection
A message delivered on the old connection Stale: the broker requeues it and sends it again. Settling it does nothing, and one not yet handed to the block is dropped
A consumer's own queue Declared and bound again, empty

A consumer made with on_connection_loss: :end does not wait: each returns :connection_lost.

With reconnect_attempts set, the client gives up after that many failures in a row. Everything waiting on it then raises ConnectionError.

When the broker blocks publishing (a memory or disk alarm), publishes wait until it unblocks.

Being told

All of this is logged. An application that wants to count it, or report it somewhere of its own, can be told as well:

client.on_connection_lost  { |error| events.record(:amqp_connection_lost, error) }
client.on_reconnect_failed { |error, attempt| events.record(:amqp_connection_failed, error, attempt) }
client.on_reconnected      { |attempts| events.record(:amqp_recovered, attempts) }
client.on_blocked          { |reason| events.record(:amqp_blocked, reason) }
client.on_unblocked        { events.record(:amqp_unblocked) }
client.on_gave_up          { |error, attempts| events.record(:amqp_gave_up, error, attempts) }
Hook Called With
on_connection_lost Each time the connection is lost, before reconnecting The error
on_reconnect_failed Each time an attempt to reconnect fails, the last before giving up included The error, and how many attempts have failed in a row
on_reconnected Each time there is a connection again, with the topology declared on it. Not for the first connection How many attempts it took
on_blocked When the broker blocks publishing The broker's reason
on_unblocked When it lifts the block
on_gave_up When reconnect_attempts failures in a row end the client The last error, and how many attempts were made

Each hook can be given more than once, and every block is called. Every block is also passed the client as a last argument, which a Cluster uses: the same hooks on a cluster are set on each of its clients, and the last argument says which node it was.

A block runs in the middle of the client's own work, so it should record what it was told and return. It must not wait on the client. A block that raises is logged and otherwise ignored.

An event you have a hook for is yours to report. The client's own line about it drops to debug, so it does not appear beside yours, and what is logged as a warning or an error is your decision:

Without a hook, the client logs At Hook that takes it over
Connection lost; reconnecting warn on_connection_lost
Reconnected info on_reconnected
Broker has blocked publishing warn on_blocked
Broker has unblocked publishing info on_unblocked
Gave up reconnecting error on_gave_up
A cancelled consumer cannot consume again yet warn on_cancelled or on_resubscribed on the consumer
A cancelled consumer is consuming again info on_resubscribed on the consumer
Handler raised error on_error on the ManagedConsumer

A failed attempt to reconnect is only ever logged at debug. What the client still logs as an error on its own account is a hook or handler callback of yours that raised, and a fault inside the client itself.

To register hooks before the first connection, make the client with Client.new, add them, and call connect.

A cluster

A Client is one connection to one node, and everything made through it lives on that node. An application that makes many consumers, each with a queue of its own, puts all those queues on the one node it happens to be connected to. A Cluster holds a Client for every node and shares the load out.

nodes = %w[amqp://rabbit1 amqp://rabbit2 amqp://rabbit3]
Async::RabbitMQ::Cluster.open(nodes) do |cluster|
  replies = cluster.consumer(prefetch: 50)     # on the node with the fewest
  replies.queue_name
end

A cluster has the same methods as a client: queue, exchange, publisher, consumer, managed_consumer. It takes the client's options, which apply to every node.

  • Placement. A new publisher or consumer goes to the connected node with the fewest publishers and consumers already, at random between ties.
  • Declarations are sent to one node and remembered by all.
  • Starting. open returns once every node has answered or failed. Those that failed join in the background. It raises only if no node could be reached, or if one refused the credentials.

When a node goes away, nothing moves by default. A queue lives on a node, and a consumer moved elsewhere has a new, empty queue, so the application has to be ready for that. A consumer chooses with on_connection_loss::

Setting What happens
:wait (default) Stays with its node and consumes again when it is back
:end each returns :connection_lost
:move Goes to the least-loaded connected node. Its own queue is declared and bound again there, empty, and on_attach is called

A consumer that moved does not move back. With nowhere to go, it waits where it is. A publisher always stays with its node and waits for it; one that should publish through whichever node is up belongs on a Client given all the addresses.

The cluster is tested against one broker reached by two routes, not against a real multi-node cluster.

Errors

Everything raised is an Async::RabbitMQ::Error.

Error Meaning
ConnectionError The connection failed or was lost. Has code and text when the broker closed it
ConnectTimeoutError, AuthenticationError, HeartbeatTimeoutError, ProtocolError Kinds of ConnectionError
ChannelError The broker refused a request. Has code, text, and not_found?, access_refused?, resource_locked?, precondition_failed?
PublishError A message was not taken: NackedError, ReturnedError, UnconfirmedError
ClosedError The client, publisher, consumer or Rpc has been closed
NoReplyError, ReplyLostError An Rpc request got no answer: in time, or because the connection was lost
TimeoutError A wait ran out of time
ChannelLimitError The connection has no channel left for another publisher or consumer

A ChannelError from a declaration is the broker's answer and is raised to the caller. The client stays usable.

Logging

The client logs through Console, like the rest of the async stack: a warning when a connection is lost, a line when it is back, an error when a handler raises. Set the level with CONSOLE_LEVEL=debug, or configure Console as you would for any async application.

To send it somewhere else, give the client a logger:. It applies to the client and to every publisher and consumer built on it, and a Cluster passes it to each of its clients.

client = Async::RabbitMQ::Client.open("amqp://localhost", logger: Rails.logger)
logger: What happens
Console (the default), or a Console::Logger Forwarded as it is, with the object that logged and its fields
A stdlib Logger, Rails.logger, or anything with debug, info, warn and error Given one line: the message, the fields, then the exception
nil Nothing is logged

A line written to a plain logger looks like this:

Connection lost; reconnecting (endpoint=amqp://guest@localhost:5672/): Async::RabbitMQ::ConnectionError: Connection to amqp://guest@localhost:5672/ lost

Wherever it goes, Async::RabbitMQ.log_level decides first what the client logs at all. It is :warn unless you change it, so an application running its logger at info is not sent this client's info and debug lines:

Async::RabbitMQ.log_level = :debug   # everything, to troubleshoot a connection
Async::RabbitMQ.log_level = :info    # reconnections and the like as well
Async::RabbitMQ.log_level = :off     # nothing, from any client

The environment variable ASYNC_RABBITMQ_LOG_LEVEL sets it at load. The logger's own level, or CONSOLE_LEVEL, still applies after it.

Three debug lines are not tied to a client and always go to Console: a socket option that could not be set, and a span or metric that could not be recorded.

OpenTelemetry

Spans and metrics are optional, and not loaded unless you ask:

require "async/rabbitmq/open_telemetry"
Async::RabbitMQ::OpenTelemetry.install      # after OpenTelemetry is configured

This needs opentelemetry-api in your bundle, and opentelemetry-metrics-api for the metrics. install(tracer_provider:, meter_provider:) takes either as nil to leave that half off.

Span Kind Around
publish <exchange> producer submit and publish. Ends when the message is written, not when it is confirmed
process <queue> consumer The block of Consumer#each, or the handler of ManagedConsumer#run

The trace context travels in the message's headers, and the process span is a child of the publish span, so a trace crosses the broker. A handler's exception is recorded on its span. Attributes follow OpenTelemetry's messaging conventions.

Metric Type
messaging.client.sent.messages counter One per answer from the broker, with error.type when it was not an ack; without confirms, one per message handed over
messaging.client.operation.duration histogram, s From submit to the broker's answer; not recorded without confirms
messaging.client.consumed.messages counter With error.type when the block or handler raised
messaging.process.duration histogram, s Time in the block or handler
async.rabbitmq.message.age histogram, s Publish to delivery, for messages with a timestamp
async.rabbitmq.client.connections counter Connections made
async.rabbitmq.client.connection.losses counter Connections lost

Tracing is not free. On a development machine, spans and metrics together roughly halved the publish and consume rates of small messages.

What is not here

Left out on purpose. The legacy engine has most of them.

  • Channels. Each publisher and consumer has its own, out of sight.
  • basic.get. Use a consumer.
  • Transactions. Use confirms.
  • A connection pool. One client serves many fibers.
  • A command-line tool. The async-rabbitmq command belongs to the legacy engine.
  • Changing credentials on a live client.
  • Direct reply-to (amq.rabbitmq.reply-to) for RPC. client.rpc uses a reply queue of its own; reply_via: is where the other would be chosen.

Development

The suite runs against a real RabbitMQ, with Toxiproxy for network faults:

docker compose -f spec/docker-compose.yml up -d --wait
bundle exec rspec             # both clients, about nine minutes
bundle exec rspec spec/v1     # this client only

spec_helper starts the containers itself if nothing listens on the configured port, and generates the TLS certificates with spec/docker/gen-certs.sh. Ports and hosts come from .env.

How the client is built is in docs/designs/async-client.md.

Releasing

The version is in lib/async/rabbitmq/version.rb and lib/async_rabbitmq/version.rb, which must agree; a spec checks it. To cut a release: bump both, date the section in CHANGELOG.md, run the suite, then

gem build async-rabbitmq.gemspec
gem push async-rabbitmq-<version>.gem
git tag -a v<version> -m "v<version>" && git push origin v<version>

The gemspec sets rubygems_mfa_required, so publishing needs multi-factor authentication on the RubyGems account.

License

MIT, see LICENSE.