Skip to content

RabbitMQ Cheatsheet ​

Dense quick reference for operating and using RabbitMQ (AMQP 0-9-1, 4.x unless noted): CLI, HTTP API, exchanges, queue arguments, policies, delivery guarantees, clustering, monitoring, errors, and Go and Laravel snippets. For theory see RabbitMQ in depth and Broker Comparison.

Ports and files ​

TaskCommand/ConfigNotes
AMQP 0-9-15672 (TLS 5671)Client connections
Management UI and HTTP API15672Plugin rabbitmq_management
Prometheus metrics15692 (/metrics)Plugin rabbitmq_prometheus
Inter-node and CLI25672, 4369 (epmd)Must be open between cluster nodes
Streams protocol5552Used by native stream clients
MQTT / STOMP1883 / 61613Plugins rabbitmq_mqtt, rabbitmq_stomp
Main configrabbitmq.confKey-value ini style; advanced.config for Erlang terms
Environmentrabbitmq-env.confNODENAME, RABBITMQ_MNESIA_BASE, ...
Enable pluginrabbitmq-plugins enable rabbitmq_managementlist, disable, --offline
Docker quick startdocker run -p 5672:5672 -p 15672:15672 rabbitmq:4-managementDefault user guest/guest, localhost only

rabbitmqctl: node, users, vhosts ​

TaskCommand/ConfigNotes
Node statusrabbitmqctl statusVersion, memory, alarms, listeners
Cluster statusrabbitmqctl cluster_statusNodes, running nodes, partitions, feature flags
Stop/start app onlyrabbitmqctl stop_app / start_appErlang VM keeps running; needed for join/reset
Stop noderabbitmqctl shutdownWaits for node to exit
Add userrabbitmqctl add_user app 's3cret'Quote the password
Tag userrabbitmqctl set_user_tags app managementTags: administrator, monitoring, management, policymaker
Add vhostrabbitmqctl add_vhost ordersIsolation unit for queues, exchanges, permissions
Permissionsrabbitmqctl set_permissions -p orders app ".*" ".*" ".*"Regexes: configure, write, read
List permissionsrabbitmqctl list_permissions -p ordersAlso list_users, list_vhosts
Change passwordrabbitmqctl change_password app 'new'Existing connections stay open
Delete userrabbitmqctl delete_user app
Feature flagsrabbitmqctl enable_feature_flag allRun after rolling upgrade
Memory watermarkrabbitmqctl set_vm_memory_high_watermark 0.6Runtime only; config key vm_memory_high_watermark.relative (default 0.6)
Disk limitrabbitmqctl set_disk_free_limit 2GBConfig key disk_free_limit.absolute (default 50MB)
Close connectionrabbitmqctl close_connection "<pid>" "reason"Pid from list_connections pid

rabbitmqctl: queues, exchanges, policies ​

TaskCommand/ConfigNotes
List queues with depthrabbitmqctl list_queues -p orders name type messages_ready messages_unacknowledged consumersColumn names are positional args
List exchangesrabbitmqctl list_exchanges -p orders name type durable
List bindingsrabbitmqctl list_bindings -p orders source_name destination_name routing_key
List connectionsrabbitmqctl list_connections user peer_host state channels
List channelsrabbitmqctl list_channels connection number prefetch_count messages_unacknowledged
List consumersrabbitmqctl list_consumers -p ordersShows ack_required, prefetch_count
Purge queuerabbitmqctl purge_queue -p orders q1Drops ready messages only, not unacked
Delete queuerabbitmqctl delete_queue -p orders q1Add --if-empty / --if-unused
Set policyrabbitmqctl set_policy -p orders ttl "^tmp\." '{"message-ttl":60000}' --apply-to queues --priority 1Regex pattern on names
Operator policyrabbitmqctl set_operator_policy -p orders cap ".*" '{"max-length":1000000}' --apply-to queuesOnly a few keys allowed (max-length, max-length-bytes, message-ttl, expires, overflow, delivery-limit, ...); the more conservative value wins
List/clear policyrabbitmqctl list_policies -p orders / clear_policy -p orders ttl
Export definitionsrabbitmqctl export_definitions defs.jsonUsers, vhosts, queues, exchanges, bindings, policies; not messages
Import definitionsrabbitmqctl import_definitions defs.jsonMerges into the broker; boot-time import does not overwrite existing entities

rabbitmq-diagnostics, rabbitmq-queues, rabbitmq-streams ​

