AlgoViz

RabbitMQ

medium 32 min

RabbitMQ is an open-source message broker.

Video lesson · Chapter 1 of 5

An invoice has to reach its queue

0:00 / 4:04

RabbitMQ in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

RabbitMQ is a program that takes messages from some applications and delivers them to others. Such a program is called a message broker. Its special strength is routing: a sender does not choose a queue, it describes the message with a routing key, and rules inside the broker decide where copies go.

Those rules are exchanges and bindings. An exchange receives messages. A binding connects it to a queue, perhaps with a pattern. A queue stores messages in order until a consumer takes one and reports, with an acknowledgement, that it is finished.

It speaks several protocols: AMQP 1.0 and AMQP 0-9-1 in the core, its own stream protocol, MQTT and STOMP through plugins that ship with it, and WebSocket variants for browsers. It also has an HTTP interface for management, which is not meant for heavy messaging.

Why it exists

Work that a user need not wait for should be handed over: send the e-mail, resize the picture, charge the card, tell the warehouse. The sender wants to be sure the request is safe, and the workers want it one at a time, at their own speed, with another try when something fails.

When several services care about the same event, the sender should not keep a list of them. With an exchange, a new service binds its own queue and the sender never changes.

A short history

  1. 2007

    RabbitMQ is first released by Rabbit Technologies, a joint venture of LShift and CohesiveFT, as an open-source AMQP broker.

  2. April 2010

    SpringSource, a division of VMware, acquires it. Today it is developed at Broadcom, which owns VMware.

  3. September 2024

    The 4.0 series: AMQP 1.0 is a core protocol, mirrored classic queues are gone, and quorum queues get a default delivery limit of 20.

  4. April 2026

    RabbitMQ 4.3: Khepri, based on Raft, is the only metadata store. Quorum queues get delayed retries and 32 strict priorities.

  5. October 2026

    RabbitMQ 4.4: publishers can delay a message in a quorum queue. Facts on this page are from its documentation.

Words to know

Exchange
Receives messages and routes copies of them.
Binding
A rule from an exchange to a queue, a stream or another exchange.
Routing key
A short text on the message, often words with dots.
Acknowledgement
The consumer's message that the work is done, so the queue may delete.
Publisher confirm
The broker's message that it has accepted what was published.
Prefetch
How many unacknowledged messages one consumer may hold.
Quorum queue
A queue copied to several nodes with the Raft protocol.
Dead-letter exchange
Where a queue sends messages that were rejected, expired, overflowed or failed too often.
Virtual host
A named space with its own exchanges, queues and permissions.
Channel
A light session inside one connection, in AMQP 0-9-1.

How it works

Step through the idea, or press Play.

Step 1 of 3

Publish. To an exchange, with a routing key, and wait for the confirm

Understand it

Start here

The pneumatic-tube post room

Imagine an old office with a tube post: capsules blown through pipes. A clerk does not walk to the departments. Each capsule wears a coloured ring, and a sorting box reads the ring.

Capsules and rings
SORTINGBOXBILLINGSHIPPINGRECORDSInto the box

The sender knows rings, not trays. Trays can be added without telling anyone.

General ideas have their own pages: queues (receipts, dead letters, competing consumers), publish and subscribe, push and pull, retries and idempotency. Here we look at the product.

Purpose

What it is good for

  • Flexible routing

    Exact keys, patterns, broadcast or headers, as configuration instead of code.

  • Prompt delivery

    The broker pushes a message as soon as a consumer has room. Measure the latency on your own network and queue type.

  • Careful delivery

    Publisher confirms, acknowledgements, limits on redelivery and dead letters.

  • Many protocols

    AMQP 1.0, AMQP 0-9-1, MQTT, STOMP and streams on one broker, so devices and services can meet.

Typical uses: background jobs, request and reply between services, event routing, urgent-first queues, delayed messages, and IoT devices over MQTT. The licence is the open-source Mozilla Public License 2.0; commercial support is sold separately.

Architecture

Publisher, exchange, binding, queue, consumer

One message, three queues

