Skip to content

RabbitMQ in Depth ​

"Exchanges then distribute message copies to queues using rules called bindings." — RabbitMQ documentation, AMQP 0-9-1 Model Explained

Summary: RabbitMQ is an Erlang broker in which producers publish to exchanges, bindings copy messages into queues, and the queue type you pick (classic, quorum or stream) decides how safe, how fast and how replayable your messages are. Focus: The AMQP 0-9-1 model, the Erlang/OTP runtime, the three queue types, persistence, confirms and returns, priorities, single active consumer, policies, vhosts and permissions, clustering on Khepri, federation and shovel, alarms and flow control, limits, the 4.0–4.4 changes, and Go (amqp091-go) and Laravel (laravel-queue-rabbitmq) code. Learning goal: Design a RabbitMQ topology that does not lose messages, choose the right queue type, run a three-node cluster through failures and upgrades, and know when RabbitMQ is the wrong tool.

This page is the complete reference for RabbitMQ as a broker, written against the 4.4 documentation (4.4.1 is the newest patch on the release page, published 16 Nov 2026). Most blog posts still describe 3.x, and a lot changed: classic mirroring is gone, Khepri replaced Mnesia, AMQP 1.0 became a core protocol, quorum queues gained priorities, delayed retry and (in 4.4) delayed delivery, and the delayed-message plugin was abandoned. Several neighbours own their detail and are linked instead of re-taught: ack/nack, prefetch and redelivery are in Message Acknowledgment; DLX and x-death handling in Dead-Letter Queue; backoff schedules in Retry, Backoff & Delayed Delivery; exchange design choices in Routing Topologies; worker scaling in Competing Consumers & Scaling; TLS and auth hardening in Messaging Security; and the side-by-side broker table in Broker Comparison. Every command you will type is in the RabbitMQ Cheatsheet.

virtual host "/orders" (permissions, policies and limits are scoped here)Publisher app1 TCP connectionchannel 1 (confirms)channel 2channel Ndirectkey == binding keytopicorders.*.created / orders.#fanoutevery bound queueheadersx-match all / anydefault exchange ""key = queue namepublishexchange+ routing key+ propertiesorders.billingquorum queueorders.auditstream (replayable)cache.node-7classic, exclusivereports.renderclassic, prioritybindingConsumersprefetch 50manual ackReplay readerx-stream-offsetfirst / timepush: basic.consumepoll: basic.getack: basic.ackreject: basic.reject/nack

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why RabbitMQ exists, the trade-off, the analogyWhy RabbitMQ exists
History, AMQP 0-9-1 vs AMQP 1.0Where it comes from
Connections, channels, exchanges, bindings, queuesThe AMQP 0-9-1 model
Erlang processes, schedulers, epmd, the cookieThe Erlang/OTP runtime
Classic vs quorum vs stream, migrationQueue types in depth
Delivery mode, persistence, message size, lazy queuesMessages and persistence
Confirms, returns, acks, TTL/DLX, delay, priority, SAC, policies, vhosts, alarmsMechanics
Clustering, Khepri, partitions, federation, shovelClustering and distribution
AMQP error codesError codes
What changed in 4.0–4.4, which version is supportedRabbitMQ 4.x changes and support policy
rabbitmqctl, rabbitmqadmin, definitions, upgrades, PrometheusOperations
amqp091-go and laravel-queue-rabbitmqGo and Laravel
RabbitMQ vs Kafka vs Redis StreamsBroker differences
Lost messages, poison loops, blocked publishers, ordering with parallelismSolving the classic problems
When not to use it, which queue type for which jobWhen not to use RabbitMQ and Choosing
Monolith to multi-regionIn architecture
Reproduce itLab
Wrong beliefs, a cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The building blocks.

EntityPlain wordsLivesKey properties
ConnectionOne TCP (or TLS) link from an app to a nodeClient ↔ nodeheartbeat, connection_name, blocked/unblocked
ChannelA lightweight session inside a connection; every operation happens on oneInside a connectionprefetch, confirm mode, delivery tags are per channel
ExchangeThe routing table you publish tovhosttype (direct, fanout, topic, headers, plus plugin types), durable, auto-delete, alternate-exchange
BindingA rule "copy messages matching X from exchange E to queue Q"vhostbinding key, header arguments
QueueWhere messages wait for consumersvhost, leader on one nodetype, durable, exclusive, auto-delete, x-arguments
Virtual hostA namespace with its own permissions, policies and limitsclusterdefault_queue_type, limits
PolicyA regex that injects arguments into matching queues and exchanges at runtimevhostpattern, definition, priority, apply-to

The three queue types (RabbitMQ 4.x).

ClassicQuorumStream
ReplicatedNo (mirroring removed in 4.0)Yes, Raft, 3 members by defaultYes, leader + replicas
ReadingDestructive (ack deletes)DestructiveNon-destructive, by offset
Durable / exclusive / non-durableAll (non-durable non-exclusive denied by default since 4.3)Durable onlyDurable only
Poison message handlingNodelivery-limit, default 20 since 4.0No
Prioritiesx-max-priority 1–255 (advice: 2–4)Always on, 0–31, strict since 4.3No
Best forTemporary, exclusive, reply queues, low latencyLong-lived, critical work queuesFan-out, replay, huge backlogs

The safety switches.

SwitchWithout itWith it
Durable queueQueue gone after restartQueue definition survives
delivery_mode = 2 (persistent)Message may live only in memoryMessage written to disk
Publisher confirmsA successful Publish call means "written to my socket"basic.ack means "the broker took responsibility"
mandatory = trueUnroutable messages vanish silentlyThey come back as basic.return (312 NO_ROUTE)
Manual ack + prefetchAuto-ack loses work when a consumer diesUnacked deliveries are requeued
Quorum queueOne node holds the only copyA majority has it before the confirm

What changed recently.

VersionChange you must know
3.12Lazy mode ignored; classic queues behave "lazy-like" by default
4.0 (Sep 2024)Classic mirroring removed; AMQP 1.0 core; quorum delivery-limit default 20; CQv1 removed; max_message_size default 16 MiB; Local Random Exchange
4.2 (Oct 2025)Khepri default for new clusters; CQv2 default
4.3 (Apr 2026)Khepri only (Mnesia and partition handling strategies removed); transient non-exclusive queues and global QoS denied by default; quorum strict priorities, delayed retry, consumer timeout; delivery-limit counts failed deliveries only
4.4 (Oct 2026)Quorum queue delayed messages (x-opt-delivery-time); AZ-aware member placement; delayed-message exchange plugin no longer maintained

Why RabbitMQ exists ​

Services need to hand work to each other without both being up at the same moment, and they need the broker to decide where a message goes so the sender does not have to know every receiver. RabbitMQ's answer is a smart broker with simple consumers: the broker routes, stores, tracks every delivery and redelivers on failure. Kafka's answer is the opposite: a simple log with smart consumers that track their own position (see Kafka in Depth).

Smart broker (RabbitMQ queues)Durable log (Kafka, RabbitMQ streams)
Broker routes by rules (exchanges, bindings)Producer picks a topic/partition
Per-message ack, redelivery, TTL, priority, DLXOffsets; reprocessing means moving the offset
Message deleted after ackMessage kept until retention expires
Great for tasks and commandsGreat for event history and replay
Throughput bounded by per-message bookkeepingThroughput bounded by sequential disk I/O

The analogy used on this page. RabbitMQ is a post office. Letters are handed in at the counter (the exchange); the clerk reads the address (routing key), checks the rules on the wall (bindings) and drops a copy in every matching pigeonhole (queue). Registered mail with a receipt (publisher confirm) tells the sender the office took custody. Carriers sign for each letter (consumer ack); a carrier who disappears without signing sends the letter back to the pigeonhole. A stream is a ledger bolted to the wall that anyone can read from any page without removing anything.

Three common misunderstandings, up front ​

  • "Durable queue means my messages survive a restart." Only persistent messages in a durable queue survive, and only once the broker has confirmed them. Exchange and queue durability do not select the delivery mode of individual messages.
  • "A cluster replicates my queues." It replicates metadata (users, vhosts, exchanges, bindings, policies). Messages are replicated only in quorum queues and streams. A classic queue lives on one node.
  • "I set an HA policy, so I am safe." ha-mode mirroring was deprecated in 2021 and removed in 4.0; after upgrading, those policy keys "will have no effect".

Where it comes from ​

RabbitMQ was first released in 2007 by Rabbit Technologies, a joint venture of LShift and CohesiveFT, and later passed through SpringSource/VMware, Pivotal and VMware again (secondary source: Wikipedia); the documentation footer today reads "Copyright © 2005-2026 Broadcom". It is written in Erlang, the language Ericsson built for telephone switches, which is why a node can hold hundreds of thousands of lightweight processes and why clustering uses Erlang distribution.

Its native protocol is AMQP 0-9-1, whose defining idea is that the application declares the routing:

Applications can declare their own entities and bindings through the protocol, so routing is part of application integration code.

That is why every client API is mostly ExchangeDeclare, QueueDeclare and QueueBind. AMQP 1.0, a different OASIS standard despite the name, became a core protocol in RabbitMQ 4.0 (the former plugin no longer controls its availability), and the team now recommends it for new applications. This page teaches 0-9-1 because amqp091-go, php-amqplib and the Laravel package speak it, and notes where AMQP 1.0 gets features first (deferred messages, filter expressions on streams).

The AMQP 0-9-1 model ​

Connections and channels Must-know ​

In plain words: open one long-lived TCP connection per process and many channels inside it; a channel is the thing you actually publish and consume on.

Common misunderstanding: "A channel per message is fine, channels are cheap." Channels are lightweight compared with connections, but opening one costs a network round trip and several Erlang processes on the node. Opening a channel per publish (the go/before snippet) is a leak pattern the docs call channel churn.

Definition: A connection is a TCP connection authenticated against a vhost. Channels are multiplexed over it with channel numbers; max_channels_per_connection defaults to 2047, and the limits guide recommends 16–128. Heartbeats detect dead peers; the server suggests 60 seconds. Protocol errors are scoped: a soft error (404, 406, 403, 405) closes the channel, a hard error (320, 501–541) closes the connection.

text
     app process                                      rabbit@node-1
1    TCP connect :5672, SASL PLAIN, vhost /orders  -> connection.open-ok
2    channel.open (1)   publisher, confirm.select  -> channel 1 in confirm mode
3    channel.open (2)   consumer, basic.qos 50     -> channel 2, prefetch 50
4    ch1 basic.publish x=orders.events key=orders.eu.created
5    ch2 basic.deliver tag=1 ... tag=50, then waits for acks
6    ch2 queue.declare orders.billing with other args -> 406, channel 2 closed
7    ch1 still fine (soft error closes one channel, not the connection)

Real scenarios: a PHP-FPM app that opens a connection per HTTP request exhausts file descriptors on the broker; a Go service acknowledges a delivery tag on a different channel and gets "unknown delivery tag" (406); a firewall that drops idle TCP sessions after 5 minutes kills connections that have heartbeats disabled (the Laravel package defaults heartbeat to 0).

KnobWhereDefaultAdvice
Heartbeatclient + heartbeat in rabbitmq.confserver suggests 60 s10–30 s behind load balancers
max_channels_per_connectionrabbitmq.conf204716–128
connection_name client propertyclientnoneAlways set; it appears in the UI and logs
Connections per vhost / userset_vhost_limits, set_user_limitsunlimitedCap them to contain runaway clients

How to use it: one connection for publishing and one for consuming (alarms block publishing connections, so a shared connection also stalls your consumer), one channel per goroutine or worker, and always name connections.

Exchanges Must-know ​

In plain words: an exchange is a routing table; you publish to it with a routing key and it decides which queues get a copy.

Common misunderstanding: "I publish to a queue." You always publish to an exchange. Publishing "to a queue" means publishing to the default exchange "", which has an implicit binding from every queue's name.

Definition and types:

TypeRoutes byExample bindingTypical use
directExact routing key matchkey invoice.paidCommands, work queues
fanoutIgnores the key; every bound queue(none)Broadcast, cache invalidation
topicDot-separated words, * = one word, # = zero or moreorders.*.created, orders.#Events by domain and region
headersHeader values, x-match = all or any (all-with-x, any-with-x include x- headers)format=pdf, lang=faRouting on several attributes
Default ""Key = queue nameimplicit"Send to this queue"
x-local-random (4.0+)One random local queue—Low-latency request-reply with exclusive queues
x-modulus-hash (built in since 4.3, stable routing in 4.4)hash(key) mod Nbinding key ignoredSharding with per-key order
x-consistent-hash (plugin)Hash ring weighted by binding key"10"Sharding

The amq.* exchanges (amq.direct, amq.topic, amq.fanout, amq.headers, amq.match) are pre-declared per the spec. Exchange durability only concerns the exchange surviving a restart; it says nothing about messages. A topic binding key may contain at most two # wildcards (hard limit).

Real scenarios: an order service publishes orders.eu.created once and billing, email and analytics each bind their own queue; a cache-invalidation fanout reaches every app node's exclusive queue; a document renderer binds on headers format=pdf AND lang=fa.