TaskCommand/ConfigNotes
Livenessrabbitmq-diagnostics pingNode answers
Health: runningrabbitmq-diagnostics check_runningExit code 0 means app is running
Health: alarmsrabbitmq-diagnostics check_local_alarmsMemory or disk alarm blocks publishers
Health: portsrabbitmq-diagnostics check_port_connectivity
Safe to stop?rabbitmq-diagnostics check_if_node_is_quorum_criticalRun before restarting a node
Memory breakdownrabbitmq-diagnostics memory_breakdown --unit MBFind what holds memory
Listenersrabbitmq-diagnostics listenersProtocols and ports
Effective configrabbitmq-diagnostics environmentApplication env
Log tailrabbitmq-diagnostics log_tail -N 50
Quorum statusrabbitmq-queues quorum_status --vhost orders q1Leader, followers, Raft indexes
Add quorum memberrabbitmq-queues add_member --vhost orders q1 rabbit@node3Also delete_member
Grow/shrinkrabbitmq-queues grow rabbit@node4 all / shrink rabbit@node1Place or remove replicas on a node
Rebalance leadersrabbitmq-queues rebalance quorumEvens leaders across nodes
Stream statusrabbitmq-streams stream_status --vhost orders s1Replicas and offsets
Add stream replicarabbitmq-streams add_replica --vhost orders s1 rabbit@node2Also delete_replica

rabbitmqadmin (v2) and definitions ​

TaskCommand/ConfigNotes
Connectrabbitmqadmin --host h --port 15672 --username u --password p ...Also --base-uri, --vhost; v1 used key=value style, v2 uses long flags
Declare queuerabbitmqadmin declare queue --name q1 --type quorum --durable trueAlso queues declare
Declare exchangerabbitmqadmin declare exchange --name ev --type topic
Bindrabbitmqadmin declare binding --source ev --destination-type queue --destination q1 --routing-key "order.*"
Publishrabbitmqadmin publish message --routing-key q1 --payload hiDev and test only; --exchange selects the exchange
Listrabbitmqadmin list queuesAlso queues list, exchanges list, bindings list, connections list
Exportrabbitmqadmin definitions export --file defs.jsonEverything except messages; --stdout prints instead
Importrabbitmqadmin definitions import --file defs.json--stdin reads from a pipe
Load at bootdefinitions.import_backend = local_filesystem and definitions.local.path = /etc/rabbitmq/defs.jsonIn rabbitmq.conf; imported after plugins start; does not overwrite existing entities

Management HTTP API ​

Default vhost / is URL-encoded as %2F. Basic auth. Base http://host:15672.

TaskCommand/ConfigNotes
Cluster overviewGET /api/overviewTotals, rates, versions
NodesGET /api/nodesMemory, disk, fd, mem_alarm, disk_free_alarm
List queuesGET /api/queues/{vhost}Add ?page=1&page_size=100&name=^q&use_regex=true (page size default 100, max 500)
One queueGET /api/queues/{vhost}/{name}messages_ready, messages_unacknowledged, consumers
Declare queuePUT /api/queues/{vhost}/{name}Body: durable, arguments
Delete queueDELETE /api/queues/{vhost}/{name}
Purge queueDELETE /api/queues/{vhost}/{name}/contents
Peek messagesPOST /api/queues/{vhost}/{name}/getBody: count, ackmode, encoding; ack_requeue_true keeps them
PublishPOST /api/exchanges/{vhost}/{name}/publishFor tests only; no confirms
Declare exchangePUT /api/exchanges/{vhost}/{name}Body: type, durable
BindingsPOST /api/bindings/{vhost}/e/{src}/q/{dst}Body: routing_key, arguments
Set policyPUT /api/policies/{vhost}/{name}Body: pattern, definition, apply-to, priority
Connections, channelsGET /api/connections, /api/channels, /api/consumersDELETE /api/connections/{name} closes
DefinitionsGET /api/definitions, POST /api/definitionsExport/import everything
Health: alarmsGET /api/health/checks/alarms200 ok, 503 on alarm
Health: vhostsGET /api/health/checks/virtual-hosts
Health: quorum criticalGET /api/health/checks/node-is-quorum-critical
bash
curl -u guest:guest -H 'content-type: application/json' \
  -X PUT http://localhost:15672/api/queues/%2F/jobs \
  -d '{"durable":true,"arguments":{"x-queue-type":"quorum"}}'

Exchange types and bindings ​