An order service publishes a message with key order.created.us to a topic exchange on a RabbitMQ node. Bindings order.created.*, order.*.us and order.# put a copy into the billing, us-shipping and audit queues, each with its own consumer.
All three patterns match, so three copies are stored. Each queue then works on its own.

The parts

PartJobNote
PublisherSends to an exchange with a key and propertiesHolds one long-lived connection
ExchangeFinds matching bindingsStores nothing
BindingConnects, perhaps with a patternMany per queue are fine
QueueKeeps messages in order until acknowledgedFirst in, first out, except for priorities and redeliveries
ConsumerReceives, works, acknowledgesMany on one queue share the work
Virtual hostSeparates tenants or environmentsA namespace with permissions; hardware is shared

Routing

Four kinds of exchange

TypeRuleExampleUse
DirectKey equals binding keyerror to the error queueTasks by type, logs by severity
TopicPatterns: * one word, # zero or moreorder.*.us, order.#Events in a hierarchy, regions
FanoutKey ignored, all bound queuesA price change for every serviceBroadcast
HeadersNamed headers; x-match all or anytype pdf and size largeSeveral attributes at once
Plugins add more, such as a consistent-hash exchange that spreads messages over queues.

Which exchange?

Topic patterns against keys

Patternorderorder.createdorder.created.usorder.created.shipped.us
order.*noyesnono
order.*.usnonoyesno
order.#yesyesyesyes
#.usnonoyesyes

Storage

Classic queues, quorum queues and streams

Classic queueQuorum queueStream
CopiesOne nodeSeveral nodes, RaftSeveral nodes
After consumingDeleted on ackDeleted on ackKept until retention
Many readers of one messageNo, one consumer gets itNo, one consumer gets itYes, each at its own offset
Failed-delivery limitNoYes, 20 by defaultNot applicable
Good forTemporary or exclusive queues, data you can loseOrders, payments, jobsFan-out to many, replay, long backlogs
Mirrored classic queues were removed in 4.0. "Lazy" mode is history too: classic queues now keep little in memory by design. Choose the type with x-queue-type.

A quorum queue has a leader and followers, by default three members in all. A message is confirmed when a majority has it. If the leader's node dies, the others elect a new one. Message bodies are kept on disk, not in memory. Quorum queues are always durable, and cannot be exclusive or server-named.

Majority and losses

m=⌊n2⌋+1n=3:m=2, lose 1n=5:m=3, lose 2m = \left\lfloor \frac{n}{2} \right\rfloor + 1 \qquad n = 3: m = 2,\ \text{lose } 1 \qquad n = 5: m = 3,\ \text{lose } 2
A fourth member adds work and no tolerance: n=4n = 4 also survives one loss. So use 3 or 5.

A stream is an append-only log, like a Kafka partition. Super streams split it into partitions. Streams complement queues: they bring replay to RabbitMQ, with their own protocol for the best speed.

The path

From publish to acknowledge

At least once, end to end

If the consumer's connection closes before its ack, the broker delivers the message again.
  1. 1

    Publish

    Key, body and properties: content type, delivery mode, message id, headers.

  2. 2

    Match

    The exchange evaluates its bindings and places a copy in each matching queue.

  3. 3

    Store and confirm

    Classic, durable and persistent: after it is on disk. Quorum: after a majority has it. With several queues, after all of them.

  4. 4

    Deliver

    The broker pushes within the prefetch. Each message goes to one consumer of the queue.

  5. 5

    Acknowledge

    ack deletes. nack or reject either requeues or, with requeue false, dead-letters or drops.

  6. 6

    Fail safely

    Rejected, expired, overflowing and endlessly redelivered messages go to the dead-letter exchange.

Where can a message get lost?

GapClosed by
Between publisher and brokerPublisher confirms and a resend
No binding matchesMandatory flag or alternate exchange
The node restartsDurable queue, persistent message
The node is lostQuorum queue
The consumer crashesManual acknowledgement after the work
The work always failsDelivery limit and dead-letter exchange
The dead-letter hop itselfAt-least-once dead-lettering, a quorum queue option

Speed