The design side (one exchange per bounded context, naming, content-based routing) is in Routing Topologies; this page owns the mechanics.

Bindings, exchange-to-exchange bindings and alternate exchanges Important ​

In plain words: a binding is one line on the routing table. Exchanges can also bind to other exchanges, and an exchange can name a fallback for messages nothing matched.

Common misunderstanding: "If no queue is bound, RabbitMQ keeps the message until one appears." It does not. A message that routes nowhere is dropped, returned (if mandatory) or sent to the alternate exchange. The publisher still gets a basic.ack, because completing routing, including finding no destination, is enough to confirm that publication.

Definition: queue.bind(queue, exchange, key, args) and exchange.bind(destination, key, source) (a RabbitMQ extension). The alternate-exchange argument (or policy key) names an exchange that receives anything the primary could not route. Bindings to durable queues from durable exchanges are durable.

text
     publisher                        orders.events (topic, AE = orders.unroutable)
1    publish key=orders.eu.created -> binding orders.*.created -> orders.billing
2                                     e2e binding orders.eu.* -> cache.invalidate (fanout) -> 3 node queues
3    publish key=refund.requested  -> no binding matches -> orders.unroutable queue (AE)
4    publish to exchange without AE, mandatory=true -> basic.return 312 NO_ROUTE, then basic.ack

How to use it: give every important exchange an alternate exchange with a queue behind it and alert on its depth; set mandatory on publishers that must know. See go/topology in Go.

Queues and their properties Must-know ​

In plain words: a queue is a named buffer. Its type and its flags are fixed when you first declare it; later declarations must match exactly.

Common misunderstanding: "Declaring a queue again with new arguments updates it." It fails with 406 PRECONDITION_FAILED and closes the channel. Change runtime-tunable arguments with a policy; change the type by migrating.

Definition:

PropertyMeaningNotes (4.4 docs)
NameUp to 255 bytes of UTF-8; amq. prefix reserved (403 ACCESS_REFUSED)Empty name = server-named (amq.gen-...)
DurableDefinition survives a restartQuorum queues and streams are always durable
ExclusiveUsed by one connection, deleted when it closesClassic only; prefer broker-generated names
Auto-deleteDeleted when its last consumer goes awayA queue that never had a consumer is never auto-deleted
Arguments (x-arguments)x-queue-type, x-message-ttl, x-expires, x-max-length, x-overflow, x-dead-letter-exchange, x-max-priority, x-single-active-consumer, x-delivery-limit, x-quorum-initial-group-size, x-max-age, ...Prefer policies for anything that may change
Property equivalenceRedeclare must match406 on mismatch; quorum_queue.property_equivalence.relaxed_checks_on_redeclaration helps migrations

Since 4.3, non-durable non-exclusive classic queues are rejected unless every node sets deprecated_features.permit.transient_nonexcl_queues = true; the go/before snippet's durable=false queue would fail on a default 4.3+ broker. Use a durable queue, an exclusive queue, or a durable queue with x-expires.

The Erlang/OTP runtime ​

In plain words: a RabbitMQ node is one Erlang virtual machine (BEAM). Every connection, channel and queue replica is an Erlang process, a lightweight green thread with its own heap and mailbox; the VM runs them on a few OS scheduler threads.

Common misunderstanding: "More queues = more throughput automatically." A single queue replica cannot execute its queue process on several CPU cores simultaneously. One hot queue cannot use 16 cores; ten queues can. That is the reason for sharding exchanges and super streams.

PieceWhat it isKnob or port
BEAM VMRuns RabbitMQ code; preemptive scheduling of processesRABBITMQ_SERVER_ADDITIONAL_ERL_ARGS
SchedulersOne OS thread per detected core (CPU quotas respected since Erlang 23)+S 4:4
Erlang process limitAbout 1 million by default+P
Atom limitRabbitMQ uses 5 millionrelevant with very many quorum queues
epmdResolves node names to distribution portsport 4369
Erlang distributionNode-to-node and CLI trafficport 25672 (AMQP port + 20000)
Erlang cookieShared secret; every node and CLI must have the same one.erlang.cookie, mode 600
Erlang version4.4 supports Erlang 27, 28 and 29; 4.0 required 26.2rabbitmq-diagnostics erlang_version
text
     BEAM VM on rabbit@node-1 (4 schedulers)
1    process <0.900.0>  connection reader for app "billing"
2    process <0.905.0>  channel 1 (publisher)  -> routes via exchange (no process per exchange)
3    process <0.910.0>  quorum queue orders.billing leader (Ra server)
4    process <0.911.0>  classic queue cache.node-7
5    scheduler 1..4 run whichever processes have messages in their mailbox
     -> a hot queue process saturates one scheduler; others stay idle

The practical consequences: memory is per-process heaps plus binaries (so rabbitmq-diagnostics memory_breakdown is the tool, not top), crash dumps (erl_crash.dump) are the post-mortem artefact, and the Erlang version is part of every upgrade plan.

Queue types in depth ​

Classic queues (CQv2) Must-know ​

In plain words: the original single-node queue: fast, flexible (exclusive, auto-delete, priorities), but one node holds the only copy.

Common misunderstanding: "Classic queues keep everything in RAM; I need lazy mode for big backlogs." Since 3.12 lazy mode is ignored, and modern classic queues write to disk early: the queue keeps a bounded working set in memory, with up to 2048 messages depending on consumption speed. The 4.3 release notes go further: declaring with x-queue-mode (any value) or x-queue-version: 1 now fails.

Definition: Classic queues have had no replicated variant since 4.0. Storage is version 2 (CQv1 removed): a per-queue index of segment files, a per-queue message store for small messages and a shared per-vhost message store for larger ones (4.4 writes new shared-store files in .sqs format and cannot be downgraded to 4.3). Both persistent and transient messages are written to disk except when the queue or message is transient, messages are smaller than the embedding threshold (4096 bytes), or the queue is short.

Use classic forAvoid classic for
Exclusive reply queues, per-connection stateAnything that must survive a node loss
Temporary queues with high churnLong-lived critical work queues
Lowest latency, data safety not a priorityPoison-message protection (no delivery limit)
Priority queues with modest priority countsAt-least-once dead-lettering (quorum only)

Quorum queues (Raft) Must-know ​

In plain words: a quorum queue keeps a copy on three nodes (by default) and only confirms a message once a majority has it, so losing one node loses nothing confirmed.

Common misunderstanding: "Quorum queues are just better classic queues; use them for everything." Temporary reply queues, minimum-latency workloads, very large backlogs and many independent readers can be poor fits. Confirms and manual acks are needed to use the safety properties. Review topology when the number of quorum queues approaches thousands, rather than assuming metadata is free.

Definition: A majority is floor(N/2)+1 members. Each queue is a Raft group (implemented by the Ra library): one leader, followers on other nodes, every operation appended to a log (WAL, flushed into segment files, compacted with snapshots). Declared with x-queue-type: quorum, which is a declaration-time choice rather than a policy setting. Members default to 3 (x-quorum-initial-group-size), never two on one node.

Publisherconfirm modenode rabbit-1: LEADERWAL (fsync) then segment files414243term 7, commit index 42rabbit-2: followerappends 43, replies OK2 of 3 = majorityrabbit-3: followerslow or down: not neededcatches up from the log later1 publish #432 append3 ack4 basic.ackIf rabbit-1 dies: rabbit-2 and rabbit-3 hold an election,the member with the most complete log becomes leader (term 8),unconfirmed publishes may be lost: the publisher re-sends themthe leader assigns deliveries to consumers
text
     publisher           leader rabbit-1          rabbit-2            rabbit-3
1    publish #43 ->      append 43 to log
2                        replicate ------------>  append 43           (network slow)
3                        <---------------------   OK: 2 of 3 = majority
4    <- basic.ack 43     commit 43, ready for delivery
5                        node dies
6                                                 election: rabbit-2 has 43, wins term 8
7    publishes continue to rabbit-2; rabbit-3 catches up from the log, no special sync step
Cluster nodesNode failures tolerated (from the docs)Partition tolerant
10not applicable
20no
31yes
52yes
73yes

Features that only quorum queues have: poison message handling (delivery-limit, default 20 since 4.0; since 4.3 it counts failed deliveries, so basic.reject with requeue=true counts and basic.nack with requeue does not), at-least-once dead-lettering (dead-letter-strategy: at-least-once plus overflow: reject-publish), consumer timeout per queue (4.3), delayed retry (x-delayed-retry-type, -min, -max, linear back-off, 4.3), delayed messages (x-opt-delivery-time, 4.4), strict priorities 0–31 (4.3), and AZ-aware member placement (4.4). They do not support non-durable or exclusive queues, global QoS, server-named queues or reject-publish-dlx.

Replication increases latency and disk work. Fast storage, appropriate prefetch and small messages help throughput; adding replicas increases the cost of writes, and the documentation advises against groups above 7 members. If a majority of the stored replicas is permanently lost, a healthy metadata cluster cannot reconstruct the queue data: recovery requires a separate data-recovery strategy or recreating the queue.

Streams and super streams Important ​

In plain words: a stream is a replicated append-only log inside RabbitMQ; consumers read from an offset and nothing is deleted on ack.

Common misunderstanding: "Streams replace queues; RabbitMQ is now Kafka." Streams serve different workloads from task queues. They have no TTL, no DLX, no priorities, no poison handling and no per-message routing after the write.

Definition: declared with x-queue-type: stream; retention by max-age (7D, 12h) and max-length-bytes, evaluated per segment. Over AMQP 0-9-1 a consumer must set a prefetch and ack (ack is flow credit, not deletion) and chooses x-stream-offset: first, last, next, a numeric offset, a timestamp or an interval. The native stream protocol (port 5552) is the preferred throughput-oriented interface and adds server-side offset tracking, publisher deduplication (producer name + publishing ID), single active consumer for streams and Bloom-filter based filtering; 4.1 added AMQP 1.0 filter expressions and 4.2 SQL filter expressions. Super streams (3.11+) partition one logical stream into several streams behind a direct exchange (rabbitmq-streams add_super_stream invoices --partitions 3).

text
     producer        stream orders.audit (offsets)          reader A (projection)   reader B (audit job)
1    append ->       0 1 2 3 4 5 6 ...
2                                                            offset=first: 0,1,2...  
3                                                                                     offset=1h ago: 4,5,6
4    ack from A or B deletes nothing; retention (7D / 20 GB) trims whole segments later

Real scenarios: rebuilding a read model after a bug fix, one event feeding 50 consumer applications without 50 queue copies, an audit trail kept for a week, a backlog of tens of millions of messages.

Choosing and migrating between queue types Important ​

The type is fixed at declaration, so migration is a new queue plus a move. Options the docs describe: set default_queue_type = quorum per vhost or node-wide so new queues are quorum; use relaxed_checks_on_redeclaration so old apps that still declare "classic" do not crash; for 3.13 clusters with mirrored queues, use a blue-green migration (a new 4.x cluster, rabbitmqadmin v2 commands, a shovel or federation to drain the old one). In-place: create orders.billing.v2 as quorum, bind it alongside the old queue, move consumers, let the old queue drain, unbind and delete.

StepCommand or action
New vhost defaults to quorumrabbitmqctl add_vhost orders --default-queue-type quorum
Old clients still say classicquorum_queue.property_equivalence.relaxed_checks_on_redeclaration = true
Find mirroring leftoversrabbitmqctl clear_policy keys or delete_policy_definition_keys for ha-*
Drain old queue to newdynamic shovel from queue to queue
Verifyrabbitmq-queues check_if_node_is_quorum_critical before stopping nodes

Messages and persistence ​

Message properties and delivery mode Must-know ​

In plain words: a message is a body plus a small set of standard properties plus free-form headers; delivery_mode 2 asks for it to be written to disk.

Common misunderstanding: "Persistent means durable end to end." Persistence is asynchronous until the required storage work completes. A crash in that interval can lose unconfirmed data; the publisher needs a confirm to know which messages crossed the durability boundary.

Definition:

PropertyPurpose
delivery_mode1 transient, 2 persistent (quorum queues and streams persist everything anyway)
content_type, content_encodingHow to decode the body
message_idYour idempotency key (Idempotent Consumers)
correlation_id, reply_toRequest-reply (Request-Reply)
expirationPer-message TTL in ms, as a string
priority0–255 (classic, capped by x-max-priority), 0–31 (quorum)
timestamp, type, app_id, user_idMetadata; user_id is validated against the connection's user
headersApplication headers, traceparent, schema version, x-opt-delivery-time

Size: max_message_size defaults to 16 MiB since 4.0 (was 128 MiB) and cannot exceed 512 MiB; the 4.0 notes recommend a blob store plus an ID in the message (the claim-check pattern in Message Design).

Mechanics ​