TaskCommand/ConfigNotes
Default exchange"" (nameless, direct)Routing key equals queue name; every queue is bound implicitly
directexact match on routing keyamq.direct
fanoutignores routing keyamq.fanout; broadcast
topicwords split by .; * = exactly one word, # = zero or moreamq.topic; key max 255 bytes
headersbind with x-match = all or anyAlso all-with-x / any-with-x variants; routing key ignored
Consistent hashtype x-consistent-hashPlugin; routing key hashed, binding key is a weight
Delayed messagetype x-delayed-message, header x-delay (ms)Plugin rabbitmq_delayed_message_exchange, no longer maintained; also set arg x-delayed-type; quorum queues get native delay from 4.4
Exchange to exchangeexchange.bindChain routing topologies
Alternate exchangearg alternate-exchange (policy or declare arg)Catches unroutable messages
Durable / auto-delete / internaldeclare flagsInternal exchanges accept only exchange-to-exchange publishes
Mandatory publishbasic.publish flag mandatoryUnroutable returned via basic.return (reply 312 NO_ROUTE)

Queue arguments (x-*) ​

Arguments are fixed at declare time and must match on re-declare. Prefer policies for tunables.

TaskCommand/ConfigNotes
Queue typex-queue-type: classic, quorum, streamCannot be set by policy; per-vhost default type exists
Max length (messages)x-max-lengthPolicy key max-length
Max length (bytes)x-max-length-bytesPolicy key max-length-bytes
Overflowx-overflow: drop-head (default), reject-publish, reject-publish-dlxreject-publish nacks publisher confirms; quorum queues accept drop-head and reject-publish
Message TTLx-message-ttl (ms)Policy message-ttl; expired at head of queue only
Queue TTLx-expires (ms)Deletes unused queue; policy expires
Dead-letter exchangex-dead-letter-exchangePolicy dead-letter-exchange
Dead-letter keyx-dead-letter-routing-keyElse original key is kept
Dead-letter strategyx-dead-letter-strategy: at-most-once, at-least-onceQuorum queues; at-least-once needs reject-publish overflow
Single active consumerx-single-active-consumer: trueOne consumer receives; others standby; ordering
Delivery limitx-delivery-limit (quorum)Poison messages dead-lettered after N redeliveries; default 20 in 4.x
Priority (classic)x-max-priority (1-255)Docs recommend 2 to 4 levels; quorum has fixed levels 0-31 (strict from 4.3, two buckets before) and ignores the argument
Initial group sizex-quorum-initial-group-sizeReplica count for new quorum queue
Leader locatorx-queue-leader-locator: client-local, balancedWhere the leader is placed
Stream retentionx-max-age (e.g. 7D), x-max-length-bytesStreams truncate by segment
Stream segment sizex-stream-max-segment-size-bytesDefault 500000000 bytes; policy applies only if it exists at declare time
Exclusivedeclare flag exclusiveConnection-scoped, deleted on close; classic only

Dead-lettering and TTL ​

TaskCommand/ConfigNotes
DLX policyrabbitmqctl set_policy dlx "^work\." '{"dead-letter-exchange":"dlx"}' --apply-to queuesDLX must exist; bind a queue to it
Dead-letter reasonsx-death header reason: rejected, expired, maxlen, delivery_limitHeader also holds count, queue, exchange, routing-keys
Retry via TTLwork queue to DLX to wait queue (x-message-ttl) to work exchangeClassic delayed-retry loop
Per-message TTLproperty expiration = "60000" (string ms)Only head-of-queue expiry; combine with queue TTL carefully
Reject without requeuebasic.nack(requeue=false) or basic.reject(requeue=false)Triggers DLX
Cycle protectionmessage dead-lettered twice for same queue and reason is droppedUnless rejected

Policies ​

TaskCommand/ConfigNotes
Createset_policy NAME PATTERN DEFINITION --apply-to queues|exchanges|all --priority NHigher priority wins (default 0); only one policy applies per entity; --apply-to also takes classic_queues, quorum_queues, streams
Common keysmax-length, max-length-bytes, overflow, message-ttl, expires, dead-letter-exchange, dead-letter-routing-key, delivery-limit, max-age, alternate-exchangeQuote JSON for the shell
Federationfederation-upstream-set, federation-upstreamNeeds rabbitmq_federation
Operator policyset_operator_policyMerged with user policy; more conservative value wins (overflow: operator value)
Not by policyx-queue-type, x-max-priority, x-single-active-consumer, exclusive, durableDeclare-time only

Message properties (basic.properties) ​