Confirms, prefetch and connections

Confirms can be awaited one by one (simple, slow), for a batch (better, but an error means resending the batch), or handled as they arrive (fastest, a bit more code). Consumer acks can also cover several messages at once.

A first guess for prefetch

n≈1+round tripwork time=1+40 ms4 ms=11n \approx 1 + \frac{\text{round trip}}{\text{work time}} = 1 + \frac{40 \text{ ms}}{4 \text{ ms}} = 11
Assumed numbers, one worker thread. With prefetch 1 it does one message per 44 ms, about 23 a second. With 11 the network is hidden: 250 a second.

Long jobs of uneven size want a prefetch of 1 or 2, so nobody hoards. Short jobs want more: the documentation finds 100 to 300 usually best for throughput. Set it per consumer; quorum queues refuse the older per-channel form.

How many consumers?

c=⌈400/s×0.05 s0.7⌉=⌈28.6⌉=29c = \left\lceil \frac{400/\text{s} \times 0.05 \text{ s}}{0.7} \right\rceil = \lceil 28.6 \rceil = 29
400 messages a second at the peak, 50 ms of work each, workers 70% busy. All assumed; put in your own.
  • One connection, many channels

    A connection costs TCP, TLS and login. Keep it open; give each thread its own channel. Separate connections for publishing and consuming, so a blocked publisher does not stop acks.

  • Heartbeats

    The suggested timeout is 60 seconds. They find dead peers that TCP has not noticed.

  • One queue, one leader

    All traffic of a queue passes through its leader. For more, use several queues, for example with a consistent-hash exchange, and lose the order between them.

Failure

Dead letters and retries

A queue with a dead-letter exchange passes on a message when it is rejected without requeue, when its time to live ends, when the queue overflows, or when a quorum queue's delivery limit is passed. Headers record where it came from, why, and how often.

Retrying at once often makes trouble worse. There are two ways to wait:

A ladder of waiting queues

Each waiting queue has a time to live and dead-letters back to the main queue through its own exchange or key. The consumer keeps a count in a header. Longest wait in all: 36 minutes.

Two ways to delay a retry

Waiting queuesDelayed retry of quorum queues
NeedsAny version, one queue per delayRabbitMQ 4.3 or later
DelaysAny steps you likeLinear: minimum times the delivery count, up to a maximum
CountingYour headerThe broker's delivery count
Watch outPublish the copy and wait for the confirm before you ack the originalbasic.reject counts as a failure; since 4.3 basic.nack with requeue does not

Delayed retry

d=min⁡(dmin⁡×count, dmax⁡)60 s:1,2,3,… min, at most 30d = \min(d_{\min} \times \text{count},\ d_{\max}) \qquad 60 \text{ s}: 1, 2, 3, \dots \text{ min, at most } 30
Set the delivery limit to say how many attempts you pay for. After it the message is dead-lettered, or dropped if there is no dead-letter exchange.

Protection

Back-pressure and limits

Who slows whom?

The alarm blocks publishing connections in the whole cluster. Consumers go on, which empties the queues.

Limits and defaults in 4.4

WhatDefaultComment
Memory alarm60% of detected RAMvm_memory_high_watermark.relative
Disk alarm50 MB freeFine for a laptop only; raise it a lot in production
Largest message16 MiBMay be raised to 512 MiB; better to send a link
Delivery limit, quorum20x-delivery-limit
Ack timeout, quorum30 minutesThen the message returns to the queue
Heartbeat60 secondsAgreed by both sides
Stream segment500 MBOne file of a stream
Ports5672, 15672, 15692AMQP, management, Prometheus

Do not wait for the alarm. Give each queue a length limit and choose what happens at the limit: drop the oldest (the default), or reject-publish, which tells the publisher no. Old messages can expire with a time to live.

Cluster

Several nodes

Three nodes, two quorum queues

Clients connect through a load balancer to a RabbitMQ cluster of three nodes. Node 1 holds the leader of the billing queue and a follower of audit, node 2 the leader of audit and a follower of billing, node 3 followers of both.
Any node accepts a client and forwards to the leader of the queue. Leaders copy to followers, which is not drawn.