1 publishpersistent, mandatory2 exchangematch bindingsno matchalternate exchange, orbasic.return, or dropped3 queue(s)stored / replicated4 basic.ack to publisherbroker is now responsible5 deliverif unacked < prefetch6 consumer processesdelivery tag per channelack: message deletedreject/nack requeueor channel closeddead-letter triggersreject/nack with requeue=false; TTL expired;max-length overflow (drop-head); quorumdelivery-limit exceeded (default 20)DLX re-publishes to a parking queuex-death header: queue, reason, count, timeTTL

Publisher confirms, mandatory and returns Must-know ​

In plain words: in confirm mode every publish gets a sequence number and the broker later says ack (I have it) or nack (I could not take it). Without confirms you are guessing.

Common misunderstanding: "A confirm means a consumer processed it." The broker can confirm while every consumer is offline. Consumer processing and its acknowledgement are a separate leg of the protocol.

Definition: confirm.select puts a channel in confirm mode; the broker sends basic.ack (possibly with multiple=true covering every tag up to N) or basic.nack on internal queue failures. Acceptance must complete at each routed queue. Persistent messages in durable queues require stable storage; quorum queues require majority replication. If mandatory is set and nothing matches, basic.return arrives before the ack.

text
     publisher (confirm mode)                      broker
1    publish seq=1 key=orders.eu.created  ->       routed to orders.billing (quorum)
2    publish seq=2 key=orders.us.created  ->       routed
3    publish seq=3 key=nobody.listens, mandatory -> no route
4                                           <-    basic.return 312 NO_ROUTE (seq 3)
5                                           <-    basic.ack seq=3
6                                           <-    basic.ack seq=2 multiple=true  (1 and 2 safe)
7    connection drops before an ack for seq=4 -> outcome unknown: re-publish, consumer dedups
StrategyThroughputComplexity
Publish, wait for each confirmLowest (one round trip per message)Trivial
Publish a batch, wait for allGoodRe-publish the whole batch on failure
Async: track outstanding tags, handle acks in a listenerBestBookkeeping of tag → message
Transactions (tx.select)Much slower; not recommended—

How to use it: always confirm business messages; treat a timeout or connection loss as "unknown" and re-publish with the same message_id (at-least-once, see Delivery Guarantees). Go: go/confirms. Laravel: ConfirmedPublisher.php (the queue package does not enable confirms).

Consumer acknowledgements and prefetch (pointer) Must-know ​

Consumers use manual acks (basic.ack, basic.nack, basic.reject) and a per-consumer prefetch (basic.qos, global=false; global QoS is denied by default since 4.3). Unacked deliveries return to the queue when the channel closes, with redelivered=true. The default delivery acknowledgement timeout is 30 minutes (consumer_timeout = 1800000); since 4.3 it is evaluated by quorum queues only. The full treatment, including choosing a prefetch value and multiple acks, is in Message Acknowledgment and Backpressure & Flow Control.

TTL, dead-lettering and the delivery limit (pointer) Important ​

x-message-ttl (per queue), expiration (per message), x-expires (unused queue) and max-length/max-length-bytes with x-overflow (drop-head, reject-publish, reject-publish-dlx on classic) bound how long and how many messages wait. A message is dead-lettered to x-dead-letter-exchange when it is rejected with requeue=false, expires, overflows with drop-head, or exceeds a quorum queue's delivery-limit; RabbitMQ adds an x-death header. Quorum queues can dead-letter at-least-once; classic queues and the default strategy are at-most-once. Parking-lot design and replay tools live in Dead-Letter Queue.

text
     consumer                     orders.billing (quorum, delivery-limit 10, DLX orders.dlx)
1    deliver tag=7 (delivery-count 0)
2    basic.reject requeue=true   -> delivery-count 1, back in queue
3    ... 9 more failed attempts
4    11th failure                -> dead-lettered to orders.dlx with x-death [reason=delivery_limit]
5    basic.nack requeue=true on 4.3+ would NOT increment delivery-count -> possible infinite loop

Delayed delivery in RabbitMQ 4.x Important ​

In plain words: RabbitMQ has three ways to say "deliver this later", and the famous plugin is no longer one of them.

Common misunderstanding: "Install rabbitmq_delayed_message_exchange." Its README now opens with "Team RabbitMQ no longer maintains this project", because it depends on Mnesia, which 4.3 removed. It also stored delayed messages on one node only.

MethodVersionHowLimits
TTL + DLX wait queueallPublish to a queue with x-message-ttl and x-dead-letter-exchange; nobody consumes itExpiry only at the head: one wait queue per delay value
x-opt-delivery-time header4.4, quorum queuesUnix ms in a long header; routing and replica placement precede the delivery deadline and the message becomes visible at that timeCounts toward length limits
Quorum delayed retry4.3x-delayed-retry-type (all, failed, returned), -min, -max: delay = min(min_delay * delivery_count, max_delay)Linear, not exponential
Deferred messages4.4, AMQP 1.0 onlyConsumer defers with a token, claims laterNot available over 0-9-1

Schedules, jitter and Laravel backoff are taught in Retry, Backoff & Delayed Delivery.

go
// Package main shows the two supported ways to delay a message on RabbitMQ 4.x:
// (1) a per-delay wait queue with x-message-ttl that dead-letters back to the
// work exchange (works on every version), and (2) the x-opt-delivery-time
// header that quorum queues honour starting with RabbitMQ 4.4.
// The community delayed-message exchange plugin is no longer maintained.
package main

import (
	"context"
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

// declareWaitQueue creates a retry exchange and "<queue>.wait.<ttl>": nobody
// consumes the wait queue, messages expire after ttl and are dead-lettered to
// the work exchange. Because they entered through a topic exchange bound with
// "#", they keep their original routing key and route normally on the way back.
func declareWaitQueue(ch *amqp.Channel, queue string, ttl time.Duration) (string, error) {
	if err := ch.ExchangeDeclare("orders.retry", "topic", true, false, false, false, nil); err != nil {
		return "", err
	}
	name := queue + ".wait." + ttl.String()
	if _, err := ch.QueueDeclare(name, true, false, false, false, amqp.Table{
		"x-queue-type":           "quorum",
		"x-message-ttl":          ttl.Milliseconds(),
		"x-dead-letter-exchange": "orders.events",
		// no x-dead-letter-routing-key: the original key is kept
	}); err != nil {
		return "", err
	}
	return name, ch.QueueBind(name, "#", "orders.retry", false, nil)
}

func publishAfterTTL(ctx context.Context, ch *amqp.Channel, key string, body []byte) error {
	return ch.PublishWithContext(ctx, "orders.retry", key, true, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		Body:         body,
	})
}

func publishAt(ctx context.Context, ch *amqp.Channel, key string, at time.Time, body []byte) error {
	// RabbitMQ 4.4+: the quorum queue stores and replicates the message at once
	// and makes it visible at the given Unix time in milliseconds.
	return ch.PublishWithContext(ctx, "orders.events", key, true, false, amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		Headers:      amqp.Table{"x-opt-delivery-time": at.UnixMilli()},
		Body:         body,
	})
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	wait, err := declareWaitQueue(ch, "orders.billing", 30*time.Second)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("wait queue:", wait)
	if err := publishAfterTTL(ctx, ch, "orders.eu.created", []byte(`{"retry":1}`)); err != nil {
		log.Fatal(err)
	}
	if err := publishAt(ctx, ch, "orders.eu.created", time.Now().Add(15*time.Minute), []byte(`{"remind":true}`)); err != nil {
		log.Fatal(err)
	}
}

Priority queues Good to know ​

In plain words: higher-priority messages jump the line inside one queue.

Common misunderstanding: "Set priority on any queue." Classic queues need x-max-priority at declaration (not through a runtime policy), messages without a priority count as 0, and each level is an internal sub-queue; 2–4 levels are generally sufficient. Quorum queues (4.3+) always support 0–31, treat a missing priority as 4, and are strict: continuous urgent traffic can starve low-priority work. Prefetch also limits the effect: messages already in a consumer's prefetch window are not reordered. Separate queues per class are often clearer.

Single active consumer and exclusive consumers Important ​

In plain words: many consumers subscribe, only one receives at a time, and another takes over automatically when it dies; that gives strict order with a hot standby.

Common misunderstanding: "exclusive=true on basic.consume does the same." An exclusive consumer refuses other consumers instead of queueing them, and failover is your job; quorum queues even "ignore the exclusive flag". SAC (x-single-active-consumer: true, declaration only, not a policy) works on classic and quorum queues; streams have their own SAC in the stream protocol.

text
     consumer A          queue ledger.postings (SAC)          consumer B