TaskCommand/ConfigNotes
Persistencedelivery_mode 2 = persistent, 1 = transientPersistent in a durable queue survives restart; quorum always persists
Identitymessage_id, correlation_idDedup and RPC matching
RPC replyreply_toUse amq.rabbitmq.reply-to for direct reply-to (no queue needed)
ExpiryexpirationString of milliseconds
Headersheaders tableUsed by headers exchange and x-death
Contentcontent_type, content_encodinge.g. application/json
Prioritypriority 0-255Only with x-max-priority
Misctimestamp, type, user_id, app_iduser_id must match the connection user

Confirms, acks, prefetch ​

TaskCommand/ConfigNotes
Publisher confirmsconfirm.select, then wait for basic.ack / basic.nackDurable queues confirm after disk write (quorum: after majority)
Transactionstx.select, tx.commitSlow; prefer confirms
Consumer ackbasic.ack(delivery_tag, multiple)multiple=true acks all up to the tag
Negative ackbasic.nack(tag, multiple, requeue)Rabbit extension; basic.reject is single only
Auto-ackno_ack=true on basic.consumeFast, can lose messages; avoid for work
Prefetchbasic.qos(prefetch_count=N)Limit of unacked per consumer; docs: 100-300 usually gives optimal throughput, 1 is most conservative
Global prefetchglobal=trueQuorum queues do not support it: consuming from one on such a channel is a channel error; per-consumer is the default in RabbitMQ
Consumer timeoutconsumer_timeout = 1800000Ack deadline in ms (30 min default); consumer cancelled if the client supports cancel notifications, otherwise channel closed with PRECONDITION_FAILED
Recoverbasic.recover(requeue=true)Redeliver unacked on the channel
Pull onebasic.getPolling; avoid in loops
Heartbeatheartbeat = 60Seconds; detects dead TCP

Quorum vs classic vs stream ​

TaskCommand/ConfigNotes
Pick for work queuesquorumRaft replicated, safe default since 4.0; classic mirroring was removed
Pick for transient/smallclassicNon-replicated, lowest overhead; exclusive and priority queues
Pick for fan-out replaystreamAppend-only log, non-destructive reads, offsets
Replicationclassic: none; quorum: Raft (odd count); stream: Raft-like replicasQuorum needs majority alive
Consumptionclassic and quorum remove on ack; stream keeps until retentionStream consumers use x-stream-offset
Poison messagesquorum x-delivery-limit; others manual
Priority, exclusiveclassic: x-max-priority, exclusive; quorum: priority 0-31, never exclusiveQuorum queues must be durable and cannot be exclusive
Declarex-queue-typeDefault via default_queue_type vhost setting
Stream consumebasic.qos required, ack, plus x-stream-offset: first, last, next, number, timestampOr use the stream protocol on 5552

Clustering, federation, shovel ​

TaskCommand/ConfigNotes
Join clusterrabbitmqctl stop_app; rabbitmqctl reset; rabbitmqctl join_cluster rabbit@node1; rabbitmqctl start_appSame Erlang cookie everywhere
Leaverabbitmqctl stop_app; rabbitmqctl reset
Remove dead noderabbitmqctl forget_cluster_node rabbit@deadFrom a live node
Cluster namerabbitmqctl set_cluster_name prod
Partition handlingcluster_partition_handling = pause_minorityBefore 4.3 only; strategies were removed with Mnesia and the key has no effect; prefer odd node counts
Rolling upgradestop, upgrade, start one node at a time; then enable_feature_flag allCheck check_if_node_is_quorum_critical first
Federation upstreamrabbitmqctl set_parameter federation-upstream up1 '{"uri":"amqp://h2"}'Plugin rabbitmq_federation; loose WAN links
Federation policyset_policy fed "^fed\." '{"federation-upstream-set":"all"}' --apply-to exchanges
Static shovelshovel plugin in advanced.configMove messages between brokers
Dynamic shovelrabbitmqctl set_parameter shovel s1 '{"src-protocol":"amqp091","src-uri":"amqp://","src-queue":"a","dest-protocol":"amqp091","dest-uri":"amqp://h2","dest-queue":"b"}'Plugin rabbitmq_shovel

Monitoring ​

TaskCommand/ConfigNotes
Queue depthmessages_ready, messages_unacknowledged, messagesAlert on ready growing and consumers 0
Prometheus scrapeGET :15692/metricsPer-object: /metrics/detailed?family=queue_coarse_metrics (names get prefix rabbitmq_detailed_)
Key metricsrabbitmq_queue_messages_ready, rabbitmq_queue_messages_unacked, rabbitmq_connections, rabbitmq_channelsConfirm exact names with curl on your version
Memory alarmnode blocks publishing connections at the watermarkcheck_local_alarms; /api/nodes mem_alarm
Disk alarmpublishers blocked below disk_free_limitdisk_free_alarm
File descriptorsfd_used vs fd_totalRaise ulimit -n
Publish rate vs ack rate/api/overview message_statsGap means a backlog is forming
Blocked connectionsstate blocked / blockingFlow control or alarm
Grafanaofficial RabbitMQ dashboardsUse with the Prometheus plugin