Every node knows all exchanges, bindings and users. Queue contents are copied only by quorum queues and streams; a classic queue lives on one node. Three nodes in three zones of a region are the usual start. Spread leaders with the balanced leader locator, or rabbitmq-queues rebalance later.

Patterns

Common designs

PatternHowNote
Work queueOne queue, many consumersLow prefetch for long jobs
EventsTopic exchange, one queue per serviceA new service binds its own queue
Request and replyDirect reply-to and a correlation idConsider RPC if the caller waits anyway
Urgent firstPriorities: 32 levels in quorum queues, up to 255 in classicKeep few levels; prefetched messages are already gone
Laterx-opt-delivery-time on quorum queues, since 4.4The separate delayed-message plugin was archived in September 2026
Strict order with a spareSingle active consumerThe next consumer takes over

Operations

Run it

What to watch

SignalHealthyWhen it is not
Ready messages, and their ageShort and fallingAdd or speed up consumers
Unacknowledged messagesAbout consumers times prefetchWork hangs, or acks are missing
Publish rate and ack rateEqual over timeA backlog is growing
Unroutable messages0A binding is missing
Redeliveries, dead-letter lengthNear 0Failing work: read the dead letters
Memory, disk, file descriptorsFar from limitsAlarms are next
Connections and channels, opened per secondStableA client opens one per message
Quorum members onlineAllOne more loss may stop the queue
Scrape the Prometheus plugin on port 15692. Before production: several nodes, TLS, own users with small permissions, the guest account unused, definitions in version control, and a load test with PerfTest.

RabbitMQ is happiest when queues are nearly empty. A long backlog is a sign, or a job for a stream. Upgrade node by node, one release series at a time as the release notes allow: community support for a series is short.

Decide

When to choose it, and when not

Choose RabbitMQ

  • Routing by key, pattern or header
  • Job queues with acks and retries
  • Request and reply, priorities, delays
  • MQTT, STOMP and AMQP together
  • Prompt push delivery
  • On your own machines or any cloud

Choose something else

  • Long history with many readers: Kafka, or a stream here
  • Event sourcing as the record of truth
  • One ordered flow beyond what one leader can carry
  • No wish to operate anything: SQS or another managed queue
  • Files: object storage with a link

Neighbours

RabbitMQKafkaAmazon SQSRedis Pub/Sub
ModelExchanges and queues, plus streamsPartitioned logManaged queueChannels, nothing stored
DeliveryPushPullPollPush
After readingDeleted on ack (queue)StaysDeleted by the consumerNever stored
GuaranteeAt least onceAt least once; exactly once inside KafkaAt least once; FIFO removes duplicates in a windowAt most once
RoutingRichTopic and keyNone in the queue itselfChannel names and patterns
Message size16 MiB, adjustableAbout 1 MB, adjustable1 MiBNot its purpose
You payMachines and peopleMachines and peoplePer requestMachines
Apache Pulsar mixes queues and streams with built-in multi-tenancy and geo-replication, over a separate storage layer. Throughput depends on size, copies and hardware, so benchmark instead of quoting a rate. See Kafka.

Summary

The whole topic in one minute.

RabbitMQ separates sending from storing. Publishers name an exchange and a key, bindings pick the queues, and each queue gives each message to one consumer until it is acknowledged. Direct, topic, fanout and headers exchanges cover most routing without code.

For work that must not be lost use quorum queues, persistent messages, publisher confirms, manual acks and a dead-letter exchange, and expect duplicates. Set prefetch and length limits, watch queue length and alarms, and choose a log such as Kafka, or a RabbitMQ stream, when many readers need the history.

  • Publish to an exchange; bindings choose the queues.
  • Direct is exact, topic has patterns, fanout is everyone, headers look at attributes.
  • Quorum queues copy with Raft; three members survive one loss.
  • Confirms protect the sending side, acks the working side, dead letters the line.
  • Wait before retrying, count attempts, and expect duplicates.
  • Set prefetch and length limits; keep queues short.

Sources