Skip to content

Load Testing RabbitMQ: Where the Queue Breaks

How RabbitMQ degrades under load, what to measure, and a copy-paste Locust file that reports publish latency, consume rate and end-to-end latency.

A publisher feeding a RabbitMQ queue where unacknowledged messages stack up behind a slow consumer while a memory alarm blocks the publisher

A RabbitMQ load test that only counts publishes tells you almost nothing. The broker accepts messages happily long after the system behind it has stopped keeping up, so the producer side stays green while the real problem grows in the queue. A useful test watches both ends: how long a publisher waits, and how long a message waits before a consumer sees it.

This post explains how RabbitMQ typically fails under load, which numbers expose each failure, and gives you a single Locust file you can run on MaxoPerf against your own broker.

How RabbitMQ fails under load

Four failure modes cover most of what goes wrong. None of them needs exotic traffic. They appear when offered load passes what the slowest part of the path can sustain.

Unacknowledged messages pile up behind a slow consumer

A consumer receives messages and acknowledges them once it has handled them. Until then the broker counts them as unacknowledged and keeps them in memory so it can redeliver. The prefetch limit decides how many one consumer may hold. If the consumer is slower than the producers, ready messages stack up in the queue, and each consumer sits on a full prefetch window of unacknowledged ones.

The queue depth is the symptom. The measurement that shows it earliest from the outside is end-to-end latency: the age of a message when a consumer finally gets it. It rises steadily across the run. Publish latency can stay flat the whole time, which is why a publish-only test misses this.

Memory and disk alarms block publishers

When the broker crosses its memory or free-disk threshold, it raises an alarm and blocks publishing connections. Publishers do not get an error. Their publish calls simply stop returning until the alarm clears. This is flow control, and it is the broker protecting itself.

From the test’s point of view the signature is a send latency that jumps from milliseconds to seconds, or send throughput that drops to zero while the consumers keep draining. A test that does not use publisher confirms can hide it, because the client writes to its socket buffer and moves on. That is why the file below turns confirms on.

Quorum queue replication adds latency

Quorum queues replicate every message to a majority of nodes before confirming it. That is the point of them: they survive a node loss without losing acknowledged messages. The cost is paid on every publish. Compared with a classic queue, send latency is higher and it is more sensitive to network latency between nodes and to slow disks.

If you plan to run quorum queues in production, test quorum queues. A load test on a classic queue says little about them. The how-to page shows the one-line change.

Too many connections and channels

Each connection costs the broker memory and file descriptors, and each channel adds more. A fleet of clients that each open a connection per task, or channels that are never closed, can exhaust limits long before throughput becomes the issue. Failures here look like refused connections or ACCESS_REFUSED and resource_limit errors rather than slow responses.

Your test should open connections the way your real clients do. The file below gives every virtual user its own connection and channel, so raising the user count raises the connection count, and you see the broker’s behaviour at that scale.

What to measure

Three numbers, in this order of importance:

  1. End-to-end latency: the time from creating a message to a consumer receiving it. It is the number users of the queue actually feel. A flat line is healthy. A line that climbs for the whole run means consumers are losing.
  2. Consume rate: messages per second reaching consumers. Compare it with the publish rate. If it is lower for long, a backlog is building.
  3. Publish latency: how long a publisher waits for the broker to confirm. It moves when the broker is under pressure or blocked by an alarm.

MaxoPerf reports these as two result labels, rabbitmq send and rabbitmq end-to-end. The number of rabbitmq end-to-end samples per second is the consume rate.

The locustfile

The file below runs producers and consumers in one test. Producers publish persistent messages with publisher confirms. Consumers read, acknowledge and record how old each message was. Before you run it, bind the broker’s AMQP URL as a secret named SECRET_RABBITMQ_URL.