1    basic.consume ->    A active
2                        B registered, waiting          <-    basic.consume
3    A crashes           unacked deliveries requeued; B becomes active
4                        B receives in order from where A stopped (redelivered=true for A's unacked)

The x-modulus-hash exchange plus N SAC queues gives "ordering per key, parallel across keys", which Ordering & Partitioning and Competing Consumers discuss.

Policies and operator policies Must-know ​

In plain words: a policy is a regex plus a JSON block of settings; RabbitMQ applies it to every matching queue or exchange now and in the future, without redeclaring anything.

Common misunderstanding: "Two matching policies combine." RabbitMQ selects a single user policy; the highest priority wins, ties must not be relied on. The exception is an operator policy, which is merged with the user policy and the more conservative value wins (operator max-length 50 vs user 100 → 50).

Definition: name, pattern, definition, priority, apply-to (queues, classic_queues, quorum_queues, streams, exchanges, all). Policies can set TTL, length limits, DLX, delivery-limit, dead-letter-strategy, federation and stream retention; they cannot set queue type, priority count, exclusivity or SAC. Operator policies are limited to a safe subset (delivery-limit, expires, max-length, max-length-bytes, message-ttl, overflow, max-in-memory-*, target-group-size ...) and can be pre-seeded for new vhosts.

bash
# Every queue whose name starts with "qq." gets a delivery limit and a DLX
rabbitmqctl set_policy --vhost orders --apply-to quorum_queues --priority 10 \
  qq-safety "^qq\." '{"delivery-limit": 50, "dead-letter-exchange": "orders.dlx"}'
# Platform team caps everything in the vhost, whatever developers set
rabbitmqctl set_operator_policy --vhost orders --apply-to queues limits ".*" \
  '{"max-length": 1000000, "expires": 604800000}'

Virtual hosts, users and permissions Important ​

In plain words: a vhost is a namespace; users get three regexes per vhost saying what they may create, write to and read from.

Common misunderstanding: "Vhosts isolate resources." A vhost is a namespace and permission boundary, not a dedicated machine; they share nodes, memory and disks. Limits (max-connections, max-queues) help, but a noisy vhost can still trigger a cluster-wide alarm.

PermissionCovers (AMQP 0-9-1)
configureexchange.declare/delete, queue.declare/delete
writebasic.publish to an exchange; queue.bind on the queue side
readbasic.consume, basic.get, queue.purge; queue.bind on the exchange side
Topic permissionsRegex on routing keys for topic exchanges
User tagsadministrator, monitoring, policymaker, management (UI/HTTP API access)

The default guest/guest user "can only connect from localhost" (loopback_users); create real users or OAuth 2 / LDAP / x.509 auth. Hardening belongs to Messaging Security.

Flow control, memory and disk alarms Must-know ​

In plain words: when a node runs low on RAM or disk it stops reading from publishing connections until it recovers; when queues just cannot keep up, it slows publishers down a little (flow).

Common misunderstanding: "My publisher hangs, RabbitMQ is broken." Resource protection pauses publishing connections while consumer-only connections can continue draining. One node crossing a watermark can activate that protection throughout the cluster.

MechanismTriggerEffectKnob
Credit flowA queue or channel falls behindConnection state flow, many short blocks per secondnone
Memory alarmNode memory above watermark (about 60% of RAM by default)Publishing connections blockedvm_memory_high_watermark.relative, .absolute (use absolute in containers)
Disk alarmFree disk below limit (50 MB by default)Publishing connections blockeddisk_free_limit.absolute, .relative (docs suggest about RAM size)
File descriptorsNear the OS limitNew connections refusedulimit -n
text
     publisher conn          rabbit@node-2 (memory 61% > 60%)        consumer conn
1    publish ...             memory alarm set, cluster-wide
2    state=blocked           socket not read; connection.blocked sent  deliveries continue
3    Publish() call blocks (TCP back pressure); confirms stop arriving
4                            consumers drain, memory falls -> alarm cleared, connection.unblocked
5    publishing resumes; unconfirmed messages are re-published by the app if they timed out

How to use it: separate publishing and consuming connections, subscribe to connection.blocked (NotifyBlocked in Go), put a timeout on confirms, and alert before the alarm. The theory of back-pressure is in Backpressure & Flow Control.

Clustering and distribution ​

Cluster EU (one LAN, low latency)Cluster US (separate cluster)eu-1Khepri memberQQ orders: leaderstream replicaeu-2Khepri memberQQ orders: followerstream replicaeu-3Khepri memberQQ orders: followerstream replicaErlang distribution: 4369 epmd, 25672, same cookiemetadata needs a majority (2 of 3) onlineexchange orders.events (upstream)local publishers, local consumersqueue reports.exportsource of a dynamic shovelus-1, us-2, us-3own Khepri, own users, own quorum queuesno shared Raft group with EUfederated exchange orders.eventspolicy federation-upstream-setexchange analytics.inshovel destinationfederation linkAMQP over WAN, tolerates outagesshovelconsume, re-publish, ack

Clustering, Khepri and partitions Must-know ​

In plain words: a cluster is three, five or seven nodes on one LAN that share all metadata; clients can use any queue through any node.

Common misunderstanding: "Two nodes give me redundancy." With two nodes nothing survives a split: quorum needs a majority. The clustering guide stresses an odd number of nodes and strongly discourages two-node clusters.

Definition: All metadata (users, vhosts, exchanges, bindings, policies, runtime parameters) is replicated to every node; queue data only for quorum queues and streams. Nodes are "equal peers". The metadata store is Khepri, built on Raft like quorum queues: default for new clusters in 4.2, the only store in 4.3, where metadata availability requires an online majority and the old cluster_partition_handling strategies (pause_minority, autoheal) were removed. Nodes find each other through peer discovery (classic config, DNS, Kubernetes, AWS, Consul, etcd) and authenticate with the Erlang cookie.

text
     3-node cluster, network splits {rabbit-1} | {rabbit-2, rabbit-3}
1    Khepri: majority side {2,3} keeps accepting declarations, policy changes, user changes
2    rabbit-1 alone: metadata changes fail; its quorum queue leaders step down
3    quorum queues with members on 2 and 3 elect leaders there and keep running
4    classic queue whose only copy is on rabbit-1: unavailable from the majority side
5    link heals: rabbit-1 follows Raft, catches up, no manual "partition recovery"
OperationCommand
Statusrabbitmqctl cluster_status, rabbitmq-diagnostics check_running
Joinrabbitmqctl stop_app; rabbitmqctl join_cluster rabbit@node-1; rabbitmqctl start_app
Removerabbitmqctl forget_cluster_node rabbit@node-3
Safe to stop?rabbitmq-queues check_if_node_is_quorum_critical
Rebalance leadersrabbitmq-queues rebalance quorum
Grow / shrink QQ membersrabbitmq-queues grow rabbit@node-4 all, shrink; or continuous membership reconciliation

Federation and shovel Important ​

In plain words: to connect clusters in different regions, do not stretch one cluster across the WAN; link separate clusters with federation (exchanges or queues pulled from an upstream) or a shovel (a consumer that re-publishes elsewhere).

Common misunderstanding: "Federation replicates my queue for failover." It moves or copies messages asynchronously between clusters that may have different users, versions and sizes; it is not a consistent replica.

FederationShovel
GoalTransfer events or work across independently operated brokersConsume at a source and publish toward a destination
Configured byUpstreams + a policy (federation-upstream-set)Runtime parameter (dynamic) or config (static)
TopologiesFederated exchanges (copy to downstream bindings), federated queues (move on demand)Queue → exchange/queue, any protocol mix (AMQP 0-9-1, 1.0), local shovels (4.2)
WANAsync links recover after intermittent network failuresReconnects; ack mode on-confirm for at-least-once
Typical useGlobal event fan-out, hub and spokeMigration, draining a queue, bridging to another broker

Plugins, protocols, limits and sizing ​

Plugins and protocols Good to know ​

Plugin / protocolPortStatus in 4.4
AMQP 0-9-15672 / 5671 TLSCore
AMQP 1.05672Core since 4.0
Streams (rabbitmq_stream)5552Plugin
Management UI + HTTP API (rabbitmq_management)15672Plugin; not an AMQP port
Prometheus (rabbitmq_prometheus)15692 /metrics, /metrics/per-object, /metrics/detailedPlugin
MQTT 3.1.1 and most of 5.0 (rabbitmq_mqtt), Web MQTT1883Plugin
STOMP (rabbitmq_stomp), Web STOMP61613Plugin
Federation, Shovel (+ _management)—Plugins
Consistent hash exchange—Plugin
rabbitmq_delayed_message_exchange—Community, no longer maintained
Auth: LDAP, HTTP, OAuth 2, x.509 (rabbitmq_auth_mechanism_ssl)—Plugins

Enable with rabbitmq-plugins enable rabbitmq_management rabbitmq_prometheus (or the enabled_plugins file). MQTT and STOMP clients land on exchanges and queues like any other publisher, which is how IoT devices and browsers join an AMQP topology.

Limits and sizing Important ​

LimitValue (4.4 docs)
max_message_size16 MiB default, 512 MiB hard maximum
max_channels_per_connection2047 default; 16–128 recommended
Queue name length255 bytes
Classic x-max-priority1–255 (2–4 recommended); quorum 0–31
# wildcards per topic binding key2
TTL and x-expires maximum10 years
CC/BCC sender-selected destinations64
Quorum queue members3 default, odd numbers, not more than 7 nodes
Quorum queues per clusterNo hard limit; review topology above about 5000
Erlang processes per nodeabout 1 million (+P)

Sizing rules of thumb grounded in those facts: one queue uses at most one core, so plan parallelism as "number of queues", not "bigger box"; quorum queues are disk-bound, so fast disks and memory for the WAL matter more than CPU; keep backlogs short or use a stream; size RAM so the memory watermark is never hit in normal peaks; and prefer fewer, long-lived connections.

Error codes ​

AMQP 0-9-1 reply codes (from the RabbitMQ protocol spec file). Soft errors close the channel, hard errors close the connection.

CodeNameKindYou see it when
311CONTENT_TOO_LARGEsoftMessage above max_message_size
312NO_ROUTEreturnmandatory publish matched no queue
313NO_CONSUMERSreturnimmediate flag (not supported by RabbitMQ)
320CONNECTION_FORCEDhardNode shutdown, close_connection, maintenance mode
402INVALID_PATHhardVhost does not exist
403ACCESS_REFUSEDsoftMissing permission, amq. name, guest from remote
404NOT_FOUNDsoftPublishing to or binding a missing exchange or queue
405RESOURCE_LOCKEDsoftExclusive queue used by another connection
406PRECONDITION_FAILEDsoftRedeclare with other args, unknown delivery tag, double ack, consumer timeout
501–505FRAME_ERROR ... UNEXPECTED_FRAMEhardClient bug or proxy corrupting frames
506RESOURCE_ERRORhardServer out of a resource
530NOT_ALLOWEDhardVhost or connection limit reached, not permitted
540NOT_IMPLEMENTEDhardUnsupported method
541INTERNAL_ERRORhardBroker-side failure

RabbitMQ 4.x changes and support policy ​

Versioning. Releases are major.minor.patch; feature flags gate cluster-wide behaviour and stable feature flags must be activated before upgrading members one at a time. Rolling upgrades between patches of one series are supported, and rolling from 3.13, 4.0 or 4.1 to 4.3/4.4 requires the intermediate 4.2 step. Deprecated features move through "Permitted by default" → "Denied by default" → "Removed" (rabbitmq-diagnostics list_deprecated_features).

Support. Community support covers only the newest series for a short window; extended support is commercial (Broadcom). From the release page on 25 Nov 2026:

SeriesFirst releaseEnd of community supportEnd of commercial support
4.420 Oct 202631 Jul 202731 Oct 2028
4.323 Apr 202631 Jan 202730 Apr 2028
4.228 Oct 202531 Jul 202630 Jun 2030
4.115 Apr 202531 Jan 202630 Apr 2027
4.018 Sep 202430 Apr 202530 Sep 2026
3.1322 Feb 202430 Sep 202431 Dec 2029

Migration checklist from 3.x: replace ha-* policies with quorum queues; remove x-queue-mode: lazy and x-queue-version: 1; declare transient queues as exclusive or durable+x-expires; switch global QoS to per-consumer; set a DLX or higher delivery-limit on queues that legitimately redeliver over 20 times; check messages above 16 MiB; enable Khepri (rabbitmqctl enable_feature_flag khepri_db) on 4.2 before 4.3; remove cluster_partition_handling; move off rabbitmqadmin v1 (download endpoint removed in 4.3) and the delayed-message plugin.

Operations ​

TaskTool
Node, cluster, alarmsrabbitmq-diagnostics status, check_local_alarms, check_port_connectivity, memory_breakdown
Queuesrabbitmqctl list_queues name type messages consumers, rabbitmq-queues quorum_status orders.billing
Connectionsrabbitmqctl list_connections name user state channels (state flow / blocked)
HTTP API CLIrabbitmqadmin v2 (Rust, rabbitmqadmin-ng): list queues, declare queue, definitions export, health checks
Export / import topologyrabbitmqctl export_definitions /tmp/defs.json (no management plugin needed), import_definitions, or load_definitions in rabbitmq.conf at boot
Maintenancerabbitmq-upgrade drain (maintenance mode), rabbitmq-upgrade revive
UpgradesRolling (recommended), blue-green (new cluster + shovel/federation), grow-then-shrink
MetricsPrometheus on 15692 + the official Grafana dashboards; management UI for humans
bash
# Definitions are the source of truth for durable topology: commit them
rabbitmqctl export_definitions /backup/definitions-$(date +%F).json
# rabbitmq.conf on a fresh node
# definitions.import_backend = local_filesystem
# definitions.local.path = /etc/rabbitmq/definitions.json

Metrics worth alerting on: ready and unacked messages per queue (backlog), publish vs deliver/ack rates, rabbitmq_alarms_*, connections in blocked, unroutable dropped/returned counters, quorum queue members missing, disk free, file descriptors, Erlang process count. Tracing and lag dashboards are in Messaging Observability.

Go ​

Before ​

A non-durable queue (rejected by default on 4.3+ anyway), transient messages, autoAck, and a fresh channel per publish. A restart or a consumer crash silently loses work.

go
// Package main shows a naive RabbitMQ setup: nothing survives a broker
// restart and a crashed consumer loses the message it was holding.
package main

import (
	"context"
	"log"
	"os"

	amqp "github.com/rabbitmq/amqp091-go"
)

func publish(conn *amqp.Connection, body []byte) error {
	// A new channel for every publish: cheap to write, wasteful at runtime.
	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	defer ch.Close()

	// durable=false: the queue disappears when the node restarts.
	q, err := ch.QueueDeclare("orders", false, false, false, false, nil)
	if err != nil {
		return err
	}

	// Transient message, no confirms: a nil error only means the frame
	// was written to the socket, not that the broker accepted it.
	return ch.PublishWithContext(context.Background(), "", q.Name, false, false,
		amqp.Publishing{ContentType: "application/json", Body: body})
}

func consume(conn *amqp.Connection) error {
	ch, err := conn.Channel()
	if err != nil {
		return err
	}

	// autoAck=true: the broker forgets the message the moment it is sent.
	// If this process dies mid-handler, the work is gone.
	msgs, err := ch.Consume("orders", "", true, false, false, false, nil)
	if err != nil {
		return err
	}
	for m := range msgs {
		log.Printf("got %s", m.Body)
	}
	return nil
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	if err := publish(conn, []byte(`{"order_id":42}`)); err != nil {
		log.Fatal(err)
	}
	if err := consume(conn); err != nil {
		log.Fatal(err)
	}
}

After ​

A durable topic exchange, a quorum queue with x-delivery-limit, persistent messages in confirm mode with mandatory, NotifyReturn, and a consumer with per-consumer Qos and manual acks.

go
// Package main declares a durable quorum queue behind a topic exchange,
// publishes persistent messages with confirms and consumes with manual acks.
package main

import (
	"context"
	"errors"
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

const (
	exchange = "orders.events"
	queue    = "orders.billing"
)

// declare creates the topology. It is idempotent as long as the arguments
// match what already exists on the broker.
func declare(ch *amqp.Channel) error {
	if err := ch.ExchangeDeclare(exchange, "topic", true, false, false, false, nil); err != nil {
		return err
	}
	// durable=true, and x-queue-type selects a replicated Raft-based queue.
	_, err := ch.QueueDeclare(queue, true, false, false, false, amqp.Table{
		"x-queue-type":     "quorum",
		"x-delivery-limit": 5, // after 5 failed deliveries the message is dropped or dead-lettered
	})
	if err != nil {
		return err
	}
	// "*" matches exactly one word, "#" matches zero or more.
	return ch.QueueBind(queue, "orders.*.created", exchange, false, nil)
}

// publish sends one persistent message and waits for the broker's confirm.
func publish(ctx context.Context, ch *amqp.Channel, key string, body []byte) error {
	dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, exchange, key,
		true,  // mandatory: unroutable messages come back through NotifyReturn
		false, // immediate: legacy flag, leave it false
		amqp.Publishing{
			ContentType:  "application/json",
			DeliveryMode: amqp.Persistent,
			Timestamp:    time.Now(),
			Body:         body,
		})
	if err != nil {
		return err
	}
	acked, err := dc.WaitContext(ctx)
	if err != nil {
		return err
	}
	if !acked {
		return errors.New("broker nacked the message")
	}
	return nil
}

func consume(ctx context.Context, ch *amqp.Channel, handle func([]byte) error) error {
	// At most 20 unacknowledged deliveries per consumer on this channel.
	if err := ch.Qos(20, 0, false); err != nil {
		return err
	}
	msgs, err := ch.ConsumeWithContext(ctx, queue, "billing-1", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for m := range msgs {
		if err := handle(m.Body); err != nil {
			// requeue=false: dead-letter or drop instead of looping forever.
			_ = m.Nack(false, false)
			continue
		}
		_ = m.Ack(false)
	}
	return nil
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	// One channel for publishing (confirm mode), one for consuming.
	pubCh, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	if err := pubCh.Confirm(false); err != nil {
		log.Fatal(err)
	}
	if err := declare(pubCh); err != nil {
		log.Fatal(err)
	}
	returns := pubCh.NotifyReturn(make(chan amqp.Return, 1))
	go func() {
		for r := range returns {
			log.Printf("unroutable: key=%s reply=%s", r.RoutingKey, r.ReplyText)
		}
	}()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := publish(ctx, pubCh, "orders.eu.created", []byte(`{"order_id":42}`)); err != nil {
		log.Fatal(err)
	}

	subCh, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	err = consume(context.Background(), subCh, func(b []byte) error {
		log.Printf("billing got %s", b)
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}

Topology declaration ​

All four exchange types, an exchange-to-exchange binding, an alternate exchange, a DLX, quorum, stream, SAC and priority queues, a server-named exclusive queue, and detection of 406.

go
// Package main declares a complete RabbitMQ topology with amqp091-go:
// the four exchange types, an exchange-to-exchange binding, an alternate
// exchange for unroutable messages, a quorum queue with dead lettering,
// a stream, a single-active-consumer queue, a classic priority queue and
// a server-named exclusive reply queue. Declarations are idempotent as long
// as the arguments match; a mismatch closes the channel with 406.
package main

import (
	"errors"
	"log"
	"os"

	amqp "github.com/rabbitmq/amqp091-go"
)

func declareTopology(ch *amqp.Channel) error {
	// Alternate exchange: anything orders.events cannot route lands here.
	if err := ch.ExchangeDeclare("orders.unroutable", "fanout", true, false, false, false, nil); err != nil {
		return err
	}
	if _, err := ch.QueueDeclare("orders.unroutable", true, false, false, false,
		amqp.Table{"x-queue-type": "quorum"}); err != nil {
		return err
	}
	if err := ch.QueueBind("orders.unroutable", "", "orders.unroutable", false, nil); err != nil {
		return err
	}

	// Topic exchange: routing keys like "orders.eu.created".
	if err := ch.ExchangeDeclare("orders.events", "topic", true, false, false, false,
		amqp.Table{"alternate-exchange": "orders.unroutable"}); err != nil {
		return err
	}
	// Direct exchange for commands and fanout for broadcast.
	if err := ch.ExchangeDeclare("billing.commands", "direct", true, false, false, false, nil); err != nil {
		return err
	}
	if err := ch.ExchangeDeclare("cache.invalidate", "fanout", true, false, false, false, nil); err != nil {
		return err
	}
	// Headers exchange: route on message headers, not the routing key.
	if err := ch.ExchangeDeclare("documents.by-format", "headers", true, false, false, false, nil); err != nil {
		return err
	}
	// Exchange-to-exchange binding (a RabbitMQ extension to AMQP 0-9-1):
	// every EU order event is also copied into the fanout exchange.
	if err := ch.ExchangeBind("cache.invalidate", "orders.eu.*", "orders.events", false, nil); err != nil {
		return err
	}

	// Dead letter exchange and its parking queue.
	if err := ch.ExchangeDeclare("orders.dlx", "direct", true, false, false, false, nil); err != nil {
		return err
	}
	if _, err := ch.QueueDeclare("orders.billing.dead", true, false, false, false,
		amqp.Table{"x-queue-type": "quorum"}); err != nil {
		return err
	}
	if err := ch.QueueBind("orders.billing.dead", "orders.billing", "orders.dlx", false, nil); err != nil {
		return err
	}

	// Quorum queue: replicated with Raft, three members by default.
	// Queue type can only be set at declaration time, never by policy.
	if _, err := ch.QueueDeclare("orders.billing", true, false, false, false, amqp.Table{
		"x-queue-type":                "quorum",
		"x-quorum-initial-group-size": 3,
		"x-delivery-limit":            10,
		"x-dead-letter-exchange":      "orders.dlx",
		"x-dead-letter-routing-key":   "orders.billing",
	}); err != nil {
		return err
	}
	if err := ch.QueueBind("orders.billing", "orders.*.created", "orders.events", false, nil); err != nil {
		return err
	}

	// Stream: append-only, replicated, non-destructive reads, retention by age/size.
	if _, err := ch.QueueDeclare("orders.audit", true, false, false, false, amqp.Table{
		"x-queue-type":       "stream",
		"x-max-age":          "7D",
		"x-max-length-bytes": int64(20_000_000_000),
	}); err != nil {
		return err
	}
	if err := ch.QueueBind("orders.audit", "orders.#", "orders.events", false, nil); err != nil {
		return err
	}

	// Single active consumer: many consumers register, one receives at a time.
	if _, err := ch.QueueDeclare("ledger.postings", true, false, false, false, amqp.Table{
		"x-queue-type":             "quorum",
		"x-single-active-consumer": true,
	}); err != nil {
		return err
	}
	if err := ch.QueueBind("ledger.postings", "post", "billing.commands", false, nil); err != nil {
		return err
	}

	// Classic priority queue: x-max-priority is fixed at declaration (2 to 4 is the advice).
	if _, err := ch.QueueDeclare("reports.render", true, false, false, false, amqp.Table{
		"x-max-priority": 4,
	}); err != nil {
		return err
	}
	// Headers binding: match when format=pdf AND lang=fa.
	if err := ch.QueueBind("reports.render", "", "documents.by-format", false, amqp.Table{
		"x-match": "all", "format": "pdf", "lang": "fa",
	}); err != nil {
		return err
	}

	// Server-named, exclusive, auto-delete queue: dies with this connection.
	reply, err := ch.QueueDeclare("", false, true, true, false, nil)
	if err != nil {
		return err
	}
	log.Printf("reply queue %s", reply.Name)
	return nil
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	if err := declareTopology(ch); err != nil {
		var amqpErr *amqp.Error
		if errors.As(err, &amqpErr) && amqpErr.Code == amqp.PreconditionFailed {
			log.Fatalf("406 PRECONDITION_FAILED, an entity exists with other arguments: %s", amqpErr.Reason)
		}
		log.Fatal(err)
	}
}

Publisher confirms, returns and blocked notifications ​

go
// Package main publishes a batch with publisher confirms, the mandatory flag,
// basic.return handling and connection.blocked notifications. Messages that
// are nacked, returned or unconfirmed at timeout are reported for re-publish.
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

type outcome struct {
	id       string
	key      string
	acked    bool
	returned bool
}

// publishBatch publishes all bodies, then waits for every confirm. It keeps
// the batch in flight instead of waiting after each message, which is the
// throughput difference between "confirm each" and "confirm a window".
func publishBatch(ctx context.Context, ch *amqp.Channel, keys []string, body []byte) ([]outcome, error) {
	returns := ch.NotifyReturn(make(chan amqp.Return, len(keys)))
	pending := make([]*amqp.DeferredConfirmation, 0, len(keys))

	ids := make([]string, len(keys))
	for i, key := range keys {
		ids[i] = fmt.Sprintf("order-42-%d", i)
		dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, "orders.events", key,
			true,  // mandatory: unroutable messages come back as basic.return
			false, // immediate: unsupported by RabbitMQ, always false
			amqp.Publishing{
				ContentType:  "application/json",
				DeliveryMode: amqp.Persistent, // delivery mode 2
				MessageId:    ids[i],          // correlate returns by id, not by arrival order
				Timestamp:    time.Now(),
				Headers:      amqp.Table{"x-schema": "order.created.v1"},
				Body:         body,
			})
		if err != nil {
			return nil, err // channel or connection closed: nothing after this is safe
		}
		pending = append(pending, dc)
	}

	out := make([]outcome, len(keys))
	for i, dc := range pending {
		acked, err := dc.WaitContext(ctx)
		if err != nil {
			return out, fmt.Errorf("confirm %d not received: %w", i, err)
		}
		out[i] = outcome{id: ids[i], key: keys[i], acked: acked}
	}
	// A returned message is ALSO acked (the broker handled it by returning it).
	return collectReturns(returns, out), nil
}

// collectReturns drains already buffered returns without spinning when the
// library closes its notification channel during connection shutdown.
func collectReturns(returns <-chan amqp.Return, out []outcome) []outcome {
	for {
		select {
		case r, ok := <-returns:
			if !ok {
				return out
			}
			for i := range out {
				if out[i].id == r.MessageId {
					out[i].returned = true
				}
			}
		default:
			return out
		}
	}
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	// Memory or disk alarm: the broker stops reading from publishing connections.
	blocked := conn.NotifyBlocked(make(chan amqp.Blocking, 1))
	go func() {
		for b := range blocked {
			log.Printf("connection blocked=%v reason=%q", b.Active, b.Reason)
		}
	}()

	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	if err := ch.Confirm(false); err != nil { // confirm.select
		log.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	res, err := publishBatch(ctx, ch, []string{"orders.eu.created", "orders.us.created", "nobody.listens"}, []byte(`{"order_id":42}`))
	if err != nil {
		log.Fatal(err)
	}
	for _, r := range res {
		switch {
		case !r.acked:
			log.Printf("%s: nacked, re-publish", r.key)
		case r.returned:
			log.Printf("%s: unroutable, fix the topology or use an alternate exchange", r.key)
		default:
			log.Printf("%s: broker owns it", r.key)
		}
	}
}

A consumer loop with context and reconnection ​

go
// Package main is a production-shaped RabbitMQ consumer with amqp091-go:
// a redial loop on NotifyClose (the stable way to reconnect), per-consumer
// prefetch, manual acks, a retry path that counts toward the quorum queue
// delivery limit, and cancellation on SIGINT/SIGTERM. Cancellation closes the
// connection and requeues unacked work; this is not a timed graceful drain.
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

var errPermanent = errors.New("permanent failure")

func handle(ctx context.Context, d amqp.Delivery) error {
	if d.ContentType != "application/json" {
		return errPermanent // will never succeed: dead-letter it
	}
	// Business logic must be idempotent: redelivery is normal.
	_ = ctx
	return nil
}

// consumeOnce runs until the connection drops or ctx is cancelled.
func consumeOnce(ctx context.Context, url string) error {
	conn, err := amqp.DialConfig(url, amqp.Config{
		Heartbeat:  10 * time.Second,
		Properties: amqp.Table{"connection_name": "billing-consumer"},
	})
	if err != nil {
		return err
	}
	defer conn.Close()
	closed := conn.NotifyClose(make(chan *amqp.Error, 1))

	ch, err := conn.Channel()
	if err != nil {
		return err
	}
	// global=false: prefetch per consumer (global QoS is deprecated).
	if err := ch.Qos(50, 0, false); err != nil {
		return err
	}
	cancelled := ch.NotifyCancel(make(chan string, 1)) // queue deleted or consumer timeout

	deliveries, err := ch.ConsumeWithContext(ctx, "orders.billing", "billing-1",
		false, // autoAck=false: manual acknowledgements
		false, false, false, nil)
	if err != nil {
		return err
	}

	for {
		select {
		case <-ctx.Done():
			return ctx.Err()
		case e, ok := <-closed:
			if !ok || e == nil {
				return errors.New("connection closed")
			}
			return e
		case tag, ok := <-cancelled:
			if !ok {
				return errors.New("consumer notification channel closed")
			}
			return errors.New("consumer cancelled by broker: " + tag)
		case d, ok := <-deliveries:
			if !ok {
				return errors.New("delivery channel closed")
			}
			err := handle(ctx, d)
			if ctx.Err() != nil {
				return ctx.Err() // Leave the delivery unsettled; closing requeues it.
			}
			if err := settle(d, err); err != nil {
				return fmt.Errorf("delivery settlement failed: %w", err)
			}
		}
	}
}

func settle(d amqp.Delivery, err error) error {
	switch {
	case err == nil:
		return d.Ack(false)
	case errors.Is(err, errPermanent):
		// requeue=false: dead-letter (x-death header) or drop.
		return d.Reject(false)
	default:
		// Transient: requeue. On RabbitMQ 4.3+ basic.reject increments the
		// quorum queue delivery-count; basic.nack with requeue does not.
		return d.Reject(true)
	}
}

func nextBackoff(current time.Duration) time.Duration {
	if current >= 15*time.Second {
		return 30 * time.Second
	}
	return current * 2
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	backoff := time.Second
	for {
		err := consumeOnce(ctx, url)
		if ctx.Err() != nil {
			log.Println("shutting down; unacked deliveries return to the queue")
			return
		}
		log.Printf("consumer stopped: %v; redial in %s", err, backoff)
		select {
		case <-time.After(backoff):
		case <-ctx.Done():
			return
		}
		backoff = nextBackoff(backoff)
	}
}

Built-in automatic recovery (experimental) ​

go
// Package main enables the automatic connection and topology recovery that
// amqp091-go added in v1.12.0. The library marks Config.Recovery as
// experimental. On reconnect it redeclares tracked exchanges, queues and
// bindings, re-subscribes consumers and restores QoS and confirm mode.
// Publishes that were awaiting a confirm resolve as not acked, so the
// application must re-publish them.
package main

import (
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.DialConfig(url, amqp.Config{
		Heartbeat: 10 * time.Second,
		Recovery: &amqp.Recovery{
			ReconnectionConfig: &amqp.ReconnectionConfig{
				MaxRetryCount: 20, // default 5
				RetryInterval: 3 * time.Second,
			},
			// Durable topology is owned by definitions/IaC; only restore
			// exclusive/auto-delete entities and consumers.
			TopologyRecoveryMode: amqp.TopologyRecoveryOnlyTransient,
			OnTopologyEntityError: func(_ *amqp.Connection, e amqp.TopologyRecoveryEntity) bool {
				log.Printf("skip %s %s: %v", e.EntityType, e.EntityName, e.Err)
				return true // skip and continue
			},
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	states := make(chan *amqp.StateChanged, 8)
	conn.NotifyStateChange(states) // must be drained continuously
	go func() {
		for s := range states {
			log.Printf("connection state: %s", s)
		}
	}()
	log.Println("recovery enabled:", conn.IsRecoveryEnabled())
}

The Go angle ​

github.com/rabbitmq/amqp091-go is pinned to v1.17.0 in these examples. Maintained by the RabbitMQ team, it descends from streadway/amqp and exposes operations close to the AMQP model. It supports PLAIN and EXTERNAL authentication. Return and confirm notifications use separate Go channels, so application receive order is not a cross-channel ordering guarantee: correlate returned messages using MessageId.

Config.Recovery is experimental. It can restore tracked topology (TopologyRecoveryAllEnabled, OnlyTransient, Disabled), consumers, QoS and confirm mode, and exposes transitions through NotifyStateChange. Pending deferred confirmations can close without an ack during reset; applications must still retry unknown outcomes. The explicit redial loop in go/consumer assumes topology was provisioned separately. Temporary, connection-owned queues must be redeclared and rebound after reconnecting.

The shutdown example cancels consumption and closes the connection, returning unacked work. It does not implement a separate drain deadline for finishing a long-running handler; real handlers must cooperate with their context. The batch publisher uses demo message IDs: production IDs must uniquely identify business events and stay stable across retries.

Rules that keep Go services healthy: one connection for publishing and one for consuming; one *amqp.Channel per goroutine; Qos(n, 0, false); PublishWithDeferredConfirmWithContext plus WaitContext with a deadline; drain every Notify* channel you register (an undrained one blocks the library); use Reject(tag, true) for retryable failures on 4.3+ quorum queues so the delivery limit counts; and close on SIGTERM so unacked messages return to the queue immediately instead of after a heartbeat timeout.

Laravel ​

Before ​

Laravel 13 ships "the database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver"; RabbitMQ is not among them. The community package vladimir-yuldashev/laravel-queue-rabbitmq (v15.0.2, requires illuminate/queue ^10.0|^11.0|^12.0|^13.0 and php-amqplib ^v3.6) adds it. The minimal README config: no exchange, default queue arguments.

php
<?php

// config/queue.php: the minimal connection from the package README.
// The queue is declared by the package with default arguments (a classic
// queue unless the vhost default says otherwise) and there is no exchange.

return [
    'default' => env('QUEUE_CONNECTION', 'rabbitmq'),

    'connections' => [
        'rabbitmq' => [
            'driver' => 'rabbitmq',
            'hosts' => [
                [
                    'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                    'port' => env('RABBITMQ_PORT', 5672),
                    'user' => env('RABBITMQ_USER', 'guest'),
                    'password' => env('RABBITMQ_PASSWORD', 'guest'),
                    'vhost' => env('RABBITMQ_VHOST', '/'),
                ],
            ],
        ],
    ],
];

After ​

A topic exchange and routing key, quorum => true (read from the package source: getQueueArguments() adds x-queue-type: quorum and, with reroute_failed, x-dead-letter-exchange and x-dead-letter-routing-key), and failed-job rerouting.

php
<?php

// config/queue.php: the same connection, now with a topic exchange,
// a routing key, a quorum queue and rerouting of failed jobs.

return [
    'default' => env('QUEUE_CONNECTION', 'rabbitmq'),

    'connections' => [
        'rabbitmq' => [
            'driver' => 'rabbitmq',
            'queue' => env('RABBITMQ_QUEUE', 'default'),
            'hosts' => [
                [
                    'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                    'port' => env('RABBITMQ_PORT', 5672),
                    'user' => env('RABBITMQ_USER', 'guest'),
                    'password' => env('RABBITMQ_PASSWORD', 'guest'),
                    'vhost' => env('RABBITMQ_VHOST', '/'),
                ],
            ],

            // Set to "horizon" to run under Laravel Horizon.
            'worker' => env('RABBITMQ_WORKER', 'default'),

            'options' => [
                'queue' => [
                    // Publish to a topic exchange; "%s" is replaced by the queue name.
                    // README: you probably create the queue bindings yourself.
                    'exchange' => 'orders.events',
                    'exchange_type' => 'topic',
                    'exchange_routing_key' => 'orders.%s.created',

                    // Not in the README. Read from the package source
                    // (QueueConfigFactory, RabbitMQQueue::getQueueArguments),
                    // where it adds the "x-queue-type: quorum" queue argument.
                    'quorum' => true,

                    // Also publish failed jobs to an exchange, in addition to
                    // Laravel's failed_jobs table.
                    'reroute_failed' => true,
                    'failed_exchange' => 'orders.failed',
                    'failed_routing_key' => 'orders.%s.failed',
                ],
            ],
        ],
    ],
];

A job and the two consumer commands:

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

// Dispatch:  ProcessOrder::dispatch(42)->onConnection('rabbitmq')->onQueue('eu');
//
// Consume with Laravel's own worker (uses basic_get, can read several queues):
//   php artisan queue:work rabbitmq --queue=eu --tries=3
// or with the package's command (basic_consume, one queue; prefetch-count defaults to 1000):
//   php artisan rabbitmq:consume --queue=eu --prefetch-count=20
class ProcessOrder implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $orderId) {}

    public function handle(): void
    {
        // Idempotent work goes here: RabbitMQ delivers at least once.
    }
}

Topology as a deploy step ​

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Wire\AMQPTable;

// php artisan rabbitmq:topology
// The package README notes that with a named exchange "you probably create
// your queues with bindings yourself". This command does it once per deploy,
// so job code never declares topology. Durable topology can also live in a
// definitions file that the broker imports at boot.
class DeclareTopology extends Command
{
    protected $signature = 'rabbitmq:topology';

    protected $description = 'Declare exchanges, queues and bindings for the orders domain';

    public function handle(): int
    {
        $connection = new AMQPStreamConnection(
            config('queue.connections.rabbitmq.hosts.0.host'),
            config('queue.connections.rabbitmq.hosts.0.port'),
            config('queue.connections.rabbitmq.hosts.0.user'),
            config('queue.connections.rabbitmq.hosts.0.password'),
            config('queue.connections.rabbitmq.hosts.0.vhost'),
        );
        $channel = $connection->channel();

        // exchange_declare(name, type, passive, durable, auto_delete)
        $channel->exchange_declare('orders.events', 'topic', false, true, false);
        $channel->exchange_declare('orders.failed', 'topic', false, true, false);

        // queue_declare(name, passive, durable, exclusive, auto_delete, nowait, arguments)
        $channel->queue_declare('eu', false, true, false, false, false, new AMQPTable([
            'x-queue-type' => 'quorum',
            'x-dead-letter-exchange' => 'orders.failed',
            'x-dead-letter-routing-key' => 'orders.eu.failed',
        ]));
        $channel->queue_bind('eu', 'orders.events', 'orders.eu.created');

        $channel->queue_declare('orders.failed.parking', false, true, false, false, false, new AMQPTable([
            'x-queue-type' => 'quorum',
        ]));
        $channel->queue_bind('orders.failed.parking', 'orders.failed', 'orders.#');

        $channel->close();
        $connection->close();
        $this->info('RabbitMQ topology declared.');

        return self::SUCCESS;
    }
}

Retries become delay queues ​

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Log;
use Throwable;

// With laravel-queue-rabbitmq, a retry with backoff is NOT a broker requeue:
// RabbitMQJob::release() calls laterRaw(), which declares a queue named
// "<queue>.delay.<ms>" with x-message-ttl, x-dead-letter-exchange and
// x-expires (2 x ttl), publishes a copy there, then acks the original.
// When the TTL fires the copy is dead-lettered back to the work queue.
// After the last try, markAsFailed() rejects with requeue=false: the job is
// written to failed_jobs and, with reroute_failed, dead-lettered too.
class SyncInvoiceToErp implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    public function __construct(public int $invoiceId) {}

    /**
     * Seconds to wait before each retry: one delay queue per distinct value.
     *
     * @return list<int>
     */
    public function backoff(): array
    {
        return [10, 60, 300, 900];
    }

    public function handle(): void
    {
        // Call the ERP; an exception here triggers release($backoff).
    }

    public function failed(?Throwable $exception): void
    {
        Log::warning('ERP sync gave up', ['invoice' => $this->invoiceId, 'error' => $exception?->getMessage()]);
    }
}

Confirmed publishing for integration events ​

php
<?php

namespace App\Messaging;

use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;

// laravel-queue-rabbitmq (v15) publishes jobs with basic_publish and
// mandatory=true but does not enable publisher confirms. For integration
// events that must not be lost, publish with php-amqplib directly:
// confirm.select, mandatory, and wait for acks and returns.
final class ConfirmedPublisher
{
    private bool $nacked = false;

    /** @var list<string> */
    private array $returned = [];

    public function __construct(private AMQPChannel $channel)
    {
        $this->channel->confirm_select();
        $this->channel->set_nack_handler(function (AMQPMessage $message): void {
            $this->nacked = true;
        });
        $this->channel->set_return_listener(
            function (int $replyCode, string $replyText, string $exchange, string $routingKey, AMQPMessage $message): void {
                $this->returned[] = $routingKey;
            }
        );
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public function publish(string $routingKey, array $payload, string $messageId): void
    {
        $this->nacked = false;
        $this->returned = [];

        $message = new AMQPMessage(json_encode($payload, JSON_THROW_ON_ERROR), [
            'content_type' => 'application/json',
            'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
            'message_id' => $messageId,
            'timestamp' => time(),
            'application_headers' => new AMQPTable(['x-schema' => 'order.created.v1']),
        ]);

        $this->channel->basic_publish($message, 'orders.events', $routingKey, true);

        // Blocks until every outstanding confirm (and any basic.return) arrived.
        $this->channel->wait_for_pending_acks_returns(5.0);

        if ($this->nacked) {
            throw new RuntimeException("Broker nacked {$messageId}; re-publish it.");
        }
        if ($this->returned !== []) {
            throw new RuntimeException("Unroutable key {$routingKey}; no queue is bound.");
        }
    }
}

The Laravel angle ​

What the package really does, from its source (RabbitMQQueue.php, RabbitMQJob.php):

Laravel actionAMQP behaviour
dispatch()basic_publish with delivery_mode persistent and mandatory=true; no publisher confirms
queue:work rabbitmqbasic_get polling; can read several queues
rabbitmq:consumebasic_consume, push-style consumption of one queue rather than repeated polling; --prefetch-count
Job succeedsbasic_ack
release($delay) / backofflaterRaw(): declares <queue>.delay.<ms> with x-message-ttl, x-dead-letter-exchange, x-dead-letter-routing-key, x-expires = 2 × ttl; publishes a copy there; acks the original
later() / ->delay()Same delay queue mechanism: one queue per distinct delay
Job fails for goodbasic_reject(requeue=false); Laravel writes failed_jobs; with reroute_failed the DLX copies it to failed_exchange
after_commit => trueDispatch waits for the DB transaction to commit (not an outbox)
worker => horizonPackage-specific Horizon integration; official Horizon support remains Redis-only

Consequences: a retry is a new message, so quorum delivery-limit never sees Laravel retries (Laravel's tries does the counting); many distinct backoff values create many delay queues (their type depends on the environment default because the arguments omit x-queue-type; verify compatibility when the vhost defaults to quorum); the default heartbeat is 0; and if you need publisher confirms, publish through php-amqplib yourself (ConfirmedPublisher.php) or pair dispatch with the outbox. Queue internals in general are in Laravel Queue Internals.

Compared with the others ​

Kafka ​

Kafka's unit is a partitioned, replicated log that stores events according to configurable retention; consumers track offsets and replay by seeking. Routing is the producer's choice of topic and key (the key normally determines the partition), so there are no exchanges, no per-message TTL, no priorities and no broker-side redelivery or DLQ (retry topics are an application pattern). Ordering and parallelism come from partitions; in RabbitMQ from single queues, SAC and hash exchanges. RabbitMQ streams are the closest RabbitMQ gets to Kafka; reading one with an offset looks like this:

go
// Package main reads a RabbitMQ stream over AMQP 0-9-1. Streams need a
// prefetch and manual acks; x-stream-offset picks where to start, which is
// what makes replay possible (classic and quorum queues delete on ack).
package main

import (
	"context"
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"
)

func replay(ctx context.Context, ch *amqp.Channel, from any) error {
	if err := ch.Qos(100, 0, false); err != nil { // QoS is mandatory for streams
		return err
	}
	msgs, err := ch.ConsumeWithContext(ctx, "orders.audit", "",
		false, false, false, false,
		amqp.Table{"x-stream-offset": from}) // "first", "last", "next", an int64 offset, a time, or "1h"
	if err != nil {
		return err
	}
	for m := range msgs {
		log.Printf("offset=%v body=%s", m.Headers["x-stream-offset"], m.Body)
		_ = m.Ack(false) // ack is credit, not deletion: the entry stays in the log
	}
	return nil
}

func main() {
	url := os.Getenv("RABBITMQ_URL")
	if url == "" {
		log.Println("set RABBITMQ_URL to run this example")
		return
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	// Rebuild a projection from the last 24 hours.
	if err := replay(ctx, ch, time.Now().Add(-24*time.Hour)); err != nil {
		log.Fatal(err)
	}
}
ConcernRabbitMQKafka
RoutingBroker: exchanges, bindings, headersProducer: topic + key
After consumptionDeleted (queues) / kept (streams)Kept until retention
RedeliveryBroker requeues unackedConsumer re-reads from committed offset
Delay, TTL, priorityBuilt inNot built in
ReplicationQuorum queues, streams (Raft)ISR replication per partition, KRaft metadata
Sweet spotTasks, commands, routing, low latencyEvent logs, replay, very high throughput

Redis Streams ​

"A Redis stream is a data structure that acts like an append-only log" with consumer groups, a pending entries list and XACK, so it behaves like a small RabbitMQ stream with competing consumers. What is missing compared with RabbitMQ: exchanges and bindings (the producer names the stream), automatic requeue on consumer death (you reclaim with XAUTOCLAIM after an idle time), dead-lettering (you count deliveries in XPENDING and move entries yourself), priorities and TTL per message, and publisher confirms (durability depends on AOF fsync and asynchronous replication; see Redis). It wins on "already in the stack" and latency. Details in Redis Streams & Pub/Sub.

go
// Package main is the Redis Streams equivalent of a RabbitMQ quorum queue
// consumer, for comparison: no exchanges or bindings (the producer picks the
// stream), no broker-side redelivery timer (the consumer must reclaim stale
// entries with XAUTOCLAIM), and no dead-letter exchange (you move entries
// yourself after counting deliveries in XPENDING).
package main

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/redis/go-redis/v9"
)

func main() {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		log.Println("set REDIS_ADDR to run this example")
		return
	}
	ctx := context.Background()
	rdb := redis.NewClient(&redis.Options{Addr: addr})
	defer rdb.Close()

	// "Routing" is the stream name the producer chooses.
	_ = rdb.XAdd(ctx, &redis.XAddArgs{Stream: "orders.billing", Values: map[string]any{"order_id": 42}}).Err()
	_ = rdb.XGroupCreateMkStream(ctx, "orders.billing", "billing", "0").Err()

	// Like basic.consume with prefetch 10 and manual ack.
	res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
		Group: "billing", Consumer: "billing-1", Streams: []string{"orders.billing", ">"}, Count: 10, Block: 5 * time.Second,
	}).Result()
	if err != nil && err != redis.Nil {
		log.Fatal(err)
	}
	for _, s := range res {
		for _, m := range s.Messages {
			_ = rdb.XAck(ctx, "orders.billing", "billing", m.ID).Err() // like basic.ack
		}
	}

	// RabbitMQ requeues automatically when a consumer's channel dies.
	// Redis needs an explicit reclaim of entries idle for more than 1 minute.
	_, _, _ = rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
		Stream: "orders.billing", Group: "billing", Consumer: "billing-2", MinIdle: time.Minute, Start: "0-0", Count: 100,
	}).Result()
}

In production systems ​

  • Quorum queues are the documented replicated queue type. Mirroring was removed in 4.0; the 4.4 docs say the team continuously exercises quorum queues with an extended Jepsen test suite.
  • Alarms block publishers, not consumers. At about 60% of RAM (default) or 50 MB free disk, publishing connections are blocked cluster-wide; producers look hung, consumers keep draining.
  • Poison loops are capped. Quorum queues dead-letter or drop after delivery-limit failed deliveries (20 by default since 4.0); on 4.3+ only basic.reject and channel crashes count, basic.nack with requeue does not.
  • Deprecations bite at upgrade. 4.3 denies transient non-exclusive queues and global QoS by default, removes CQv1, x-queue-mode, Mnesia and partition handling strategies; 3.13–4.1 must pass through 4.2.
  • The delayed-message exchange is abandoned. Its README says the team "no longer maintains this project" and points to 4.4 quorum delivery delay and TTL+DLX.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Messages lost on broker restartQuorum queue + persistent + confirmsx-queue-type: quorum, DeliveryMode: Persistent, Confirm + WaitContextMajority-replicated before ackHigher latency, disk I/O
Messages lost between DB commit and publishTransactional outboxWrite event row in the same transaction, relay publishes with confirmsNo dual-write gapRelay to run, duplicates possible
Unroutable messages vanishAlternate exchange + mandatoryalternate-exchange policy/arg, NotifyReturnNothing silently droppedOne more queue to watch
Poison message loops foreverDelivery limit + DLXQuorum delivery-limit, Reject(false) on permanent errorsBounded retries, parked for inspectionNeed a parking-lot process
Retry stormsDelayed retryQuorum x-delayed-retry-* (4.3), TTL+DLX wait queues, Laravel backoffSpreads loadLinear only (quorum) or one queue per delay
Publishers hangHandle alarmsSeparate connections, NotifyBlocked, confirm timeouts, absolute watermarkPredictable behaviourMust design for back-pressure
One hot queue maxes one coreShardx-modulus-hash / consistent hash exchange to N queues, SAC per queueParallel and ordered per keyMore queues to operate
Huge backlog / many readersStreamx-queue-type: stream, x-stream-offsetNon-destructive, replayNo DLX/TTL/priority
Cross-region deliveryFederation or shovelUpstream + policy, or dynamic shovel with on-confirmTolerates WAN outagesEventual, not a replica
Connection churn from PHPLong-lived workersrabbitmq:consume / queue:work daemons; never connect per requestFewer TCP setupsDaemon management

The outbox table that closes the "commit then publish" gap (full pattern in Transactional Outbox):

sql
CREATE TABLE outbox (
    id            BIGSERIAL PRIMARY KEY,
    message_id    UUID        NOT NULL UNIQUE,      -- becomes AMQP message_id
    exchange      TEXT        NOT NULL,             -- e.g. orders.events
    routing_key   TEXT        NOT NULL,             -- e.g. orders.eu.created
    payload       JSONB       NOT NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    published_at  TIMESTAMPTZ                       -- set only after basic.ack
);
-- relay: claim a batch without blocking other relays
SELECT id, message_id, exchange, routing_key, payload
FROM outbox WHERE published_at IS NULL
ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED;
-- Laravel: what failed and why, before replaying with queue:retry
SELECT uuid, queue, failed_at, left(exception, 120) FROM failed_jobs ORDER BY failed_at DESC LIMIT 20;

When NOT to use RabbitMQ ​

SituationWhy RabbitMQ is the wrong defaultUse instead
Event log that many teams replay for monthsQueues delete on ack; streams lack Kafka's ecosystem (Connect, Streams, schema tooling)Kafka
Stream processing with windows and stateNo processing layerKafka Streams / Flink (Stream Processing)
A few background jobs in one Laravel appA broker to operate for little gainLaravel database or redis driver
You already run Redis and need light fan-out with groupsExtra systemRedis Streams
Fully managed, serverless, pay-per-requestYou run clusters, upgrades, ErlangSQS/SNS, Google Pub/Sub (Other Brokers)
Multi-region active-active with ordering guaranteesFederation is asynchronous, clusters are LAN-boundPulsar geo-replication or a database-backed design
Synchronous request/response with a user waitingAdds latency and failure modesPlain HTTP/gRPC (Service Communication)
Long-running workflows with timers and compensationMessages are not workflow stateTemporal (Durable Workflows)

Choosing ​

SituationQueue type / featureExtra techniqueReason
Orders, payments, anything you cannot loseQuorum queueConfirms, manual ack, DLX, outboxMajority replication + poison handling
RPC reply queuesClassic exclusive, server-named, or direct reply-tox-local-random exchange for latencyTemporary, per-connection
Cache invalidation to every app nodeFanout + classic exclusive auto-delete queues—Each node needs its own copy only while alive
Audit trail, projections, replayStreamx-max-age, offset trackingNon-destructive reads
50+ consumers of the same eventsStream (or super stream)Native stream protocolOne copy instead of 50 queues
Per-customer ordering with parallelismx-modulus-hash exchange + N quorum queues with SACKey = customer idOne active consumer per shard
Urgent vs bulk jobsTwo queues (or quorum priorities)Separate worker poolsAvoid starvation
Retry after 30 s, 5 min, 1 hTTL+DLX wait queues, or quorum delayed retry / x-opt-delivery-time (4.4)x-death countPlugin-free delays
Thousands of tenantsvhost per tenant group, not per tenantOperator policies, vhost limitsMetadata and connection limits
IoT devicesMQTT plugin into topic exchangesQuorum or stream behind itOne broker for devices and services

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel monolith sends email and generates PDFs asynchronously. Simplest correct setup: one vhost, a direct exchange per job type (or the package's default), quorum queues, queue:work or rabbitmq:consume under Supervisor, tries and backoff on jobs, failed_jobs for inspection. Honest note: if the only reason for RabbitMQ is "run jobs later", the Laravel database or redis driver is simpler; RabbitMQ earns its place when routing, priorities or multiple languages appear.

Modular monolith and multiple databases ​

Modules (Billing, Catalog, Shipping) talk through integration events instead of each other's tables. One topic exchange per module (billing.events, catalog.events), each consumer module owns its queue and its bindings, and nobody else declares them. Use separate vhosts only when permissions must differ. Events published from inside a DB transaction go through an outbox table per module, so a rollback never leaks a message. This is the step where Domain Events vs Integration Events becomes concrete.

Microservices ​

text
     Order svc (Go)          RabbitMQ (orders.events topic)        Billing svc (Laravel)     Email svc (Go)
1    tx: insert order + outbox row
2    relay: publish orders.eu.created, confirm -> ack, mark outbox published
3                            -> orders.billing (quorum) ----------> charge card, ack
4                            -> email.order-created (quorum) ------------------------------> send mail, ack
5                                                                    charge fails 3x -> reject(false) -> orders.dlx
6                                                                    publish billing.payment-failed -> Order svc compensates

What survives across service boundaries: at-least-once delivery, so every consumer is idempotent on message_id (Idempotent Consumers); no distributed transaction, so failures are compensated (Saga Pattern); and topology ownership: the consumer declares its queue and binding, the producer only its exchange. Version message schemas (Message Design) and design for broker outages per Designing for Failure: Reliable Messaging. Choosing messaging versus HTTP per interaction is covered in Service Communication.

Distributed data: clusters, regions and replicas ​

Inside one region, a 3-node cluster across 3 availability zones with quorum queues (4.4 can place members per AZ) survives one zone. Across regions, run one cluster per region and connect them with federation (events fan out to the other region) or shovels (move specific queues), accepting asynchronous delivery and possible duplicates. Never stretch a cluster across a WAN: Khepri and every quorum queue need a majority, so latency becomes every write's latency and a link flap becomes an outage. The same majority arithmetic is explained for databases in Distributed SQL & Consensus and replica lag in Replication & Failover. Durability is a chain: broker fsync (compare Durability & Crash Recovery), confirm, outbox in the ACID transaction that produced the event.

Scaling path: 1×, 10×, 100× ​

LoadShapeWhat changes
1× (hundreds msg/s)3-node cluster, a dozen quorum queuesDefaults, Prometheus alerts, definitions in git
10× (thousands msg/s)Same cluster, more queues and consumersTune prefetch, separate publish/consume connections, shard hot queues with x-modulus-hash, fast disks
100× (tens of thousands msg/s, many readers)Streams/super streams for fan-out, several clusters by domainNative stream protocol, federation between clusters, consider Kafka for the event backbone while RabbitMQ keeps commands

Lab (expected, not run) ​

All commands and observations are expected, not run. No broker or Docker environment was started. Use a pre-provisioned, disposable three-node RabbitMQ 4.4 test cluster (rabbit@node-1 through rabbit@node-3) with CLI access. Never perform failure injection on production.

  1. Inspect the baseline and provision topology. Supply RABBITMQ_URL through your test environment's secret mechanism. Do not paste credentials into shell history.
bash
rabbitmqctl cluster_status
# expected: three running nodes
cd docs/snippets/messaging/rabbitmq/go
go run ./topology
rabbitmqctl list_queues name type arguments
# expected: orders.billing quorum; orders.audit stream; reports.render classic
rabbitmqctl list_bindings source_name destination_name routing_key
# expected: orders.events -> orders.billing with orders.*.created
  1. Confirms and returns. Run go run ./confirms. With the alternate exchange present, the unknown key reaches orders.unroutable and is confirmed. For the return experiment, create a separate test exchange without an alternate exchange and change the snippet's exchange only in your lab copy. Expected: mandatory unroutable messages return 312 NO_ROUTE and can still receive a positive confirm. Redeclare orders.billing with a conflicting delivery limit: expect 406 PRECONDITION_FAILED.

  2. Prefetch and consumer death. In a dedicated queue publish 100 messages. Run a test consumer with prefetch 10 that does not ack. Expected: 90 ready, 10 unacked. Close that consumer connection: expect 100 ready; returned deliveries carry redelivered=true. Make the consumer handler fail transiently every time: counted rejections eventually hit the configured delivery limit and produce a DLX message with x-death reason delivery_limit.

  3. Quorum availability. Verify the actual group has replicas on all three nodes before this experiment.

bash
rabbitmq-queues -n rabbit@node-1 quorum_status orders.billing
rabbitmqctl -n rabbit@node-1 stop_app
# expected: remaining majority elects a leader
rabbitmqctl -n rabbit@node-2 stop_app
# expected: no majority; no successful publisher confirms
rabbitmqctl -n rabbit@node-1 start_app
rabbitmqctl -n rabbit@node-2 start_app
# expected: majority restored; confirmed messages remain
  1. Controlled memory alarm. Record the original watermark. In the disposable environment set rabbitmqctl set_vm_memory_high_watermark absolute 50MiB. Expected: publishing connection blocked, separate consumer-only connection running, and NotifyBlocked active. Restore the recorded original value immediately; do not assume it was 0.6.

Common misconceptions ​

BeliefReality
A durable queue makes messages durableNeeds persistent delivery mode and publisher confirms too
The cluster replicates my queuesOnly metadata, plus quorum queues and streams
ha-mode: all gives HAMirroring was removed in 4.0; policy keys are ignored
Lazy queues save memoryLazy mode is ignored since 3.12; x-queue-mode fails on 4.3
A publish without error is safeWithout confirms it only reached your socket buffer
A confirm means the consumer processed itConfirms only cover publisher to queue leader
Two nodes are redundantTwo nodes cannot form a majority after a split
Use the delayed-message plugin for delaysUnmaintained; use TTL+DLX or 4.4 x-opt-delivery-time
basic.nack requeue counts toward the delivery limitNot since 4.3; use basic.reject
Policies can set the queue type or prioritiesBoth are declaration-only
Vhosts isolate resourcesThey isolate names and permissions; alarms are cluster-wide
Streams replace KafkaThey complement queues; no DLX/TTL/priority, smaller ecosystem
A cluster can span regionsClusters assume a LAN; use federation or shovel

Cheat sheet ​

TopicRemember
ModelPublish to exchange → bindings → queues → consumers
Exchange typesdirect, fanout, topic (* one word, # zero or more), headers; default ""
Safe publishDurable quorum queue + persistent + confirms + mandatory/AE
Safe consumeManual ack, per-consumer prefetch, idempotent handler
Queue typesClassic = single node; quorum = Raft majority; stream = replayable log
Quorum facts3 members default, odd cluster sizes, ≤ 7 nodes, delivery-limit 20
4.3 trapdelivery-limit counts reject, not nack requeue
DelayTTL+DLX, quorum delayed retry (4.3), x-opt-delivery-time (4.4)
PoliciesOne policy per entity (highest priority); operator policy merges conservatively
AlarmsMemory ~60% RAM, disk 50 MB; publishers blocked cluster-wide
ClusteringKhepri (Raft) metadata, majority needed; cookie, 4369, 25672
Cross-regionFederation or shovel, not a stretched cluster
Limits16 MiB messages default, 2047 channels/connection, 255-byte names
UpgradesEnable feature flags first; 3.13–4.1 go via 4.2
Opsrabbitmq-diagnostics, rabbitmq-queues, rabbitmqadmin v2, export_definitions, Prometheus 15692

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A publisher sends persistent messages to a durable classic queue without confirms, and the node crashes. Can messages be lost? Must-know ​

Answer

Answer: Yes. The message store writes to disk in batches every few hundred milliseconds; without confirms the publisher never learns which messages made it. See Message properties and Confirms.

2 — Your quorum queue keeps redelivering a poison message forever on 4.3 even though delivery-limit is 10. Why? Good to know ​

Answer

Answer: The consumer uses basic.nack with requeue. Since 4.3 the limit counts failed deliveries (basic.reject, channel crashes), not nack-requeues. Switch to Reject(tag, true) or reject with requeue=false. See TTL, dead-lettering and the delivery limit.

3 — Can you turn an existing classic queue into a quorum queue with a policy? Important ​

Answer

Answer: No. Queue type is declaration-only. Create a new quorum queue, bind it, move consumers, drain the old one; vhost default_queue_type and relaxed equivalence checks help. See Migration.

4 — Why should a two-node cluster be avoided? Must-know ​

Answer

Answer: After a split neither side has a majority, so Khepri metadata and quorum queues stop. The docs list 0 tolerated failures for 2 nodes. See Quorum queues and Clustering.

5 — Your producers hang but consumers keep working. What is the likely cause and the first command? Important ​

Answer

Answer: A memory or disk alarm blocking publishing connections. Run rabbitmq-diagnostics check_local_alarms / status and list_connections name state. See Alarms.

6 — You need to rebuild a read model from last week's events. Which queue type supports that and how do you start reading? Important ​

Answer

Answer: A stream with retention of at least a week; consume with x-stream-offset set to a timestamp or first, with a prefetch and acks. See Streams.

7 — Name three ways to delay a message on RabbitMQ 4.4 and the one to avoid. Important ​

Answer

Answer: TTL+DLX wait queues, quorum delayed retry (4.3+), and x-opt-delivery-time on quorum queues (4.4). Avoid the unmaintained delayed-message exchange plugin. See Delayed delivery.

8 — A message is published to a topic exchange with no matching binding and no alternate exchange, mandatory=false, in confirm mode. What does the publisher get? Important ​

Answer

Answer: A basic.ack; the message is dropped. With mandatory=true it would first receive basic.return 312 NO_ROUTE. See Bindings.

9 — How does laravel-queue-rabbitmq implement release(60)? Good to know ​

Answer

Answer: It declares <queue>.delay.60000 with x-message-ttl, a DLX back to the work exchange and x-expires, publishes a copy there and acks the original. See The Laravel angle.

10 — Why can't one RabbitMQ queue use all 16 cores, and what do you do about it? Important ​

Answer

Answer: A queue replica is one Erlang process and is limited to a single core. Shard with x-modulus-hash or consistent-hash exchanges (SAC per shard for order) or use super streams. See Erlang runtime.

11 — Two regions need each other's order events. Cluster or federation? Must-know ​

Answer

Answer: Federation (or shovel) between two clusters. Clusters assume a LAN and need a majority for every metadata and quorum write. See Federation and shovel.

12 — What does amqp091-go's experimental recovery do with publishes waiting for a confirm when the connection drops? Good to know ​

Answer

Answer: Pending deferred confirmations are closed as not acked; the application must re-publish them (and consumers must dedup). See The Go angle.

Glossary ​

TermMeaning
AMQP 0-9-1RabbitMQ's original, programmable messaging protocol (exchanges, queues, bindings)
AMQP 1.0A different OASIS protocol; core in RabbitMQ since 4.0
ConnectionAuthenticated TCP link from a client to a node
ChannelLightweight session multiplexed on a connection; scope of prefetch and delivery tags
HeartbeatPeriodic frame to detect dead peers (server suggests 60 s)
ExchangeNamed router that receives publishes
Direct / fanout / topic / headers exchangeRoute by exact key / to all / by word pattern / by header values
Default exchange"", routes to the queue named by the routing key
Binding / binding keyRule from exchange to queue (or exchange)
Routing keyAddress string set by the publisher
Exchange-to-exchange bindingRabbitMQ extension binding one exchange to another
Alternate exchange (AE)Receives messages the primary exchange could not route
x-local-random4.0 exchange type routing to a random local queue
x-modulus-hashBuilt-in exchange that routes by hash(key) mod N
Consistent hash exchangePlugin exchange routing by a hash ring
QueueOrdered buffer that consumers read from
DurableEntity definition survives a node restart
Exclusive queueOwned by one connection, deleted when it closes
Auto-deleteDeleted when the last consumer leaves
Server-named queueName generated by the broker (amq.gen-...)
x-argumentsOptional queue/exchange/consumer arguments such as x-queue-type
Property equivalenceRedeclaration must match; mismatch → 406
Classic queueSingle-node queue type, CQv2 storage
CQv1 / CQv2Old and current classic queue storage formats
Lazy queueRemoved mode; ignored since 3.12, rejected by 4.3
Quorum queueRaft-replicated durable queue
RaftConsensus algorithm: leader, followers, majority commit, terms
RaRabbitMQ's Raft library
Leader / follower / memberRoles of a quorum queue's replicas
x-quorum-initial-group-sizeNumber of quorum queue members at declaration (default 3)
Delivery limitMax failed deliveries before dead-lettering or dropping (default 20)
Delivery countCounter of failed deliveries, x-delivery-count header
At-least-once dead-letteringQuorum DLX mode using internal confirms
Delayed retryQuorum back-off on returned messages (4.3)
x-opt-delivery-time4.4 header to delay a message on a quorum queue
Deferred message4.4 AMQP 1.0 feature to park and claim a message by token
StreamReplicated append-only log with non-destructive reads
Super streamPartitioned stream made of several streams
x-stream-offsetWhere a stream consumer starts: first, last, next, offset, time
Retention (max-age, max-length-bytes)How long and how much a stream keeps
Delivery mode1 transient, 2 persistent
Publisher confirmBroker ack/nack for each publish in confirm mode
mandatoryReturn unroutable messages to the publisher
basic.returnThe returned unroutable message (312 NO_ROUTE)
Consumer acknowledgementbasic.ack / nack / reject from a consumer
Prefetch (QoS)Max unacked deliveries per consumer
Global QoSPer-channel prefetch, denied by default since 4.3
Consumer timeoutMax time a delivery may stay unacked (30 min default)
TTLTime-to-live for messages (x-message-ttl, expiration) or queues (x-expires)
Dead letter exchange (DLX)Exchange receiving rejected, expired or over-limit messages
x-deathHeader recording dead-letter history
OverflowBehaviour at max length: drop-head, reject-publish, reject-publish-dlx
Priority queueQueue delivering higher priority first
Single active consumer (SAC)One consumer active at a time, automatic failover
Exclusive consumerConsumer that prevents others (classic queues only)
PolicyRegex-matched runtime arguments for queues/exchanges
Operator policyAdmin-enforced limits merged conservatively with policies
Virtual host (vhost)Namespace for entities, permissions, policies
Permissions (configure/write/read)Per-vhost regexes controlling access
User tagsadministrator, monitoring, policymaker, management
Flow controlCredit-based throttling of fast publishers (flow state)
Memory alarm / watermarkBlocks publishers above vm_memory_high_watermark
Disk alarmBlocks publishers below disk_free_limit
connection.blockedNotification that publishing is blocked
ClusterNodes sharing metadata on a LAN
KhepriRaft-based metadata store; only option since 4.3
MnesiaFormer metadata store, removed in 4.3
Erlang cookieShared secret authenticating nodes and CLI tools
epmdErlang port mapper daemon (port 4369)
BEAM / Erlang process / schedulerErlang VM / lightweight process / OS thread running processes
Feature flagCluster-wide switch for new behaviour; enable before upgrades
Deprecated featureFeature moving to denied and removed
FederationAsynchronous message transfer between separate brokers/clusters
ShovelPlugin that consumes from a source and re-publishes to a destination
Management pluginUI and HTTP API on port 15672
rabbitmq_prometheusMetrics endpoint on port 15692
rabbitmqctl / rabbitmq-diagnostics / rabbitmq-queues / rabbitmq-upgradeCLI tools for admin, health, queues and maintenance
rabbitmqadmin v2HTTP API CLI (rabbitmqadmin-ng)
DefinitionsJSON export of users, vhosts, topology and policies
Rolling / blue-green upgradeNode-by-node in place / new cluster and migrate
MQTT / STOMPIoT and text protocols supported via plugins
amqp091-goOfficial Go AMQP 0-9-1 client
laravel-queue-rabbitmqCommunity Laravel queue driver for RabbitMQ
php-amqplibPHP AMQP 0-9-1 client used by the Laravel package
Delayed-message exchangeCommunity plugin, no longer maintained
OutboxDB table written in the business transaction and relayed to the broker

References ​

Built by Morteza Negahi