Common errors ​

TaskCommand/ConfigNotes
406 PRECONDITION_FAILEDredeclare with different arguments, ack unknown tag, or consumer timeoutMake args identical or delete the queue; use policies for tunables
404 NOT_FOUNDpublish or bind to missing exchange/queue, or wrong vhostDeclare first; check vhost
403 ACCESS_REFUSEDno permission on vhost/resourceset_permissions
405 RESOURCE_LOCKEDexclusive queue used by another connection
320 CONNECTION_FORCEDbroker closed it (shutdown, close_connection, admin)Reconnect with backoff
311 CONTENT_TOO_LARGEmessage exceeds max_message_size (default 16 MiB, hard max 512 MiB)Send a reference instead
312 NO_ROUTEmandatory publish with no matching bindingHandle basic.return
501 FRAME_ERROR / 503 COMMAND_INVALIDprotocol misuseClient bug
504 CHANNEL_ERRORoperation on wrong channel stateDo not share channels across threads
530 NOT_ALLOWEDe.g. invalid arguments, feature not allowedRead the reply text
connection blockedmemory or disk alarmFree resources; see monitoring

Go: amqp091-go ​

go
conn, err := amqp.Dial("amqp://app:s3cret@localhost:5672/orders")
if err != nil { log.Fatal(err) }
defer conn.Close()
ch, _ := conn.Channel()
defer ch.Close()

_, _ = ch.QueueDeclare("jobs", true, false, false, false,
    amqp.Table{"x-queue-type": "quorum", "x-delivery-limit": 5})
_ = ch.Confirm(false)

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", "jobs", true, false,
    amqp.Publishing{
        DeliveryMode: amqp.Persistent,
        ContentType:  "application/json",
        MessageId:    "m-1",
        CorrelationId: "c-1",
        Expiration:   "60000",
        Body:         []byte(`{"id":1}`),
    })
if err == nil { ok, _ := dc.WaitContext(ctx); _ = ok }

_ = ch.Qos(20, 0, false) // prefetch per consumer
msgs, _ := ch.Consume("jobs", "", false, false, false, false, nil)
for d := range msgs {
    if err := handle(d.Body); err != nil {
        _ = d.Nack(false, false) // dead-letter or drop
        continue
    }
    _ = d.Ack(false)
}
TaskCommand/ConfigNotes
Reconnectconn.NotifyClose(make(chan *amqp.Error, 1))Automatic recovery is opt-in via amqp.Config.Recovery; otherwise rebuild conn, channel, topology
Returned messagesch.NotifyReturn(make(chan amqp.Return, 1))For mandatory publishes
Channel per goroutineone channel per publisher/consumer goroutineChannels are not goroutine-safe for concurrent publish
Blockedconn.NotifyBlocked(...)Alarm backpressure
Heartbeat/configamqp.DialConfig(url, amqp.Config{Heartbeat: 30*time.Second})

Laravel: laravel-queue-rabbitmq ​

Package vladimir-yuldashev/laravel-queue-rabbitmq; set QUEUE_CONNECTION=rabbitmq.

php
// config/queue.php
'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', '/'),
    ]],
    'options' => ['queue' => [
        'exchange' => 'application-x',
        'exchange_type' => 'topic',
        'exchange_routing_key' => '',
        'reroute_failed' => true,
        'failed_exchange' => 'failed-exchange',
        'prioritize_delayed' => false,
        'queue_max_priority' => 10,
    ]],
],
TaskCommand/ConfigNotes
Run worker (multi-queue)php artisan queue:work rabbitmq --queue=a,bUses basic_get
Run worker (fast)php artisan rabbitmq:consume rabbitmq --queue=aUses basic_consume, about 2x faster, one queue
Declare topologycreate queues and bindings yourself when using exchangesREADME: with routing keys you create bindings
Custom job classoptions.queue.job = your class extending RabbitMQJob
TLSoptions.ssl_options (cafile, local_cert, local_key, verify_peer)Plus secure flag; see README
Delayed jobs->delay(60)Mechanism not documented in the README (it has a prioritize_delayed option)

References ​

Built by Morteza Negahi