locustfile.py
"""RabbitMQ load test for MaxoPerf: producers publish, consumers measure end-to-end latency.
Connection values come from MaxoPerf secrets bound to this test (Dependencies tab)."""
import json, os, time, uuid
import pika
from gevent import sleep
from locust import User, task, events, constant, constant_throughput
# --- connection (bind as a secret; the default works against a local broker) ---
URL = os.environ.get("SECRET_RABBITMQ_URL", "amqp://guest:guest@localhost:5672/%2F")
# --- names + load knobs (edit freely; not secrets: secret values are masked in run output) ---
QUEUE = "maxoperf-load"
SENDS_PER_USER_PER_SEC = 10 # producer rate per virtual user
MESSAGE_BYTES = 512 # payload size
CONSUMERS = 2 # fixed consumer users (Locust fixed_count)
PREFETCH = 100 # unacked messages a consumer may hold
STALE_AFTER_S = 60 # skip leftovers from earlier runs (durable queue keeps them)
STARTED = time.time()
def record(name, start, exc=None, size=0): # one result sample under "rabbitmq <name>"
if exc is not None: # bzt's results CSV cannot escape commas or quotes in error text
exc = Exception(str(exc).replace(",", ";").replace('"', "'"))
events.request.fire(request_type="RABBITMQ", name=f"rabbitmq {name}",
response_time=(time.time() - start) * 1000,
response_length=size, exception=exc, context={})
class Rabbit(User):
abstract = True
conn = None
def channel(self): # lazy connect: an unreachable broker becomes failed samples, not a crash
if self.conn is None:
params = pika.URLParameters(URL)
params.heartbeat = 600 # pika only services heartbeats inside its own calls
self.conn = pika.BlockingConnection(params)
ch = self.conn.channel()
ch.queue_declare(QUEUE, durable=True) # idempotent while arguments match
self.setup(ch)
self.ch = ch
return self.ch
def drop(self):
try:
self.conn.close()
except Exception:
pass
self.conn = None
def on_stop(self): # bzt gives teardown --stop-timeout=10 s
if self.conn is not None:
self.drop()
class Producer(Rabbit): # "rabbitmq send" = publish call until the broker confirms
wait_time = constant_throughput(SENDS_PER_USER_PER_SEC)
def setup(self, ch):
ch.confirm_delivery()
@task
def send(self):
start = time.time()
try:
ch = self.channel()
start = time.time() # exclude connect time
body = json.dumps({"id": str(uuid.uuid4()), "sent_at": time.time(),
"pad": "x" * MESSAGE_BYTES}).encode()
ch.basic_publish("", QUEUE, body, pika.BasicProperties(delivery_mode=2))
record("send", start, size=len(body))
except (pika.exceptions.AMQPError, OSError) as e: # incl. UnroutableError / NackError
self.drop()
record("send", start, e)
class Consumer(Rabbit): # "rabbitmq end-to-end" = now - sent_at for every message read
fixed_count = CONSUMERS
wait_time = constant(0)
messages = None
def setup(self, ch):
ch.basic_qos(prefetch_count=PREFETCH)
self.messages = ch.consume(QUEUE, inactivity_timeout=0.5)
@task
def receive(self):
start = time.time()
try:
self.channel()
method, _, body = next(self.messages)
if method is None: # idle: nothing arrived within 0.5 s
return
sent_at = json.loads(body)["sent_at"]
self.ch.basic_ack(method.delivery_tag)
if sent_at >= STARTED - STALE_AFTER_S:
record("end-to-end", sent_at, size=len(body))
except (pika.exceptions.AMQPError, OSError) as e: # StopUser (run over) must pass through
self.drop()
record("end-to-end", start, e)
sleep(1) # do not spin while the broker is down

Upload it together with this taurus.yml, which runs the Locust file and installs the client at test start:

taurus.yml
execution:
- executor: locust
scenario: mq
scenarios:
mq:
script: locustfile.py
services:
- module: pip-install
packages:
- pika==1.5.0

A few choices in the file are deliberate:

  • The queue is declared durable and the declaration is idempotent, so you can rerun the test.
  • Messages older than 60 seconds at the start of the run are skipped. A durable queue keeps the backlog of previous runs, and counting it would report latencies that belong to an earlier test.
  • Only the connection value is a secret. The queue name and the load knobs are constants, because MaxoPerf masks bound secret values in run output.
  • Locust runs on gevent, and pika’s blocking adapter uses plain sockets, so every virtual user stays cooperative.

Run it on MaxoPerf

  1. Create a test and upload locustfile.py. MaxoPerf detects Locust from the file.
  2. Bind SECRET_RABBITMQ_URL on the test’s Dependencies tab.
  3. Choose the number of users and a duration. Two users are consumers; the rest are producers.
  4. Start the run. If your broker is inside a private network, run it on a private datacenter outpost.
  5. Open the results and compare the two labels.

The how-to page has the secret table, screenshots of each step and a troubleshooting table.

What to look for

Start with a short run at a low rate and confirm that both labels have samples and zero failures. Then raise the publish rate in steps and watch for these patterns.

  • End-to-end latency climbs and the end-to-end sample count falls behind sends. The consumers are the bottleneck. Add consumers, raise prefetch, or speed up the work they do. In the file, change CONSUMERS and PREFETCH.
  • Send latency jumps by orders of magnitude or sends stall. Look at the broker for a memory or disk alarm and for blocked connections.
  • Send latency is steadily high with a quorum queue. That is replication cost. Check inter-node latency and disk speed before blaming the client.
  • Connection errors at higher user counts. Check connection limits, file descriptor limits and any proxy in front of the broker.
  • A failed row with no name. An exception inside the script. The run logs have the traceback.

One caution about reading the numbers. MaxoPerf records samples in whole milliseconds, so a broker on a fast local network can show 0 or 1 ms for sends. And when you spread the test over several runners, each runner has its own clock, so end-to-end latency includes any clock difference between publisher and consumer. Use the trend within a run rather than the absolute value when clocks are not tightly synchronised.

Test only what you own

Load against a production broker affects everyone sharing it. Use a dedicated vhost and queue, agree the load with the people who run the broker, and read Message queue testing: do and don’t before the first run.

Next step

Copy the file, point it at a test broker and run the first short test. The RabbitMQ how-to walks through each step. When you outgrow one runner, run the same file across several and compare the end-to-end trend.